* wesnoth-mode.el (wesnoth-mode-version): Updated.
[wesnoth-mode.git] / wesnoth-mode.el
blobc4a9a67ba9000d001af3a3fe4adff062b0a5ddd0
1 ;;; wesnoth-mode.el --- A major mode for editing WML.
2 ;; Copyright (C) 2006, 2007, 2008 Chris Mann
4 ;; This file is part of wesnoth-mode.
6 ;; This program is free software; you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation; either version 2 of the
9 ;; License, or (at your option) any later version.
11 ;; This program is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;; General Public License for more details.
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with this program; see the file COPYING. If not, write to the
18 ;; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
19 ;; MA 02139, USA.
21 ;;; Description:
22 ;; wesnoth-mode is a major mode for Emacs which assists in the editing
23 ;; of Wesnoth Markup Language (WML) files. Currently, this major-mode
24 ;; features syntax highlighting support, automatic indentation,
25 ;; context-sensitive completion and support for WML checking.
27 ;;; Commentary:
28 ;; Add the following to your .emacs:
29 ;; (add-to-list 'load-path "path/to/wesnoth-mode")
30 ;; (autoload 'wesnoth-mode "wesnoth-mode" "Major mode for editing WML." t)
31 ;; Optionally adding:
32 ;; (add-to-list 'auto-mode-alist '("\\.cfg\\'" . wesnoth-mode))
33 ;; to automatically load wesnoth-mode for all files ending in '.cfg'.
35 ;;; History:
36 ;; 1.3.1
37 ;; * Completion history available is now specific to wesnoth-mode.
38 ;; * Significantly improved performance of completion and WML checking.
39 ;; 1.3.0
40 ;; * Added support for Xemacs.
41 ;; * WML checking is now context sensitive; checks attributes and macros.
42 ;; * WML checks are now always performed on the entire buffer, with results
43 ;; displayed in a temporary buffer.
44 ;; * Context-sensitive completion for attributes and tags.
45 ;; * Completion for built-in and project-specific macros.
46 ;; * Changed the following bindings:
47 ;; `wesnoth-insert-tag' - C-c e -> C-c t
48 ;; `wesnoth-jump-to-matching' - C-c m -> C-c o
49 ;; `wesnoth-check-structure' -> `wesnoth-check-wml' - C-c c
50 ;; * Added the following bindings:
51 ;; `wesnoth-complete-attribute' - C-c a
52 ;; `wesnoth-complete-macro' - C-c m
53 ;; `wesnoth-complete-tag' - C-c t
54 ;; * Removed the following bindings:
55 ;; `wesnoth-check-tag-names' - C-c n
56 ;; * Removed `wesnoth-check-tag-names'. Replaced by `wesnoth-check-wml'.
57 ;; * Completion for an incomplete attribute, tag, or macro at point is
58 ;; attempted via TAB.
59 ;; 1.2.5
60 ;; * Fixed support for GNU Emacs 21.
61 ;; * Added several new tags to `wesnoth-tags-list'.
62 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
63 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
64 ;; how many blocks to wrap across instead of a region.
65 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
66 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
67 ;; causing tags not to be inserted in the correct position.
68 ;; * Fixed highlighting of array indexes as tags.
69 ;; 1.2.4
70 ;; * Improved syntax-highlighting for macro calls.
71 ;; * Underscore is now treated as whitespace.
72 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
73 ;; * Point is now placed at the first non-whitespace character of the line,
74 ;; instead of the last.
75 ;; * Corrected minor indentation bugs.
76 ;; * Indenting across large regions is now much more efficient.
77 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
78 ;; applied.
79 ;; 1.2.3
80 ;; * Now compatible with GNU Emacs 21.4.
81 ;; * Added support for several new tags.
82 ;; * Added menu entry for wesnoth-mode.
83 ;; * Significant speed increase to indentation.
84 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
85 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
86 ;; has been removed.
87 ;; * Trailing whitespace is no longer created when creating a second
88 ;; consecutive newline.
89 ;; * Spurious newlines are no longer created when inserting a tag elements
90 ;; around a region.
91 ;; 1.2.2
92 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
93 ;; `wesnoth-element', `wesnoth-element-opening',
94 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
95 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
96 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
97 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
98 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
99 ;; * Fixed a bug in indentation where content was needed between elements pairs
100 ;; for indentation to work.
101 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
102 ;; `wesnoth-auto-indent-flag'.
103 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
104 ;; * Added indentation styles: `wesnoth-indent-default',
105 ;; `wesnoth-indent-withtags' which implement a a similar indentation
106 ;; style to the existing styles, however all preprocessor statements are
107 ;; indented to the first column.
108 ;; * Added support for several new tags.
109 ;; * Modified `wesnoth-newline' to behave more consistently.
110 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
111 ;; now leaves point at the beginning (when moving backward) or end (when
112 ;; moving forward) of the match.
113 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
114 ;; will now work on preprocessor statements. Will now warn if jump
115 ;; destination may not be correct (due to errors in WML structure).
116 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
117 ;; * `wesnoth-check-structure' can now be applied over an active region and
118 ;; now checks preprocessor statements for correct nesting.
119 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
120 ;; perform indentation by providing a prefix argument.
121 ;; * Indentation styles now leave point at the first non-whitespace character
122 ;; of the line.
123 ;; * `wesnoth-check-tag-names' now reports on success.
124 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
125 ;; * `outline-minor-mode' now works on macro definitions.
126 ;; 1.2.1
127 ;; * Base indent now defaults to 4.
128 ;; * Added support for #ifndef.
130 ;;; Code:
131 (eval-when-compile
132 (require 'cl))
133 (require 'easymenu)
134 (require 'wesnoth-update)
135 (require 'wesnoth-wml-data)
137 (defconst wesnoth-mode-version "1.3.0+git"
138 "The current version of `wesnoth-mode'.")
140 (defgroup wesnoth-mode nil "Wesnoth-mode access"
141 :group 'languages
142 :prefix "wesnoth-")
144 (defcustom wesnoth-auto-indent-flag t
145 "Non-nil means indent the current line upon creating a newline."
146 :type 'boolean
147 :group 'wesnoth-mode)
149 (defcustom wesnoth-indent-savefile t
150 "Non-nil means to use the current indentation conventions.
151 If nil, use the old convention for indentation.
152 The current convention is all attributes are indented a level deeper
153 than their parent; in the past attributes were indented to the same
154 level as their parent.")
156 (defcustom wesnoth-base-indent 4
157 "The number of columns to indent WML."
158 :type 'integer
159 :group 'wesnoth-mode)
161 (defconst wesnoth-preprocessor-regexp
162 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def\\)"
163 "Regular expression to match all preprocessor statements.")
165 (defconst wesnoth-preprocessor-opening-regexp
166 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
167 "Regular expression to match \"opening\" preprocessor statements.")
169 (defconst wesnoth-preprocessor-closing-regexp
170 "[\t ]*#\\(e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\)"
171 "Regular expression to match \"closing\" preprocessor statements.")
173 (defvar wesnoth-define-blocks '()
174 "Cache of all toplevel #define and #enddef pairs.")
176 (defvar wesnoth-history-list '()
177 "History of inserted WML elements.")
179 (defvar wesnoth-mode-hook nil)
181 (defvar wesnoth-mode-map
182 (let ((map (make-sparse-keymap)))
183 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
184 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
185 (define-key map (kbd "C-m") 'wesnoth-newline)
186 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
187 (define-key map (kbd "C-c C-c") 'wesnoth-check-wml)
188 (define-key map (kbd "C-c C-a") 'wesnoth-complete-attribute)
189 (define-key map (kbd "C-c C-t") 'wesnoth-complete-tag)
190 (define-key map (kbd "M-TAB") 'wesnoth-complete-tag)
191 (define-key map (kbd "C-c C-m") 'wesnoth-complete-macro)
192 (define-key map (kbd "C-c C-o") 'wesnoth-jump-to-matching)
193 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
194 (define-key map (kbd "TAB") 'wesnoth-indent-or-complete)
195 map)
196 "Keymap used in `wesnoth-mode'.")
198 (easy-menu-define wesnoth-menu wesnoth-mode-map "Menu for wesnoth-mode"
199 '("WML"
200 ["Check WML" wesnoth-check-wml t]
201 ["Indent or Complete" wesnoth-indent-or-complete t]
202 ["Indent buffer" (lambda ()
203 (interactive)
204 (wesnoth-indent-region (point-min) (point-max))) t]
205 ["Insert Tag" wesnoth-complete-tag t]
206 ["Insert Attribute" wesnoth-complete-attribute t]
207 ["Insert Macro" wesnoth-complete-macro t]
208 ["Jump to Matching" wesnoth-jump-to-matching t]
209 ["Insert Missing Tag" wesnoth-insert-missing-closing t]))
211 (defvar wesnoth-syntax-table
212 (let ((wesnoth-syntax-table (make-syntax-table)))
213 (modify-syntax-entry ?= "." wesnoth-syntax-table)
214 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
215 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
216 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
217 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
218 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
219 wesnoth-syntax-table)
220 "Syntax table for `wesnoth-mode'.")
222 ;; Prevents automatic syntax-highlighting of elements which might be
223 ;; pre-processor statements.
224 (defvar wesnoth-syntactic-keywords
225 (list
226 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
227 '("\\(#[\t ]*.*$\\)" 1 "<"))
228 "Highlighting syntactic keywords within `wesnoth-mode'.")
230 (defvar wesnoth-font-lock-keywords
231 (list
232 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face)
233 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
234 font-lock-keyword-face)
235 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
236 2 font-lock-function-name-face)
237 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face))
238 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face))
239 '("}" . font-lock-function-name-face)
240 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face)
241 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
242 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
243 1 font-lock-variable-name-face))
244 "Syntax highlighting for `wesnoth-mode'.")
246 (defconst wesnoth-element-closing "^[\t ]*\\(\\[/\\|#enddef\\)"
247 "String to use for a closing element.")
249 (defconst wesnoth-element-opening "^[\t ]*\\(\\[[^/]\\|#define\\)"
250 "String to use for an opening element.")
252 (defconst wesnoth-element "^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
253 "String to use for an opening or closing element.")
255 ;;; Insertion and completion
256 (defmacro wesnoth-element-completion (completions prompt partial)
257 "Process completion of COMPLETIONS, displaying PROMPT.
258 PARTIAL is the partial string on which to attempt completion."
259 `(let* ((element (when ,partial (try-completion ,partial ,completions))))
260 (cond ((eq element t)
261 (setq element nil))
262 ((null element)
263 (setq element
264 (completing-read ,prompt ,completions nil nil nil
265 wesnoth-history-list)))
266 ((not (if (listp (car ,completions))
267 (assoc element ,completions)
268 (member element ,completions)))
269 (setq element
270 (completing-read ,prompt ,completions
271 nil nil ,partial
272 wesnoth-history-list))))
273 element))
275 (defun wesnoth-parent-tag ()
276 "Return the name of the parent tag.
277 If the parent is a preprocessor statement, return non-nil.
278 If the element has not parent, return nil.
279 Otherwise, return a string containing the name of the parent tag."
280 (save-excursion
281 (let ((start-point (point)))
282 (when (save-excursion (> (point) (progn (back-to-indentation)
283 (point))))
284 (end-of-line))
285 (when (wesnoth-search-for-matching-tag
286 'search-backward-regexp
287 wesnoth-element-opening 'point-min)
288 (while (wesnoth-search-for-matching-tag
289 'search-backward-regexp
290 wesnoth-element-opening 'point-min)))
291 (unless (= (point) start-point)
292 (beginning-of-line)
293 (when (looking-at
294 "^[\t ]*\\(\\[\\(\\(\\w\\|_\\)+\\)\\]\\|#define\\|#enddef\\)")
295 (let ((parent (match-string-no-properties 1)))
296 (if (string-match wesnoth-preprocessor-closing-regexp parent)
298 (substring parent 1 (1- (length parent))))))))))
300 (defun wesnoth-indent-or-complete (&optional elements)
301 "Indent or complete the line at point, depending on context.
302 ELEMENTS is the number of elements to wrap around if inserting
303 matching tags."
304 (interactive "P")
305 (or elements (setq elements 0))
306 (let ((target nil))
307 (save-excursion
308 (back-to-indentation)
309 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
310 (wesnoth-complete-attribute t))
311 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
312 (wesnoth-complete-tag elements t))
313 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
314 (wesnoth-complete-macro t))
315 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
316 (delete-region (point) (progn (end-of-line) (point)))
317 (wesnoth-insert-missing-closing)
318 (end-of-line))
320 (wesnoth-indent)))
321 (setq target (point)))
322 (goto-char target)))
324 (defun wesnoth-complete-macro (&optional completep)
325 "Complete and insert the macro at point.
326 If COMPLETEP is non-nil, attempt to complete the macro at point."
327 (interactive)
328 (let* ((macro-information (append wesnoth-macro-data
329 wesnoth-local-macro-data))
330 (completions (wesnoth-emacs-completion-formats
331 (mapcar 'car macro-information)))
332 (partial (when completep
333 (save-excursion
334 (back-to-indentation)
335 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
336 (match-string 1)))))
337 (macro (or (wesnoth-element-completion completions "Macro: " partial)
338 partial))
339 (args (cadr (assoc macro macro-information))))
340 (when macro
341 (if partial
342 (progn
343 (delete-region (progn (back-to-indentation) (point))
344 (progn (end-of-line) (point)))
345 (insert "{" macro (if args " }" "}")))
346 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
347 (save-excursion
348 (wesnoth-indent))
349 (when args
350 (forward-char -1)))))
352 (defun wesnoth-complete-attribute (&optional completep)
353 "Insert the attribute at point.
354 If COMPLETEP is non-nil, attempt to complete the attribute at point."
355 (interactive)
356 (let* ((completions (wesnoth-build-completion 2))
357 (partial (when completep
358 (save-excursion
359 (back-to-indentation)
360 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
361 (match-string 1)))))
362 (attribute (or (wesnoth-element-completion completions "Attribute: "
363 partial)
364 partial)))
365 (when attribute
366 (if (and partial completep)
367 (progn
368 (delete-region (progn (back-to-indentation) (point))
369 (progn (end-of-line) (point)))
370 (insert attribute "="))
371 (wesnoth-insert-element-separately attribute
372 (if (string-match "=" attribute)
374 "=")))
375 (save-excursion
376 (wesnoth-indent)))))
378 (defun wesnoth-complete-tag (&optional elements completep)
379 "Complete and insert the tag at point.
380 ELEMENTS is the number of elements to wrap around.
381 If COMPLETEP is non-nil, attempt to complete tag at point."
382 (interactive "P")
383 (or elements (setq elements 0))
384 (let* ((completions (wesnoth-build-completion 1))
385 (partial (when completep
386 (save-excursion
387 (back-to-indentation)
388 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
389 (match-string 1)))))
390 (tag (or (wesnoth-element-completion completions "Tag: " partial)
391 partial)))
392 (let ((closed-p nil))
393 (save-excursion
394 (wesnoth-jump-to-matching)
395 (back-to-indentation)
396 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
397 (string= tag (match-string 1)))
398 (setq closed-p t)))
399 (when completep
400 (delete-region (progn (back-to-indentation) (point))
401 (progn (end-of-line) (point))))
402 (if (and closed-p completep)
403 (progn
404 (wesnoth-insert-and-indent "[" tag "]")
405 (end-of-line))
406 (wesnoth-insert-tag elements tag)))))
408 (defun wesnoth-build-completion (position)
409 "Create a new list for tag completion if necessary.
410 Rebuilding list is required for versions of GNU Emacs earlier
411 than 22. POSITION is the argument passed to `nth' for
412 `wesnoth-tag-data'."
413 (interactive "P")
414 (let* ((parent (wesnoth-parent-tag))
415 (candidates
416 (if (or (stringp parent) (null parent))
417 (nth (1- position) (gethash parent wesnoth-tag-hash-table))
418 (mapcar 'car wesnoth-tag-data))))
419 (wesnoth-emacs-completion-formats candidates)))
421 (defun wesnoth-emacs-completion-formats (candidates)
422 "Return the completions in the correct format for `emacs-major-version'.
423 CANDIDATES is a list of all possible completions."
424 (if (> emacs-major-version 21)
425 candidates
426 (let ((tags '())
427 (iter 0))
428 (dolist (tag candidates)
429 (setq iter (1+ iter))
430 (setq tags (append tags (list (cons tag iter)))))
431 tags)))
433 (defun wesnoth-insert-tag (&optional elements tagname)
434 "Insert the specified opening tag and it's matching closing tag.
435 Both the opening and closing tags will be placed on their own
436 lines with point positioned between them. Completion of tags at
437 the prompt uses `wesnoth-tags-list'.
439 ELEMENTS is specifies the number of following blocks which the
440 tag should wrap around.
442 TAGNAME is the name of the tag to be inserted."
443 (interactive "Ps")
444 (unless tagname
445 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 1)
446 nil nil nil wesnoth-history-list)))
447 (when (or (not elements)
448 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
449 wesnoth-preprocessor-regexp "\\)")))
450 (setq elements 0))
451 (let ((depth 0)
452 (start (save-excursion (forward-line -1) (point)))
453 (end (unless (= elements 0)
454 (wesnoth-nth-pair-position elements))))
455 (wesnoth-insert-element-separately "[" tagname "]")
456 (save-excursion
457 (if end
458 (goto-char (marker-position end))
459 (newline 2))
460 (wesnoth-insert-element-separately "[/" tagname "]")
461 (indent-region start (point) nil))
462 (unless end
463 (forward-line 1)))
464 (wesnoth-indent))
466 (defun wesnoth-nth-pair-position (count)
467 "Return `point' after COUNT number of matching element pairs.
468 COUNT is a positive number representing the number of balanced
469 pairs to move across.
470 `point' is returned as a marker object."
471 (save-excursion
472 (let ((start (point))
473 (failed nil))
474 (if (> (point) (save-excursion (back-to-indentation) (point)))
475 (end-of-line)
476 (beginning-of-line))
477 (while (> count 0)
478 ;; Currently looking-at target tag. Stop here to avoid
479 ;; incorrect nesting.
480 (unless (wesnoth-search-for-matching-tag
481 'search-forward-regexp wesnoth-element-closing 'point-max)
482 (setq count 0)
483 (unless (or (= (point) (point-max))
484 (progn (beginning-of-line)
485 (search-backward-regexp wesnoth-element-closing
486 start t)))
487 (setq failed t)))
488 (and (> (decf count) 0) (forward-line 1)))
489 (if failed
490 (beginning-of-line)
491 (end-of-line))
492 (point-marker))))
494 (defun wesnoth-insert-element-separately (&rest strings)
495 "Concatenate STRINGS and insert them on a line of their own."
496 (let ((create-newline (save-excursion
497 (beginning-of-line)
498 (if (looking-at "^[\t ]*$") nil t))))
499 (when create-newline
500 (if (> (point) (save-excursion (back-to-indentation) (point)))
501 (progn
502 (end-of-line)
503 (newline))
504 (beginning-of-line)
505 (open-line 1)))
506 (insert (apply 'concat strings))))
508 (defun wesnoth-insert-missing-closing (&optional start end)
509 "Insert the next expected closing element at point.
511 START and END define the region to check for missing closing
512 elements. If function `transient-mark-mode' is enabled, the region
513 specified will be used as START and END. Otherwise, START and
514 END will be the minimum and maximum positions of the buffer,
515 respectively."
516 (interactive)
517 (if (and (boundp 'transient-mark-mode)
518 transient-mark-mode
519 mark-active)
520 (setq start (region-beginning)
521 end (copy-marker (region-end)))
522 (setq start (point-min)
523 end (point-max)))
524 (let ((element (wesnoth-check-structure start end)))
525 (if (not element)
526 (error "%s" "Unable to find element to insert")
527 (when (string= element "Unexpected end of file")
528 (error "%s" element))
529 (wesnoth-insert-element-separately element)))
530 (wesnoth-indent)
531 (end-of-line))
533 (defun wesnoth-insert-and-indent (&rest args)
534 "Concatenate and insert the given string(s) before indenting.
536 ARGS is a list of strings to be inserted."
537 (insert (apply 'concat args))
538 (wesnoth-indent))
540 (defun wesnoth-newline (&optional indent)
541 "Indent both the current line and the newline created.
542 If `wesnoth-auto-indent-flag' is nil, indentation will not be
543 performed. Indentation can be forced by setting INDENT to
544 non-nil."
545 (interactive)
546 (save-excursion
547 (when (and (or wesnoth-auto-indent-flag indent)
548 (not (looking-at "^[\t ]*$")))
549 (wesnoth-indent)))
550 (newline))
552 ;;; Movement
553 (defmacro wesnoth-navigate-element (repeat search-function bound)
554 "Move point to the tag in the given direction REPEAT times.
556 SEARCH-FUNCTION is the symbol of the function for searching in
557 the required direction, with BOUND marking the furthest point to
558 search."
559 `(progn
560 (or ,repeat (setq ,repeat 1))
561 (while (> ,repeat 0)
562 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
563 (funcall ,search-function wesnoth-element-opening ,bound t)
564 (back-to-indentation)
565 (decf ,repeat))))
567 (defun wesnoth-forward-element (repeat)
568 "Move point to the end of the next tag.
569 REPEAT is an optional numeric argument. If REPEAT is non-nil,
570 jump forward the specified number of tags."
571 (interactive "p")
572 (if (< repeat 0)
573 (wesnoth-backward-element (abs repeat))
574 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
576 (defun wesnoth-backward-element (repeat)
577 "Move point to the beginning of the previous tag.
578 REPEAT is an optional numeric argument. If REPEAT is non-nil,
579 jump backward the specified number of tags."
580 (interactive "p")
581 (if (< repeat 0)
582 (wesnoth-forward-element (abs repeat))
583 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
585 (defmacro wesnoth-search-for-matching-tag (search-function search-string bound)
586 "Search for the matching tag for the current line.
588 SEARCH-FUNCTION is the name of the function used to perform the search.
589 SEARCH-STRING is a string representing the matching tag type.
590 BOUND is the bound to be passed to the search function."
591 `(let ((depth 1))
592 (when (funcall ,search-function wesnoth-element (funcall ,bound) t)
593 (unless (string-match ,search-string (match-string 0))
594 (while (and (> depth 0)
595 (funcall ,search-function wesnoth-element
596 (funcall ,bound) t))
597 (if (string-match ,search-string (match-string 0))
598 (decf depth)
599 (incf depth)))
600 t))))
602 (defun wesnoth-jump-to-matching ()
603 "Jump point to the matching opening/closing tag."
604 (interactive)
605 (beginning-of-line)
606 (if (looking-at wesnoth-element-opening)
607 (wesnoth-search-for-matching-tag
608 'search-forward-regexp wesnoth-element-closing 'point-max)
609 (end-of-line)
610 (wesnoth-search-for-matching-tag
611 'search-backward-regexp wesnoth-element-opening 'wesnoth-wml-start-pos))
612 (back-to-indentation))
614 (defun wesnoth-wml-start-pos ()
615 "Determine the position of `point' relative to where the actual WML begins.
616 Return the likely starting position of the WML if it is found.
617 Otherwise return nil."
618 (save-excursion
619 (goto-char (point-min))
620 (when (search-forward-regexp wesnoth-element (point-max) t)
621 (beginning-of-line)
622 (point))))
624 (defun first-column-indent-p (point)
625 "Return non-nil if the current line should not be indented.
627 POINT is the position in the buffer to check.
628 CONTEXT represents the type of element which precedes the current element."
629 (or (not (wesnoth-wml-start-pos))
630 (<= (point) (wesnoth-wml-start-pos))
631 (nth 3 (parse-partial-sexp (point-min) point))
632 (looking-at wesnoth-preprocessor-regexp)))
634 (defun wesnoth-indent ()
635 "Indent the current line as WML."
636 (beginning-of-line)
637 (let ((cur-indent 0))
638 (unless (first-column-indent-p (point))
639 (multiple-value-bind (context ref-indent)
640 (wesnoth-determine-context (point))
641 (cond
642 ((eq context 'opening)
643 (if (or (and wesnoth-indent-savefile
644 (not (looking-at wesnoth-element-closing)))
645 (looking-at wesnoth-element-opening))
646 (setq cur-indent (+ ref-indent wesnoth-base-indent))
647 (setq cur-indent ref-indent)))
648 ((eq context 'closing)
649 (if (or (looking-at "^[\t ]*\\[/")
650 (and (not wesnoth-indent-savefile)
651 (not (looking-at wesnoth-element-opening))))
652 (setq cur-indent (- ref-indent wesnoth-base-indent))
653 (setq cur-indent ref-indent))))))
654 (indent-line-to (max cur-indent 0))))
656 (defun wesnoth-within-define (position)
657 "Determine whether point is currently inside a #define block.
658 POSITION is the initial cursor position."
659 (let ((depth 0))
660 (dolist (element (or wesnoth-define-blocks
661 (wesnoth-find-macro-definitions)))
662 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
663 (list position)) '>)) position)
664 (setq depth (max (car element) depth))))
665 depth))
667 (defun wesnoth-find-macro-definitions ()
668 "Return information regarding positioning of macro definitions."
669 (save-excursion
670 (goto-char (point-min))
671 (let ((depth 0)
672 openings cache)
673 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t)
674 (and (string= (match-string 1) "#define") (beginning-of-line))
675 (setq depth
676 (if (string= (match-string 1) "#define")
677 (progn
678 (add-to-list 'openings (point-marker))
679 (1+ depth))
680 (add-to-list 'cache
681 (list depth (list (car openings) (point-marker))))
682 (setq openings (cdr openings))
683 (1- depth)))
684 (end-of-line))
685 cache)))
687 (defun wesnoth-indent-region (start end)
688 "Indent the region from START to END.
690 Creates and destroys a cache of macro definition details as necessary."
691 (interactive "r")
692 (unwind-protect
693 (save-excursion
694 (goto-char end)
695 (setq end (point-marker))
696 (goto-char start)
697 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
698 (or (bolp) (forward-line 1))
699 (while (< (point) end)
700 (if (looking-at "^[\t ]*$")
701 (indent-line-to 0)
702 (funcall indent-line-function))
703 (forward-line 1)))
704 (setq wesnoth-define-blocks nil)))
706 (defun wesnoth-determine-context (position)
707 "Determine the type of the last relevant element.
709 POSITION is the buffer position of the element for which to
710 determine the context."
711 (save-excursion
712 (search-backward-regexp wesnoth-element (wesnoth-wml-start-pos) t)
713 (let ((match (or (match-string 1) ""))
714 (depth (wesnoth-within-define position)))
715 (while (and (> (wesnoth-within-define (point)) depth)
716 (not (= (point) (wesnoth-wml-start-pos))))
717 (search-backward-regexp wesnoth-element
718 (wesnoth-wml-start-pos) t)
719 (setq match (match-string 1)))
720 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth 0)
721 (string-match "#define" match))
722 ;; Found nothing of use; reset match and assume top-level tag.
723 (setq match ""))
724 (cond
725 ((string-match "\\[/\\|#enddef" match)
726 (values 'closing (current-indentation)))
727 ((string-match "\\[[^/]?\\|#define" match)
728 (values 'opening (current-indentation)))))))
730 (defun wesnoth-newline-and-indent (&optional indent)
731 "Indent both the current line and the newline created.
732 If `wesnoth-auto-indent-flag' is nil, indentation will not be
733 performed.
735 If the optional argument, INDENT is non-nil, force indentation to
736 be performed."
737 (interactive)
738 (wesnoth-newline)
739 (when (or wesnoth-auto-indent-flag indent)
740 (wesnoth-indent)))
742 ;;; WML checks
743 (defun wesnoth-check-element-type (position last-tag)
744 "Determine the context of the element.
745 POSITION is the position of the element in the list.
746 LAST-TAG is the parent element."
747 (let ((inhibit-changing-match-data t))
748 (if (or (not last-tag) (string-match "#\\(?:define\\|ifn?def\\)" last-tag))
749 (member (match-string-no-properties 1)
750 (mapcar 'car wesnoth-tag-data))
751 (member (match-string-no-properties 1)
752 (nth position (gethash last-tag
753 wesnoth-tag-hash-table))))))
755 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
756 (defun wesnoth-line-number-at-pos (&optional pos)
757 "Return (narrowed) buffer line number at position POS.
758 If POS is nil, use current buffer location.
759 Counting starts at (point-min), so the value refers
760 to the contents of the accessible portion of the buffer."
761 (let ((opoint (or pos (point))) start)
762 (save-excursion
763 (goto-char (point-min))
764 (setq start (point))
765 (goto-char opoint)
766 (forward-line 0)
767 (1+ (count-lines start (point))))))
769 (defun wesnoth-check-output (buffer format-string &rest args)
770 "Output the string as passed to `format'.
771 BUFFER is the buffer to output the result.
772 FORMAT-STRING is the string as the first argument of `format'.
773 ARGS is any additional data required by `format' to handle FORMAT-STRING."
774 (save-excursion
775 (let ((lnap (wesnoth-line-number-at-pos)))
776 (set-buffer buffer)
777 (insert (apply 'format (concat "Line %d: " format-string "\n")
778 lnap args)))))
780 (defun wesnoth-check-wml ()
781 "Perform context-sensitive analysis of WML-code."
782 (interactive)
783 (wesnoth-update-project-information)
784 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
785 (error "WML data not available; can not generate report"))
786 (let ((unmatched-tag-list '())
787 (outbuf (get-buffer-create "*WML*")))
788 (save-excursion
789 (let ((buffer (buffer-name)))
790 (set-buffer outbuf)
791 (erase-buffer)
792 (insert (format "Checking %s...\n" buffer))
793 (message (format "Checking %s..." buffer))))
794 (save-excursion
795 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
796 (while (search-forward-regexp
797 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
798 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
799 wesnoth-preprocessor-regexp "\\)")
800 (point-max) t)
801 (beginning-of-line)
802 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
803 (unless (wesnoth-check-element-type 0
804 (car unmatched-tag-list))
805 (wesnoth-check-output outbuf
806 "Tag not available in this context: '%s'"
807 (match-string-no-properties 1)))
808 (setq unmatched-tag-list (cons
809 (match-string-no-properties 1)
810 unmatched-tag-list)))
811 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
812 (setq unmatched-tag-list (cons (match-string-no-properties 1)
813 unmatched-tag-list)))
814 ((looking-at wesnoth-preprocessor-closing-regexp)
815 (unless (string= (car unmatched-tag-list)
816 (second (assoc (match-string-no-properties 1)
817 '(("enddef" "#define")
818 ("ifdef" "#endif")
819 ("ifndef" "#endif")))))
820 (wesnoth-check-output
821 outbuf
822 "Preprocessor statement does not nest correctly"))
823 (setq unmatched-tag-list (cdr unmatched-tag-list)))
824 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
825 (unless (wesnoth-check-element-type 1
826 (car unmatched-tag-list))
827 (wesnoth-check-output
828 outbuf "Attribute not available in this context: '%s'"
829 (match-string-no-properties 1)))
830 (unless (match-string 3)
831 (wesnoth-check-output
832 outbuf "Attribute has no value")))
833 ((looking-at "^[\t ]*#else")
834 (unless (string-match "ifn?def" (car unmatched-tag-list))
835 (if (string= (car unmatched-tag-list) "#define")
836 (wesnoth-check-output outbuf "Expecting: '%s'"
837 (car unmatched-tag-list))
838 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
839 (car unmatched-tag-list)))))
840 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
841 (unless (assoc (match-string-no-properties 1)
842 (append wesnoth-local-macro-data
843 wesnoth-macro-data))
844 (wesnoth-check-output outbuf "Unknown macro definition: '{%s}'"
845 (match-string-no-properties 1))))
846 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
847 (unless (string= (match-string-no-properties 1)
848 (car unmatched-tag-list))
849 (if (string-match "^#.+" (car unmatched-tag-list))
850 (wesnoth-check-output outbuf "Expecting: '#%s'"
851 (car
852 (assoc (car unmatched-tag-list)
853 '(("define" "#enddef")
854 ("endif" "#ifdef")
855 ("endif" "#ifndef")))))
856 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
857 (car unmatched-tag-list))))
858 (setq unmatched-tag-list (cdr unmatched-tag-list))))
859 (end-of-line))
860 (if unmatched-tag-list
861 (dolist (tag unmatched-tag-list)
862 (wesnoth-check-output outbuf "Unmatched tag: '%s'"
863 (car unmatched-tag-list)))))
864 (save-excursion
865 (let ((buffer (buffer-name)))
866 (set-buffer outbuf)
867 (display-buffer outbuf t)
868 (let ((warnings (- (wesnoth-line-number-at-pos
869 (save-excursion (goto-char (point-max)))) 2)))
870 (insert (format (concat "\nCheck complete. %d warning"
871 (if (= warnings 1) "." "s.")) warnings)))
872 (message (format "Checking %s...done" buffer))))))
874 (defmacro wesnoth-element-requires (element requirement &optional pop)
875 "Process requirements for corresponding preprocessor elements.
876 ELEMENT is the current element being tested.
877 REQUIREMENT is the element required to exist for correct nesting.
878 POP is an optional argument indicating the element should be
879 removed from the unmatched-tag-list."
880 `(when (string= ,element (match-string-no-properties 1))
882 (if (string-match ,requirement (car unmatched-tag-list))
883 (progn
884 (and ,pop (setq unmatched-tag-list (cdr unmatched-tag-list)))
886 (setq error-position (point)))))
888 (defmacro wesnoth-structure-result (position element)
889 "Process results of the structure check.
890 POSITION is the error position or nil, if no error was found.
891 ELEMENT is the last unmatched element, or nil if all opening
892 elements have been matched."
893 `(let ((expected nil))
894 (when ,element
895 (cond ((string= ,element "define ") (setq expected "#enddef"))
896 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
897 (if (interactive-p)
898 (if (or ,element ,position)
899 (progn
900 (and ,position (goto-char ,position))
901 (message "Error: Expecting %s" (or expected
902 (concat "[/" ,element "]"))))
903 (message "%s" "Structure appears consistent."))
904 (when (or expected ,element)
905 (or expected (concat "[/" ,element "]"))))))
907 (defun wesnoth-check-structure (&optional start end)
908 "Check the buffer for correct nesting of elements.
909 If a problem is found in the structure, point will be placed at
910 the location which an element was expected and the expected
911 element will be displayed in the mini-buffer.
913 START and END define the region to be checked. If
914 function `transient-mark-mode' is enabled, the region specified will be
915 checked. Otherwise START and END will be the minimum and maximum
916 positions of the buffer, respectively."
917 (interactive)
918 (unless (or start end)
919 (if (and (boundp 'transient-mark-mode)
920 transient-mark-mode mark-active)
921 (setq start (region-beginning)
922 end (copy-marker (region-end)))
923 (setq start (point-min)
924 end (point-max))))
925 (let ((unmatched-tag-list '())
926 (error-position nil))
927 (save-excursion
928 (and start (goto-char start))
929 (while (and (search-forward-regexp
930 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
931 wesnoth-preprocessor-regexp "\\)") end t)
932 (not error-position))
933 (beginning-of-line)
934 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
935 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
936 (setq unmatched-tag-list (cons (match-string-no-properties 1)
937 unmatched-tag-list))
938 (cond
939 ((wesnoth-element-requires "#else" "ifn?def "))
940 ((wesnoth-element-requires "#endif" "ifn?def " t))
941 ((wesnoth-element-requires "#enddef" "define " t))
942 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
943 wesnoth-preprocessor-closing-regexp))
944 (if (string= (match-string-no-properties 1)
945 (car unmatched-tag-list))
946 (setq unmatched-tag-list (cdr unmatched-tag-list))
947 (setq error-position (point))))))
948 (end-of-line)))
949 (wesnoth-structure-result error-position (car unmatched-tag-list))))
951 ;;; wesnoth-mode
952 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
953 "Major mode for editing WML."
954 (kill-all-local-variables)
955 (use-local-map wesnoth-mode-map)
956 (setq major-mode 'wesnoth-mode)
957 (setq mode-name "WML")
958 (set-syntax-table wesnoth-syntax-table)
959 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
960 (set (make-local-variable 'comment-start) "#")
961 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
962 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
963 (set (make-local-variable 'font-lock-defaults)
964 '(wesnoth-font-lock-keywords
965 nil t nil nil
966 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
967 (setq indent-tabs-mode nil)
968 (easy-menu-add wesnoth-menu wesnoth-mode-map)
969 (wesnoth-create-wml-hash-table)
970 (run-hooks 'wesnoth-mode-hook))
972 (provide 'wesnoth-mode)
974 ;;; wesnoth-mode.el ends here