* wesnoth-mode.el: Remove trailing whitespace. Indent.
[wesnoth-mode.git] / wesnoth-mode.el
blobc5f01eb4b343ab351ec6887cea95ec098ed4b9ff
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 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 ;; * Improved performance for inserting missing tags.
40 ;; * Fixed a bug where #ifdef was never matched when checking WML.
41 ;; * Added completion for preprocessor statements.
42 ;; 1.3.0
43 ;; * Added support for Xemacs.
44 ;; * WML checking is now context sensitive; checks attributes and macros.
45 ;; * WML checks are now always performed on the entire buffer, with results
46 ;; displayed in a temporary buffer.
47 ;; * Context-sensitive completion for attributes and tags.
48 ;; * Completion for built-in and project-specific macros.
49 ;; * Changed the following bindings:
50 ;; `wesnoth-insert-tag' - C-c e -> C-c t
51 ;; `wesnoth-jump-to-matching' - C-c m -> C-c o
52 ;; `wesnoth-check-structure' -> `wesnoth-check-wml' - C-c c
53 ;; * Added the following bindings:
54 ;; `wesnoth-complete-attribute' - C-c a
55 ;; `wesnoth-complete-macro' - C-c m
56 ;; `wesnoth-complete-tag' - C-c t
57 ;; * Removed the following bindings:
58 ;; `wesnoth-check-tag-names' - C-c n
59 ;; * Removed `wesnoth-check-tag-names'. Replaced by `wesnoth-check-wml'.
60 ;; * Completion for an incomplete attribute, tag, or macro at point is
61 ;; attempted via TAB.
62 ;; 1.2.5
63 ;; * Fixed support for GNU Emacs 21.
64 ;; * Added several new tags to `wesnoth-tags-list'.
65 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
66 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
67 ;; how many blocks to wrap across instead of a region.
68 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
69 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
70 ;; causing tags not to be inserted in the correct position.
71 ;; * Fixed highlighting of array indexes as tags.
72 ;; 1.2.4
73 ;; * Improved syntax-highlighting for macro calls.
74 ;; * Underscore is now treated as whitespace.
75 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
76 ;; * Point is now placed at the first non-whitespace character of the line,
77 ;; instead of the last.
78 ;; * Corrected minor indentation bugs.
79 ;; * Indenting across large regions is now much more efficient.
80 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
81 ;; applied.
82 ;; 1.2.3
83 ;; * Now compatible with GNU Emacs 21.4.
84 ;; * Added support for several new tags.
85 ;; * Added menu entry for wesnoth-mode.
86 ;; * Significant speed increase to indentation.
87 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
88 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
89 ;; has been removed.
90 ;; * Trailing whitespace is no longer created when creating a second
91 ;; consecutive newline.
92 ;; * Spurious newlines are no longer created when inserting a tag elements
93 ;; around a region.
94 ;; 1.2.2
95 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
96 ;; `wesnoth-element', `wesnoth-element-opening',
97 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
98 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
99 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
100 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
101 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
102 ;; * Fixed a bug in indentation where content was needed between elements pairs
103 ;; for indentation to work.
104 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
105 ;; `wesnoth-auto-indent-flag'.
106 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
107 ;; * Added indentation styles: `wesnoth-indent-default',
108 ;; `wesnoth-indent-withtags' which implement a a similar indentation
109 ;; style to the existing styles, however all preprocessor statements are
110 ;; indented to the first column.
111 ;; * Added support for several new tags.
112 ;; * Modified `wesnoth-newline' to behave more consistently.
113 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
114 ;; now leaves point at the beginning (when moving backward) or end (when
115 ;; moving forward) of the match.
116 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
117 ;; will now work on preprocessor statements. Will now warn if jump
118 ;; destination may not be correct (due to errors in WML structure).
119 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
120 ;; * `wesnoth-check-structure' can now be applied over an active region and
121 ;; now checks preprocessor statements for correct nesting.
122 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
123 ;; perform indentation by providing a prefix argument.
124 ;; * Indentation styles now leave point at the first non-whitespace character
125 ;; of the line.
126 ;; * `wesnoth-check-tag-names' now reports on success.
127 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
128 ;; * `outline-minor-mode' now works on macro definitions.
129 ;; 1.2.1
130 ;; * Base indent now defaults to 4.
131 ;; * Added support for #ifndef.
133 ;;; Code:
134 (eval-when-compile
135 (require 'cl))
136 (require 'easymenu)
137 (require 'wesnoth-update)
138 (require 'wesnoth-wml-data)
140 (defconst wesnoth-mode-version "1.3.0+git"
141 "The current version of `wesnoth-mode'.")
143 (defgroup wesnoth-mode nil "Wesnoth-mode access"
144 :group 'languages
145 :prefix "wesnoth-")
147 (defcustom wesnoth-auto-indent-flag t
148 "Non-nil means indent the current line upon creating a newline."
149 :type 'boolean
150 :group 'wesnoth-mode)
152 (defcustom wesnoth-indent-savefile t
153 "Non-nil means to use the current indentation conventions.
154 If nil, use the old convention for indentation.
155 The current convention is all attributes are indented a level deeper
156 than their parent; in the past attributes were indented to the same
157 level as their parent.")
159 (defcustom wesnoth-base-indent 4
160 "The number of columns to indent WML."
161 :type 'integer
162 :group 'wesnoth-mode)
164 (defconst wesnoth-preprocessor-regexp
165 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def \\)"
166 "Regular expression to match all preprocessor statements.")
168 (defconst wesnoth-preprocessor-opening-regexp
169 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
170 "Regular expression to match \"opening\" preprocessor statements.")
172 (defconst wesnoth-preprocessor-closing-regexp
173 "[\t ]*#\\(end\\(\\(de\\|i\\)f\\)\\)"
174 "Regular expression to match \"closing\" preprocessor statements.")
176 (defvar wesnoth-define-blocks '()
177 "Cache of all toplevel #define and #enddef pairs.")
179 (defvar wesnoth-history-list '()
180 "History of inserted WML elements.")
182 (defvar wesnoth-mode-hook nil)
184 (defvar wesnoth-mode-map
185 (let ((map (make-sparse-keymap)))
186 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
187 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
188 (define-key map (kbd "C-m") 'wesnoth-newline)
189 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
190 (define-key map (kbd "C-c C-c") 'wesnoth-check-wml)
191 (define-key map (kbd "C-c C-a") 'wesnoth-complete-attribute)
192 (define-key map (kbd "C-c C-t") 'wesnoth-complete-tag)
193 (define-key map (kbd "C-c C-p") 'wesnoth-complete-preprocessor)
194 (define-key map (kbd "M-TAB") 'wesnoth-complete-tag)
195 (define-key map (kbd "C-c C-m") 'wesnoth-complete-macro)
196 (define-key map (kbd "C-c C-o") 'wesnoth-jump-to-matching)
197 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
198 (define-key map (kbd "TAB") 'wesnoth-indent-or-complete)
199 map)
200 "Keymap used in `wesnoth-mode'.")
202 (easy-menu-define wesnoth-menu wesnoth-mode-map "Menu for wesnoth-mode"
203 '("WML"
204 ["Check WML" wesnoth-check-wml t]
205 ["Indent or Complete" wesnoth-indent-or-complete t]
206 ["Indent buffer" (lambda ()
207 (interactive)
208 (wesnoth-indent-region (point-min) (point-max))) t]
209 ["Insert Tag" wesnoth-complete-tag t]
210 ["Insert Attribute" wesnoth-complete-attribute t]
211 ["Insert Macro" wesnoth-complete-macro t]
212 ["Insert Missing Tag" wesnoth-insert-missing-closing t]
213 ["Jump to Matching" wesnoth-jump-to-matching t]))
215 (defvar wesnoth-syntax-table
216 (let ((wesnoth-syntax-table (make-syntax-table)))
217 (modify-syntax-entry ?= "." wesnoth-syntax-table)
218 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
219 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
220 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
221 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
222 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
223 wesnoth-syntax-table)
224 "Syntax table for `wesnoth-mode'.")
226 ;; Prevents automatic syntax-highlighting of elements which might be
227 ;; pre-processor statements.
228 (defvar wesnoth-syntactic-keywords
229 (list
230 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
231 '("\\(#[\t ]*.*$\\)" 1 "<"))
232 "Highlighting syntactic keywords within `wesnoth-mode'.")
234 (defvar wesnoth-font-lock-keywords
235 (list
236 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face)
237 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
238 font-lock-keyword-face)
239 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
240 2 font-lock-function-name-face)
241 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face))
242 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face))
243 '("}" . font-lock-function-name-face)
244 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face)
245 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
246 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
247 1 font-lock-variable-name-face))
248 "Syntax highlighting for `wesnoth-mode'.")
250 (defun wesnoth-element-closing (&optional limited)
251 "Return the regexp to match a closing element.
252 If LIMITED is non-nil, return a regexp which matches only the
253 #enddef preprocessor."
254 (concat "^[\t ]*\\(\\[/\\(\\w\\|_\\)+\\|"
255 (if limited
256 "#enddef"
257 "#end\\(?:def\\|if\\)")
258 "\\)"))
260 (defun wesnoth-element-opening (&optional limited)
261 "Return the regexp to match a closing element.
262 If LIMITED is non-nil, return a regexp which matches only the
263 #define preprocessor."
264 (concat "^[\t ]*\\(\\[\\(\\w\\|_\\)+\\]\\|#define "
265 (if limited
267 "\\|#ifn?def ")
268 "\\)"))
270 (defun wesnoth-element (&optional limited)
271 "Return the regexp to match a closing element.
272 If LIMITED is non-nil, return a regexp which matches only the
273 #define and #enddef preprocessors."
274 (concat "^[\t ]*\\(\\[/?\\(\\w\\|_\\)+\\]?\\|"
275 (if limited
276 "#define \\|#enddef"
277 (substring wesnoth-preprocessor-regexp 5))
278 "\\)"))
281 ;;; Insertion and completion
282 (defmacro wesnoth-element-completion (completions prompt partial)
283 "Process completion of COMPLETIONS, displaying PROMPT.
284 PARTIAL is the partial string on which to attempt completion."
285 `(let* ((element (when ,partial (try-completion ,partial ,completions))))
286 (cond ((eq element t)
287 (setq element nil))
288 ((null element)
289 (setq element
290 (completing-read ,prompt ,completions nil nil nil
291 'wesnoth-history-list)))
292 ((not (if (listp (car ,completions))
293 (assoc element ,completions)
294 (member element ,completions)))
295 (setq element
296 (completing-read ,prompt ,completions
297 nil nil ,partial
298 'wesnoth-history-list))))
299 element))
301 (defun wesnoth-parent-tag ()
302 "Return the name of the parent tag.
303 If the parent is a preprocessor statement, return non-nil.
304 If the element does not have a parent, return nil.
305 Otherwise, return a string containing the name of the parent tag."
306 (save-excursion
307 (let ((start-point (point))
308 (depth 1))
309 (when (save-excursion (> (point) (progn (back-to-indentation)
310 (point))))
311 (end-of-line))
312 (while (and (> depth 0)
313 (search-backward-regexp (wesnoth-element)
314 (point-min) t))
315 (if (string-match "[\t ]*\\[/" (match-string 0))
316 (incf depth)
317 (decf depth)))
318 (beginning-of-line)
319 (if (> depth 0)
321 (when (looking-at (wesnoth-element-opening))
322 (let ((parent (match-string-no-properties 1)))
323 (if (string-match wesnoth-preprocessor-opening-regexp parent)
325 (substring parent 1 (1- (length parent))))))))))
327 (defun wesnoth-indent-or-complete (&optional elements)
328 "Indent or complete the line at point, depending on context.
329 ELEMENTS is the number of elements to wrap around if inserting
330 matching tags."
331 (interactive "P")
332 (or elements (setq elements 0))
333 (let ((target nil))
334 (save-excursion
335 (back-to-indentation)
336 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
337 (wesnoth-complete-attribute t))
338 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
339 (wesnoth-complete-tag elements t))
340 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
341 (wesnoth-complete-macro t))
342 ((looking-at "^#\\w+$")
343 (wesnoth-complete-preprocessor elements t))
344 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
345 (delete-region (point) (progn (end-of-line) (point)))
346 (wesnoth-insert-missing-closing)
347 (end-of-line))
349 (wesnoth-indent)))
350 (setq target (point)))
351 (goto-char target)))
353 (defun wesnoth-preprocessor-closed-p (preprocessor)
354 "Determine whether PREPROCESSOR has been closed.
355 PREPROCESSOR is a string matching the preprocessor statement to
356 be inserted."
357 (save-excursion
358 (back-to-indentation)
359 (wesnoth-jump-to-matching preprocessor)
360 (when (looking-at
361 (if (string= preprocessor "#define ")
362 "#enddef"
363 "#endif"))
364 t)))
366 (defun wesnoth-complete-preprocessor (&optional elements completep)
367 "Complete and insert the preprocessor at point.
368 ELEMENTS is the number of elements to wrap around.
369 If COMPLETEP is non-nil, attempt to complete preprocessor at point."
370 (interactive "P")
371 (or elements (setq elements 0))
372 (let* ((completions '("define" "else" "ifdef" "ifndef"
373 "enddef" "endif" "undef"))
374 (partial (when completep
375 (save-excursion
376 (back-to-indentation)
377 (when (looking-at "#\\(\\w+\\)$")
378 (match-string 1)))))
379 (preprocessor (or (wesnoth-element-completion
380 completions "Preprocessor: " partial)
381 partial))
382 (closedp
383 (save-excursion
384 (when preprocessor
385 (unless (string= "#" (substring preprocessor 0 1))
386 (setq preprocessor (concat "#" preprocessor)))
387 (when (string-match "#\\(define\\|ifn?def\\|undef\\)" preprocessor)
388 (setq preprocessor (concat preprocessor " ")))
389 (when partial
390 (delete-region (progn (back-to-indentation) (point))
391 (progn (end-of-line) (point))))
392 (wesnoth-preprocessor-closed-p preprocessor)))))
393 (when preprocessor
394 (when partial
395 (delete-region (progn (back-to-indentation) (point))
396 (progn (end-of-line) (point))))
397 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor)
398 (not closedp))
399 (progn
400 (wesnoth-insert-tag elements preprocessor)
401 (forward-line -1)
402 (end-of-line))
403 (wesnoth-insert-element-separately preprocessor)))))
405 (defun wesnoth-complete-macro (&optional completep)
406 "Complete and insert the macro at point.
407 If COMPLETEP is non-nil, attempt to complete the macro at point."
408 (interactive)
409 (let* ((macro-information (append wesnoth-macro-data
410 wesnoth-local-macro-data))
411 (completions (wesnoth-emacs-completion-formats
412 (mapcar 'car macro-information)))
413 (partial (when completep
414 (save-excursion
415 (back-to-indentation)
416 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
417 (match-string 1)))))
418 (macro (or (wesnoth-element-completion completions "Macro: " partial)
419 partial))
420 (args (cadr (assoc macro macro-information))))
421 (when macro
422 (if partial
423 (progn
424 (delete-region (progn (back-to-indentation) (point))
425 (progn (end-of-line) (point)))
426 (insert "{" macro (if args " }" "}")))
427 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
428 (save-excursion
429 (wesnoth-indent))
430 (when args
431 (forward-char -1)))))
433 (defun wesnoth-complete-attribute (&optional completep)
434 "Insert the attribute at point.
435 If COMPLETEP is non-nil, attempt to complete the attribute at point."
436 (interactive)
437 (let* ((completions (wesnoth-build-completion 2))
438 (partial (when completep
439 (save-excursion
440 (back-to-indentation)
441 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
442 (match-string 1)))))
443 (attribute (or (wesnoth-element-completion completions "Attribute: "
444 partial)
445 partial)))
446 (when attribute
447 (if (and partial completep)
448 (progn
449 (delete-region (progn (back-to-indentation) (point))
450 (progn (end-of-line) (point)))
451 (insert attribute "="))
452 (wesnoth-insert-element-separately attribute
453 (if (string-match "=" attribute)
455 "=")))
456 (save-excursion
457 (wesnoth-indent)))))
459 (defun wesnoth-complete-tag (&optional elements completep)
460 "Complete and insert the tag at point.
461 ELEMENTS is the number of elements to wrap around.
462 If COMPLETEP is non-nil, attempt to complete tag at point."
463 (interactive "P")
464 (or elements (setq elements 0))
465 (let* ((completions (wesnoth-build-completion 1))
466 (partial (when completep
467 (save-excursion
468 (back-to-indentation)
469 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
470 (match-string 1)))))
471 (tag (or (wesnoth-element-completion completions "Tag: " partial)
472 partial))
473 (closedp
474 (save-excursion
475 (wesnoth-jump-to-matching)
476 (back-to-indentation)
477 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
478 (string= tag (match-string 1)))
479 t))))
480 (when completep
481 (delete-region (progn (back-to-indentation) (point))
482 (progn (end-of-line) (point))))
483 (if (and closedp completep)
484 (progn
485 (wesnoth-insert-and-indent "[" tag "]")
486 (end-of-line))
487 (wesnoth-insert-tag elements tag))))
489 (defun wesnoth-build-completion (position)
490 "Create a new list for tag completion if necessary.
491 Rebuilding list is required for versions of GNU Emacs earlier
492 than 22. POSITION is the argument passed to `nth' for
493 `wesnoth-tag-data'."
494 (interactive "P")
495 (let* ((parent (wesnoth-parent-tag))
496 (candidates
497 (if (or (stringp parent) (null parent))
498 (nth (1- position) (gethash parent wesnoth-tag-hash-table))
499 (mapcar 'car wesnoth-tag-data))))
500 (wesnoth-emacs-completion-formats candidates)))
502 (defun wesnoth-emacs-completion-formats (candidates)
503 "Return the completions in the correct format for `emacs-major-version'.
504 CANDIDATES is a list of all possible completions."
505 (if (> emacs-major-version 21)
506 candidates
507 (let ((tags '())
508 (iter 0))
509 (dolist (tag candidates)
510 (setq iter (1+ iter))
511 (setq tags (append tags (list (cons tag iter)))))
512 tags)))
514 (defun wesnoth-insert-tag (&optional elements tagname)
515 "Insert the specified opening tag and it's matching closing tag.
516 Both the opening and closing tags will be placed on their own
517 lines with point positioned between them. Completion of tags at
518 the prompt uses `wesnoth-tags-list'.
520 ELEMENTS is specifies the number of following blocks which the
521 tag should wrap around.
523 TAGNAME is the name of the tag to be inserted."
524 (interactive "Ps")
525 (unless tagname
526 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 1)
527 nil nil nil wesnoth-history-list)))
528 (when (or (not elements)
529 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
530 wesnoth-preprocessor-regexp "\\)")))
531 (setq elements 0))
532 (let ((depth 0)
533 (start (save-excursion (forward-line -1) (point)))
534 (end (unless (= elements 0)
535 (wesnoth-nth-pair-position elements))))
536 (if (string-match wesnoth-preprocessor-regexp tagname)
537 (wesnoth-insert-element-separately tagname)
538 (wesnoth-insert-element-separately "[" tagname "]"))
539 (save-excursion
540 (if end
541 (goto-char (marker-position end))
542 (newline 2))
543 (if (string-match wesnoth-preprocessor-opening-regexp tagname)
544 (wesnoth-insert-element-separately
545 (if (string= tagname "#define ")
546 "#enddef"
547 "#endif"))
548 (wesnoth-insert-element-separately "[/" tagname "]"))
549 (indent-region start (point) nil))
550 (unless end
551 (forward-line 1)))
552 (wesnoth-indent))
554 (defun wesnoth-nth-pair-position (count)
555 "Return `point' after COUNT number of matching element pairs.
556 COUNT is a positive number representing the number of balanced
557 pairs to move across.
558 `point' is returned as a marker object."
559 (save-excursion
560 (let ((start (point))
561 (failed nil))
562 (if (> (point) (save-excursion (back-to-indentation) (point)))
563 (end-of-line)
564 (beginning-of-line))
565 (while (> count 0)
566 ;; Currently looking-at target tag. Stop here to avoid
567 ;; incorrect nesting.
568 (unless (wesnoth-search-for-matching-tag
569 'search-forward-regexp (wesnoth-element-closing) 'point-max)
570 (setq count 0)
571 (unless (or (= (point) (point-max))
572 (progn (beginning-of-line)
573 (search-backward-regexp (wesnoth-element-closing)
574 start t)))
575 (setq failed t)))
576 (and (> (decf count) 0) (forward-line 1)))
577 (if failed
578 (beginning-of-line)
579 (end-of-line))
580 (point-marker))))
582 (defun wesnoth-insert-element-separately (&rest strings)
583 "Concatenate STRINGS and insert them on a line of their own."
584 (let ((create-newline (save-excursion
585 (beginning-of-line)
586 (if (looking-at "^[\t ]*$") nil t))))
587 (when create-newline
588 (if (> (point) (save-excursion (back-to-indentation) (point)))
589 (progn
590 (end-of-line)
591 (newline))
592 (beginning-of-line)
593 (open-line 1)))
594 (insert (apply 'concat strings))))
596 (defun wesnoth-insert-missing-closing (&optional start end)
597 "Insert the next expected closing element at point.
599 START and END define the region to check for missing closing
600 elements. If function `transient-mark-mode' is enabled, the region
601 specified will be used as START and END. Otherwise, START and
602 END will be the minimum and current positions of the buffer,
603 respectively."
604 (interactive)
605 (if (and (boundp 'transient-mark-mode)
606 transient-mark-mode mark-active)
607 (setq start (region-beginning)
608 end (copy-marker (region-end)))
609 (setq start (point-min)
610 end (point)))
611 (let ((element (wesnoth-check-structure start end)))
612 (if (not element)
613 (error "%s" "Unable to find element to insert")
614 (when (string= element "Unexpected end of file")
615 (error "%s" element))
616 (wesnoth-insert-element-separately element)))
617 (wesnoth-indent)
618 (end-of-line))
620 (defun wesnoth-insert-and-indent (&rest args)
621 "Concatenate and insert the given string(s) before indenting.
623 ARGS is a list of strings to be inserted."
624 (insert (apply 'concat args))
625 (wesnoth-indent))
627 (defun wesnoth-newline (&optional indent)
628 "Indent both the current line and the newline created.
629 If `wesnoth-auto-indent-flag' is nil, indentation will not be
630 performed. Indentation can be forced by setting INDENT to
631 non-nil."
632 (interactive)
633 (save-excursion
634 (when (and (or wesnoth-auto-indent-flag indent)
635 (not (looking-at "^[\t ]*$")))
636 (wesnoth-indent)))
637 (newline))
639 ;;; Movement
640 (defmacro wesnoth-navigate-element (repeat search-function bound)
641 "Move point to the tag in the given direction REPEAT times.
643 SEARCH-FUNCTION is the symbol of the function for searching in
644 the required direction, with BOUND marking the furthest point to
645 search."
646 `(progn
647 (or ,repeat (setq ,repeat 1))
648 (while (> ,repeat 0)
649 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
650 (funcall ,search-function (wesnoth-element-opening) ,bound t)
651 (back-to-indentation)
652 (decf ,repeat))))
654 (defun wesnoth-forward-element (repeat)
655 "Move point to the end of the next tag.
656 REPEAT is an optional numeric argument. If REPEAT is non-nil,
657 jump forward the specified number of tags."
658 (interactive "p")
659 (if (< repeat 0)
660 (wesnoth-backward-element (abs repeat))
661 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
663 (defun wesnoth-backward-element (repeat)
664 "Move point to the beginning of the previous tag.
665 REPEAT is an optional numeric argument. If REPEAT is non-nil,
666 jump backward the specified number of tags."
667 (interactive "p")
668 (if (< repeat 0)
669 (wesnoth-forward-element (abs repeat))
670 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
672 (defmacro wesnoth-search-for-matching-tag (search-function
673 search-string bound &optional skip)
674 "Search for the matching tag for the current line.
676 SEARCH-FUNCTION is the name of the function used to perform the search.
677 SEARCH-STRING is a string representing the matching tag type.
678 BOUND is the bound to be passed to the search function.
679 If SKIP is non-nil, skip the first element and continue from there."
680 `(let ((depth 1))
681 (when (or (and ,skip (forward-line 1))
682 (funcall ,search-function (wesnoth-element) (funcall ,bound) t))
683 (when (or ,skip (not (string-match ,search-string (match-string 0))))
684 (while (and (> depth 0)
685 (funcall ,search-function (wesnoth-element)
686 (funcall ,bound) t))
687 (if (string-match ,search-string (match-string 0))
688 (decf depth)
689 (incf depth)))
690 (when (= depth 0)
691 t)))))
693 (defun wesnoth-jump-to-matching (&optional opening)
694 "Jump point to the matching opening/closing tag.
695 OPENING is an opening preprocessor statement to attempt to find a match for."
696 (interactive)
697 (beginning-of-line)
698 (let ((target nil)
699 (first-element nil))
700 (save-excursion
701 (if (or (and (stringp opening)
702 (string-match (wesnoth-element-opening) opening))
703 (looking-at (wesnoth-element-opening)))
704 (progn
705 (setq first-element (match-string-no-properties 0 opening))
706 (when (wesnoth-search-for-matching-tag
707 'search-forward-regexp (wesnoth-element-closing) 'point-max
708 (stringp opening))
709 (beginning-of-line)
710 (if (and (string-match wesnoth-preprocessor-opening-regexp
711 first-element)
712 (looking-at (wesnoth-element-closing)))
713 (when (string= (match-string-no-properties 0)
714 (cdr (assoc first-element
715 '(("#define " . "#enddef")
716 ("#ifndef " . "#endif")
717 ("#ifdef " . "#endif")))))
718 (setq target (point)))
719 (setq target (point)))))
720 (when (looking-at (wesnoth-element-closing))
721 (setq first-element (match-string-no-properties 0))
722 (end-of-line)
723 (when (wesnoth-search-for-matching-tag
724 'search-backward-regexp (wesnoth-element-opening)
725 'wesnoth-wml-start-pos)
726 (if (and (string-match wesnoth-preprocessor-closing-regexp
727 first-element)
728 (looking-at (wesnoth-element-opening)))
729 (progn
730 (when (or (and (string= "#enddef" first-element)
731 (string= "#define "
732 (match-string-no-properties 0)))
733 (and (string= "#endif" first-element)
734 (string-match
735 "#ifn?def "
736 (match-string-no-properties 0))))
737 (setq target (point))))
738 (setq target (point)))))))
739 (if target
740 (goto-char target)
741 (when (interactive-p)
742 (error "Tag does not appear to be matched"))))
743 (back-to-indentation))
745 (defun wesnoth-wml-start-pos ()
746 "Determine the position of `point' relative to where the actual WML begins.
747 Return the likely starting position of the WML if it is found.
748 Otherwise return nil."
749 (save-excursion
750 (goto-char (point-min))
751 (when (search-forward-regexp (wesnoth-element) (point-max) t)
752 (beginning-of-line)
753 (point))))
755 (defun first-column-indent-p (point)
756 "Return non-nil if the current line should not be indented.
758 POINT is the position in the buffer to check.
759 CONTEXT represents the type of element which precedes the current element."
760 (or (not (wesnoth-wml-start-pos))
761 (<= (point) (wesnoth-wml-start-pos))
762 (nth 3 (parse-partial-sexp (point-min) point))
763 (looking-at wesnoth-preprocessor-regexp)))
765 (defun wesnoth-indent ()
766 "Indent the current line as WML."
767 (beginning-of-line)
768 (let ((cur-indent 0))
769 (unless (first-column-indent-p (point))
770 (multiple-value-bind (context ref-indent)
771 (wesnoth-determine-context (point))
772 (cond
773 ((eq context 'opening)
774 (if (or (and wesnoth-indent-savefile
775 (not (looking-at (wesnoth-element-closing t))))
776 (looking-at (wesnoth-element-opening t)))
777 (setq cur-indent (+ ref-indent wesnoth-base-indent))
778 (setq cur-indent ref-indent)))
779 ((eq context 'closing)
780 (if (or (looking-at "^[\t ]*\\[/")
781 (and (not wesnoth-indent-savefile)
782 (not (looking-at (wesnoth-element-opening t)))))
783 (setq cur-indent (- ref-indent wesnoth-base-indent))
784 (setq cur-indent ref-indent))))))
785 (indent-line-to (max cur-indent 0))))
787 (defun wesnoth-within-define (position)
788 "Determine whether point is currently inside a #define block.
789 POSITION is the initial cursor position."
790 (let ((depth 0))
791 (dolist (element (or wesnoth-define-blocks
792 (wesnoth-find-macro-definitions)))
793 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
794 (list position)) '>)) position)
795 (setq depth (max (car element) depth))))
796 depth))
798 (defun wesnoth-find-macro-definitions ()
799 "Return information regarding positioning of macro definitions."
800 (save-excursion
801 (goto-char (point-min))
802 (let ((depth 0)
803 openings cache)
804 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t)
805 (and (string= (match-string 1) "#define") (beginning-of-line))
806 (setq depth
807 (if (string= (match-string 1) "#define")
808 (progn
809 (add-to-list 'openings (point-marker))
810 (1+ depth))
811 (if openings
812 (progn
813 (add-to-list 'cache
814 (list depth (list (car openings)
815 (point-marker))))
816 (setq openings (cdr openings))
817 (1- depth))
818 depth)))
819 (end-of-line))
820 cache)))
822 (defun wesnoth-indent-region (start end)
823 "Indent the region from START to END.
825 Creates and destroys a cache of macro definition details as necessary."
826 (interactive "r")
827 (unwind-protect
828 (save-excursion
829 (goto-char end)
830 (setq end (point-marker))
831 (goto-char start)
832 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
833 (or (bolp) (forward-line 1))
834 (while (< (point) end)
835 (if (looking-at "^[\t ]*$")
836 (indent-line-to 0)
837 (funcall indent-line-function))
838 (forward-line 1)))
839 (setq wesnoth-define-blocks nil)))
841 (defun wesnoth-determine-context (position)
842 "Determine the type of the last relevant element.
844 POSITION is the buffer position of the element for which to
845 determine the context."
846 (save-excursion
847 (search-backward-regexp (wesnoth-element t)
848 (wesnoth-wml-start-pos) t)
849 (let ((match (or (match-string 1) ""))
850 (depth (wesnoth-within-define position)))
851 (while (and (> (wesnoth-within-define (point)) depth)
852 (not (= (point) (wesnoth-wml-start-pos))))
853 (search-backward-regexp (wesnoth-element t)
854 (wesnoth-wml-start-pos) t)
855 (setq match (match-string 1)))
856 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth 0)
857 (string-match "#define" match))
858 ;; Found nothing of use; reset match and assume top-level tag.
859 (setq match ""))
860 (cond
861 ((string-match "\\[/\\|#enddef" match)
862 (values 'closing (current-indentation)))
863 ((string-match "\\[[^/]?\\|#define" match)
864 (values 'opening (current-indentation)))))))
866 (defun wesnoth-newline-and-indent (&optional indent)
867 "Indent both the current line and the newline created.
868 If `wesnoth-auto-indent-flag' is nil, indentation will not be
869 performed.
871 If the optional argument, INDENT is non-nil, force indentation to
872 be performed."
873 (interactive)
874 (wesnoth-newline)
875 (when (or wesnoth-auto-indent-flag indent)
876 (wesnoth-indent)))
878 ;;; WML checks
879 (defun wesnoth-check-element-type (position last-tag)
880 "Determine the context of the element.
881 POSITION is the position of the element in the list.
882 LAST-TAG is the parent element."
883 (let ((inhibit-changing-match-data t))
884 (if (or (not last-tag) (string-match "#\\(?:define\\|ifn?def\\)" last-tag))
885 (member (match-string-no-properties 1)
886 (mapcar 'car wesnoth-tag-data))
887 (member (match-string-no-properties 1)
888 (nth position (gethash last-tag
889 wesnoth-tag-hash-table))))))
891 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
892 (defun wesnoth-line-number-at-pos (&optional pos)
893 "Return (narrowed) buffer line number at position POS.
894 If POS is nil, use current buffer location.
895 Counting starts at (point-min), so the value refers
896 to the contents of the accessible portion of the buffer."
897 (let ((opoint (or pos (point))) start)
898 (save-excursion
899 (goto-char (point-min))
900 (setq start (point))
901 (goto-char opoint)
902 (forward-line 0)
903 (1+ (count-lines start (point))))))
905 (defun wesnoth-check-output (buffer format-string &rest args)
906 "Output the string as passed to `format'.
907 BUFFER is the buffer to output the result.
908 FORMAT-STRING is the string as the first argument of `format'.
909 ARGS is any additional data required by `format' to handle FORMAT-STRING."
910 (save-excursion
911 (let ((lnap (wesnoth-line-number-at-pos)))
912 (set-buffer buffer)
913 (insert (apply 'format (concat "Line %d: " format-string "\n")
914 lnap args)))))
916 (defun wesnoth-check-wml ()
917 "Perform context-sensitive analysis of WML-code."
918 (interactive)
919 (wesnoth-update-project-information)
920 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
921 (error "WML data not available; can not generate report"))
922 (let ((unmatched-tag-list '())
923 (outbuf (get-buffer-create "*WML*")))
924 (save-excursion
925 (let ((buffer (buffer-name)))
926 (set-buffer outbuf)
927 (erase-buffer)
928 (insert (format "Checking %s...\n" buffer))
929 (message (format "Checking %s..." buffer))))
930 (save-excursion
931 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
932 (while (search-forward-regexp
933 ;; Match tags, preprocessors, macros and attributes.
934 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
935 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
936 wesnoth-preprocessor-regexp "\\)")
937 (point-max) t)
938 (beginning-of-line)
939 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
940 (unless (wesnoth-check-element-type 0
941 (car unmatched-tag-list))
942 (wesnoth-check-output outbuf
943 "Tag not available in this context: '%s'"
944 (match-string-no-properties 1)))
945 (setq unmatched-tag-list (cons
946 (match-string-no-properties 1)
947 unmatched-tag-list)))
948 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
949 (setq unmatched-tag-list (cons (match-string-no-properties 1)
950 unmatched-tag-list)))
951 ((looking-at wesnoth-preprocessor-closing-regexp)
952 (unless (string-match (cdr (assoc (match-string-no-properties 1)
953 '(("enddef" . "#define")
954 ("endif" . "#ifn?def"))))
955 (car unmatched-tag-list))
956 (wesnoth-check-output
957 outbuf
958 "Preprocessor statement does not nest correctly"))
959 (setq unmatched-tag-list (cdr unmatched-tag-list)))
960 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
961 (unless (wesnoth-check-element-type 1
962 (car unmatched-tag-list))
963 (wesnoth-check-output
964 outbuf "Attribute not available in this context: '%s'"
965 (match-string-no-properties 1)))
966 (unless (match-string 3)
967 (wesnoth-check-output
968 outbuf "Attribute has no value")))
969 ((looking-at "^[\t ]*#else")
970 (unless (string-match "ifn?def" (car unmatched-tag-list))
971 (if (string= (car unmatched-tag-list) "#define")
972 (wesnoth-check-output outbuf "Expecting: '%s'"
973 (car unmatched-tag-list))
974 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
975 (car unmatched-tag-list)))))
976 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
977 (unless (assoc (match-string-no-properties 1)
978 (append wesnoth-local-macro-data
979 wesnoth-macro-data))
980 (wesnoth-check-output outbuf "Unknown macro definition: '{%s}'"
981 (match-string-no-properties 1))))
982 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
983 (when (and (not unmatched-tag-list)
984 (string= (match-string-no-properties 1)
985 (car unmatched-tag-list)))
986 (if (string-match "^#.+" (car unmatched-tag-list))
987 (wesnoth-check-output outbuf "Expecting: '%s'"
988 (cdr
989 (assoc (car unmatched-tag-list)
990 '(("#define" . "#enddef")
991 ("#endif" . "#ifdef")
992 ("#endif" . "#ifndef")))))
993 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
994 (car unmatched-tag-list))))
995 (setq unmatched-tag-list (cdr unmatched-tag-list))))
996 (end-of-line))
997 (if unmatched-tag-list
998 (dolist (tag unmatched-tag-list)
999 (wesnoth-check-output outbuf "Unmatched tag: '%s'"
1000 (car unmatched-tag-list)))))
1001 (save-excursion
1002 (let ((buffer (buffer-name)))
1003 (set-buffer outbuf)
1004 (display-buffer outbuf t)
1005 (let ((warnings (- (wesnoth-line-number-at-pos
1006 (save-excursion (goto-char (point-max)))) 2)))
1007 (insert (format (concat "\nCheck complete. %d warning"
1008 (if (= warnings 1) "." "s.")) warnings)))
1009 (message (format "Checking %s...done" buffer))))))
1011 (defmacro wesnoth-element-requires (element requirement &optional pop)
1012 "Process requirements for corresponding preprocessor elements.
1013 ELEMENT is the current element being tested.
1014 REQUIREMENT is the element required to exist for correct nesting.
1015 POP is an optional argument indicating the element should be
1016 removed from the unmatched-tag-list."
1017 `(when (string= ,element (match-string-no-properties 1))
1019 (if (string-match ,requirement (car unmatched-tag-list))
1020 (progn
1021 (and ,pop (setq unmatched-tag-list (cdr unmatched-tag-list)))
1023 (setq error-position (point)))))
1025 (defmacro wesnoth-structure-result (position element)
1026 "Process results of the structure check.
1027 POSITION is the error position or nil, if no error was found.
1028 ELEMENT is the last unmatched element, or nil if all opening
1029 elements have been matched."
1030 `(let ((expected nil))
1031 (when ,element
1032 (cond ((string= ,element "define ") (setq expected "#enddef"))
1033 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
1034 (if (interactive-p)
1035 (if (or ,element ,position)
1036 (progn
1037 (and ,position (goto-char ,position))
1038 (message "Error: Expecting %s" (or expected
1039 (concat "[/" ,element "]"))))
1040 (message "%s" "Structure appears consistent."))
1041 (when (or expected ,element)
1042 (or expected (concat "[/" ,element "]"))))))
1044 (defun wesnoth-check-structure (&optional start end)
1045 "Check the buffer for correct nesting of elements.
1046 If a problem is found in the structure, point will be placed at
1047 the location which an element was expected and the expected
1048 element will be displayed in the mini-buffer.
1050 START and END define the region to be checked. If
1051 function `transient-mark-mode' is enabled, the region specified will be
1052 checked. Otherwise START and END will be the minimum and maximum
1053 positions of the buffer, respectively."
1054 (interactive)
1055 (unless (or start end)
1056 (if (and (boundp 'transient-mark-mode)
1057 transient-mark-mode mark-active)
1058 (setq start (region-beginning)
1059 end (copy-marker (region-end)))
1060 (setq start (point-min)
1061 end (point-max))))
1062 (let ((unmatched-tag-list '())
1063 (error-position nil))
1064 (save-excursion
1065 (and start (goto-char start))
1066 (while (and (search-forward-regexp
1067 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
1068 wesnoth-preprocessor-regexp "\\)") end t)
1069 (not error-position))
1070 (beginning-of-line)
1071 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
1072 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
1073 (setq unmatched-tag-list (cons (match-string-no-properties 1)
1074 unmatched-tag-list))
1075 (cond
1076 ((wesnoth-element-requires "#else" "ifn?def "))
1077 ((wesnoth-element-requires "#endif" "ifn?def " t))
1078 ((wesnoth-element-requires "#enddef" "define " t))
1079 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
1080 wesnoth-preprocessor-closing-regexp))
1081 (if (string= (match-string-no-properties 1)
1082 (car unmatched-tag-list))
1083 (setq unmatched-tag-list (cdr unmatched-tag-list))
1084 (setq error-position (point))))))
1085 (end-of-line)))
1086 (wesnoth-structure-result error-position (car unmatched-tag-list))))
1088 ;;; wesnoth-mode
1089 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
1090 "Major mode for editing WML."
1091 (kill-all-local-variables)
1092 (use-local-map wesnoth-mode-map)
1093 (setq major-mode 'wesnoth-mode)
1094 (setq mode-name "WML")
1095 (set-syntax-table wesnoth-syntax-table)
1096 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
1097 (set (make-local-variable 'comment-start) "#")
1098 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
1099 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
1100 (set (make-local-variable 'font-lock-defaults)
1101 '(wesnoth-font-lock-keywords
1102 nil t nil nil
1103 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
1104 (setq indent-tabs-mode nil)
1105 (easy-menu-add wesnoth-menu wesnoth-mode-map)
1106 (wesnoth-create-wml-hash-table)
1107 (run-hooks 'wesnoth-mode-hook))
1109 (provide 'wesnoth-mode)
1111 ;;; wesnoth-mode.el ends here