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,
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.
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)
32 ;; (add-to-list 'auto-mode-alist '("\\.cfg\\'" . wesnoth-mode))
33 ;; to automatically load wesnoth-mode for all files ending in '.cfg'.
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.
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
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.
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
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'
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
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
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.
130 ;; * Base indent now defaults to 4.
131 ;; * Added support for #ifndef.
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"
147 (defcustom wesnoth-auto-indent-flag t
148 "Non-nil means indent the current line upon creating a newline."
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."
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
)
200 "Keymap used in `wesnoth-mode'.")
202 (easy-menu-define wesnoth-menu wesnoth-mode-map
"Menu for wesnoth-mode"
204 ["Check WML" wesnoth-check-wml t
]
205 ["Indent or Complete" wesnoth-indent-or-complete t
]
206 ["Indent buffer" (lambda ()
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 Preprocessor" wesnoth-complete-preprocessor t
]
213 ["Insert Missing Tag" wesnoth-insert-missing-closing t
]
214 ["Jump to Matching" wesnoth-jump-to-matching t
]))
216 (defvar wesnoth-syntax-table
217 (let ((wesnoth-syntax-table (make-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 ?.
"_" wesnoth-syntax-table
)
222 (modify-syntax-entry ?
\n ">" wesnoth-syntax-table
)
223 (modify-syntax-entry ?
\r ">" wesnoth-syntax-table
)
224 wesnoth-syntax-table
)
225 "Syntax table for `wesnoth-mode'.")
227 ;; Prevents automatic syntax-highlighting of elements which might be
228 ;; pre-processor statements.
229 (defvar wesnoth-syntactic-keywords
231 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\)" 1 "w")
232 '("\\(#[\t ]*.*$\\)" 1 "<"))
233 "Highlighting syntactic keywords within `wesnoth-mode'.")
235 (defvar wesnoth-font-lock-keywords
237 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face
)
238 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
239 font-lock-keyword-face
)
240 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
241 2 font-lock-function-name-face
)
242 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face
))
243 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face
))
244 '("}" . font-lock-function-name-face
)
245 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face
)
246 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face
)
247 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
248 1 font-lock-variable-name-face
))
249 "Syntax highlighting for `wesnoth-mode'.")
251 (defun wesnoth-element-closing (&optional limited
)
252 "Return the regexp to match a closing element.
253 If LIMITED is non-nil, return a regexp which matches only the
254 #enddef preprocessor."
255 (concat "^[\t ]*\\(\\[/\\(\\w\\|_\\)+\\|"
258 "#end\\(?:def\\|if\\)")
261 (defun wesnoth-element-opening (&optional limited
)
262 "Return the regexp to match a closing element.
263 If LIMITED is non-nil, return a regexp which matches only the
264 #define preprocessor."
265 (concat "^[\t ]*\\(\\[\\(\\w\\|_\\)+\\]\\|#define "
271 (defun wesnoth-element (&optional limited
)
272 "Return the regexp to match a closing element.
273 If LIMITED is non-nil, return a regexp which matches only the
274 #define and #enddef preprocessors."
275 (concat "^[\t ]*\\(\\[/?\\(\\w\\|_\\)+\\]?\\|"
278 (substring wesnoth-preprocessor-regexp
5))
282 ;;; Insertion and completion
283 (defmacro wesnoth-element-completion
(completions prompt partial
)
284 "Process completion of COMPLETIONS, displaying PROMPT.
285 PARTIAL is the partial string on which to attempt completion."
286 `(let* ((element (when ,partial
(try-completion ,partial
,completions
))))
287 (cond ((eq element t
)
291 (completing-read ,prompt
,completions nil nil nil
292 'wesnoth-history-list
)))
293 ((not (if (listp (car ,completions
))
294 (assoc element
,completions
)
295 (member element
,completions
)))
297 (completing-read ,prompt
,completions
299 'wesnoth-history-list
))))
302 (defun wesnoth-parent-tag ()
303 "Return the name of the parent tag.
304 If the parent is a preprocessor statement, return non-nil.
305 If the element does not have a parent, return nil.
306 Otherwise, return a string containing the name of the parent tag."
308 (let ((start-point (point))
310 (when (save-excursion (> (point) (progn (back-to-indentation)
313 (while (and (> depth
0)
314 (search-backward-regexp (wesnoth-element)
316 (if (string-match "[\t ]*\\[/" (match-string 0))
322 (when (looking-at (wesnoth-element-opening))
323 (let ((parent (match-string-no-properties 1)))
324 (if (string-match wesnoth-preprocessor-opening-regexp parent
)
326 (substring parent
1 (1- (length parent
))))))))))
328 (defun wesnoth-indent-or-complete (&optional elements
)
329 "Indent or complete the line at point, depending on context.
330 ELEMENTS is the number of elements to wrap around if inserting
333 (or elements
(setq elements
0))
336 (back-to-indentation)
337 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
338 (wesnoth-complete-attribute t
))
339 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
340 (wesnoth-complete-tag elements t
))
341 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
342 (wesnoth-complete-macro t
))
343 ((looking-at "^#\\w+$")
344 (wesnoth-complete-preprocessor elements t
))
345 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
346 (delete-region (point) (progn (end-of-line) (point)))
347 (wesnoth-insert-missing-closing)
351 (setq target
(point)))
354 (defun wesnoth-preprocessor-closed-p (preprocessor)
355 "Determine whether PREPROCESSOR has been closed.
356 PREPROCESSOR is a string matching the preprocessor statement to
359 (back-to-indentation)
360 (wesnoth-jump-to-matching preprocessor
)
362 (if (string= preprocessor
"#define ")
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."
371 (or elements
(setq elements
0))
372 (let* ((completions (wesnoth-emacs-completion-formats
373 '("define" "else" "ifdef" "ifndef"
374 "enddef" "endif" "undef")))
375 (partial (when completep
377 (back-to-indentation)
378 (when (looking-at "#\\(\\w+\\)$")
380 (preprocessor (or (wesnoth-element-completion
381 completions
"Preprocessor: " partial
)
386 (unless (string= "#" (substring preprocessor
0 1))
387 (setq preprocessor
(concat "#" preprocessor
)))
388 (when (string-match "#\\(define\\|ifn?def\\|undef\\)" preprocessor
)
389 (setq preprocessor
(concat preprocessor
" ")))
391 (delete-region (progn (back-to-indentation) (point))
392 (progn (end-of-line) (point))))
393 (wesnoth-preprocessor-closed-p preprocessor
)))))
396 (delete-region (progn (back-to-indentation) (point))
397 (progn (end-of-line) (point))))
398 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor
)
401 (wesnoth-insert-tag elements preprocessor
)
404 (wesnoth-insert-element-separately preprocessor
)))))
406 (defun wesnoth-complete-macro (&optional completep
)
407 "Complete and insert the macro at point.
408 If COMPLETEP is non-nil, attempt to complete the macro at point."
410 (wesnoth-update-project-information)
411 (let* ((macro-information (append wesnoth-macro-data
412 wesnoth-local-macro-data
))
413 (completions (wesnoth-emacs-completion-formats
414 (mapcar 'car macro-information
)))
415 (partial (when completep
417 (back-to-indentation)
418 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
420 (macro (or (wesnoth-element-completion completions
"Macro: " partial
)
422 (args (cadr (assoc macro macro-information
))))
426 (delete-region (progn (back-to-indentation) (point))
427 (progn (end-of-line) (point)))
428 (insert "{" macro
(if args
" }" "}")))
429 (wesnoth-insert-element-separately "{" macro
(if args
" }" "}")))
433 (forward-char -
1)))))
435 (defun wesnoth-complete-attribute (&optional completep
)
436 "Insert the attribute at point.
437 If COMPLETEP is non-nil, attempt to complete the attribute at point."
439 (let* ((completions (wesnoth-build-completion 2))
440 (partial (when completep
442 (back-to-indentation)
443 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
445 (attribute (or (wesnoth-element-completion completions
"Attribute: "
449 (if (and partial completep
)
451 (delete-region (progn (back-to-indentation) (point))
452 (progn (end-of-line) (point)))
453 (insert attribute
"="))
454 (wesnoth-insert-element-separately attribute
455 (if (string-match "=" attribute
)
461 (defun wesnoth-complete-tag (&optional elements completep
)
462 "Complete and insert the tag at point.
463 ELEMENTS is the number of elements to wrap around.
464 If COMPLETEP is non-nil, attempt to complete tag at point."
466 (or elements
(setq elements
0))
467 (let* ((completions (wesnoth-build-completion 1))
468 (partial (when completep
470 (back-to-indentation)
471 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
473 (tag (or (wesnoth-element-completion completions
"Tag: " partial
)
477 (wesnoth-jump-to-matching)
478 (back-to-indentation)
479 (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
480 (string= tag
(match-string 1))))))
482 (delete-region (progn (back-to-indentation) (point))
483 (progn (end-of-line) (point))))
484 (if (and closedp completep
)
486 (wesnoth-insert-and-indent "[" tag
"]")
488 (wesnoth-insert-tag elements tag
))))
490 (defun wesnoth-build-completion (position)
491 "Create a new list for tag completion if necessary.
492 Rebuilding list is required for versions of GNU Emacs earlier
493 than 22. POSITION is the argument passed to `nth' for
496 (let* ((parent (wesnoth-parent-tag))
498 (if (or (stringp parent
) (null parent
))
499 (nth (1- position
) (gethash parent wesnoth-tag-hash-table
))
500 (mapcar 'car wesnoth-tag-data
))))
501 (wesnoth-emacs-completion-formats candidates
)))
503 (defun wesnoth-emacs-completion-formats (candidates)
504 "Return the completions in the correct format for `emacs-major-version'.
505 CANDIDATES is a list of all possible completions."
506 (if (> emacs-major-version
21)
510 (dolist (tag candidates
)
511 (setq iter
(1+ iter
))
512 (setq tags
(append tags
(list (cons tag iter
)))))
515 (defun wesnoth-insert-tag (&optional elements tagname
)
516 "Insert the specified opening tag and it's matching closing tag.
517 Both the opening and closing tags will be placed on their own
518 lines with point positioned between them. Completion of tags at
519 the prompt uses `wesnoth-tags-list'.
521 ELEMENTS is specifies the number of following blocks which the
522 tag should wrap around.
524 TAGNAME is the name of the tag to be inserted."
527 (setq tagname
(completing-read "Tag: " (wesnoth-build-completion 1)
528 nil nil nil wesnoth-history-list
)))
529 (when (or (not elements
)
530 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
531 wesnoth-preprocessor-regexp
"\\)")))
534 (start (save-excursion (forward-line -
1) (point)))
535 (end (unless (= elements
0)
536 (wesnoth-nth-pair-position elements
))))
537 (if (string-match wesnoth-preprocessor-regexp tagname
)
538 (wesnoth-insert-element-separately tagname
)
539 (wesnoth-insert-element-separately "[" tagname
"]"))
542 (goto-char (marker-position end
))
544 (if (string-match wesnoth-preprocessor-opening-regexp tagname
)
545 (wesnoth-insert-element-separately
546 (if (string= tagname
"#define ")
549 (wesnoth-insert-element-separately "[/" tagname
"]"))
550 (indent-region start
(point) nil
))
555 (defun wesnoth-insert-element-separately (&rest strings
)
556 "Concatenate STRINGS and insert them on a line of their own."
557 (let ((create-newline (save-excursion
559 (if (looking-at "^[\t ]*$") nil t
))))
561 (if (> (point) (save-excursion (back-to-indentation) (point)))
567 (insert (apply 'concat strings
))))
569 (defun wesnoth-insert-missing-closing (&optional start end
)
570 "Insert the next expected closing element at point.
572 START and END define the region to check for missing closing
573 elements. If function `transient-mark-mode' is enabled, the region
574 specified will be used as START and END. Otherwise, START and
575 END will be the minimum and current positions of the buffer,
578 (if (and (boundp 'transient-mark-mode
)
579 transient-mark-mode mark-active
)
580 (setq start
(region-beginning)
581 end
(copy-marker (region-end)))
582 (setq start
(point-min)
584 (let ((element (wesnoth-check-structure start end
)))
586 (error "%s" "Unable to find element to insert")
587 (when (string= element
"Unexpected end of file")
588 (error "%s" element
))
589 (wesnoth-insert-element-separately element
)))
593 (defun wesnoth-insert-and-indent (&rest args
)
594 "Concatenate and insert the given string(s) before indenting.
596 ARGS is a list of strings to be inserted."
597 (insert (apply 'concat args
))
600 (defun wesnoth-newline (&optional indent
)
601 "Indent both the current line and the newline created.
602 If `wesnoth-auto-indent-flag' is nil, indentation will not be
603 performed. Indentation can be forced by setting INDENT to
607 (when (and (or wesnoth-auto-indent-flag indent
)
608 (not (looking-at "^[\t ]*$")))
613 (defmacro wesnoth-navigate-element
(repeat search-function bound
)
614 "Move point to the tag in the given direction REPEAT times.
616 SEARCH-FUNCTION is the symbol of the function for searching in
617 the required direction, with BOUND marking the furthest point to
620 (or ,repeat
(setq ,repeat
1))
622 (and (eq ,search-function
'search-forward-regexp
) (end-of-line))
623 (funcall ,search-function
(wesnoth-element-opening) ,bound t
)
624 (back-to-indentation)
627 (defun wesnoth-nth-pair-position (count)
628 "Return `point' after COUNT number of matching element pairs.
629 COUNT is a positive number representing the number of balanced
630 pairs to move across.
631 `point' is returned as a marker object."
633 (let ((start (point))
635 (if (> (point) (save-excursion (back-to-indentation) (point)))
639 ;; Currently looking-at target tag. Stop here to avoid
640 ;; incorrect nesting.
641 (unless (wesnoth-search-for-matching-tag
642 'search-forward-regexp
(wesnoth-element-closing) 'point-max
)
644 (unless (or (= (point) (point-max))
645 (progn (beginning-of-line)
646 (search-backward-regexp (wesnoth-element-closing)
649 (and (> (decf count
) 0) (forward-line 1)))
655 (defun wesnoth-forward-element (repeat)
656 "Move point to the end of the next tag.
657 REPEAT is an optional numeric argument. If REPEAT is non-nil,
658 jump forward the specified number of tags."
661 (wesnoth-backward-element (abs repeat
))
662 (wesnoth-navigate-element repeat
'search-forward-regexp
(point-max))))
664 (defun wesnoth-backward-element (repeat)
665 "Move point to the beginning of the previous tag.
666 REPEAT is an optional numeric argument. If REPEAT is non-nil,
667 jump backward the specified number of tags."
670 (wesnoth-forward-element (abs repeat
))
671 (wesnoth-navigate-element repeat
'search-backward-regexp
(point-min))))
673 (defmacro wesnoth-search-for-matching-tag
(search-function
674 search-string bound
&optional skip
)
675 "Search for the matching tag for the current line.
677 SEARCH-FUNCTION is the name of the function used to perform the search.
678 SEARCH-STRING is a string representing the matching tag type.
679 BOUND is the bound to be passed to the search function.
680 If SKIP is non-nil, skip the first element and continue from there."
682 (when (or (and ,skip
(forward-line 1))
683 (funcall ,search-function
(wesnoth-element) (funcall ,bound
) t
))
684 (when (or ,skip
(not (string-match ,search-string
(match-string 0))))
685 (while (and (> depth
0)
686 (funcall ,search-function
(wesnoth-element)
688 (if (string-match ,search-string
(match-string 0))
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."
701 (if (or (and (stringp opening
)
702 (string-match (wesnoth-element-opening) opening
))
703 (looking-at (wesnoth-element-opening)))
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
710 (if (and (string-match wesnoth-preprocessor-opening-regexp
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))
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
728 (looking-at (wesnoth-element-opening)))
730 (when (or (and (string= "#enddef" first-element
)
732 (match-string-no-properties 0)))
733 (and (string= "#endif" first-element
)
736 (match-string-no-properties 0))))
737 (setq target
(point))))
738 (setq target
(point)))))))
741 (when (interactive-p)
742 (error "Tag does not appear to be matched"))))
743 (back-to-indentation))
746 (defun wesnoth-wml-start-pos ()
747 "Determine the position of `point' relative to where the actual WML begins.
748 Return the likely starting position of the WML if it is found.
749 Otherwise return nil."
751 (goto-char (point-min))
752 (when (search-forward-regexp (wesnoth-element) (point-max) t
)
756 (defun first-column-indent-p (point)
757 "Return non-nil if the current line should not be indented.
759 POINT is the position in the buffer to check.
760 CONTEXT represents the type of element which precedes the current element."
761 (or (not (wesnoth-wml-start-pos))
762 (<= (point) (wesnoth-wml-start-pos))
763 (nth 3 (parse-partial-sexp (point-min) point
))
764 (looking-at wesnoth-preprocessor-regexp
)))
766 (defun wesnoth-indent ()
767 "Indent the current line as WML."
769 (let ((cur-indent 0))
770 (unless (first-column-indent-p (point))
771 (multiple-value-bind (context ref-indent
)
772 (wesnoth-determine-context (point))
774 ((eq context
'opening
)
775 (if (or (and wesnoth-indent-savefile
776 (not (looking-at (wesnoth-element-closing t
))))
777 (looking-at (wesnoth-element-opening t
)))
778 (setq cur-indent
(+ ref-indent wesnoth-base-indent
))
779 (setq cur-indent ref-indent
)))
780 ((eq context
'closing
)
781 (if (or (looking-at "^[\t ]*\\[/")
782 (and (not wesnoth-indent-savefile
)
783 (not (looking-at (wesnoth-element-opening t
)))))
784 (setq cur-indent
(- ref-indent wesnoth-base-indent
))
785 (setq cur-indent ref-indent
))))))
786 (indent-line-to (max cur-indent
0))))
788 (defun wesnoth-within-define (position)
789 "Determine whether point is currently inside a #define block.
790 POSITION is the initial cursor position."
792 (dolist (element (or wesnoth-define-blocks
793 (wesnoth-find-macro-definitions)))
794 (when (= (cadr (sort (append (mapcar 'marker-position
(cadr element
))
795 (list position
)) '>)) position
)
796 (setq depth
(max (car element
) depth
))))
799 (defun wesnoth-find-macro-definitions ()
800 "Return information regarding positioning of macro definitions."
802 (goto-char (point-min))
805 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t
)
806 (and (string= (match-string 1) "#define") (beginning-of-line))
808 (if (string= (match-string 1) "#define")
810 (add-to-list 'openings
(point-marker))
815 (list depth
(list (car openings
)
817 (setq openings
(cdr openings
))
823 (defun wesnoth-indent-region (start end
)
824 "Indent the region from START to END.
826 Creates and destroys a cache of macro definition details as necessary."
831 (setq end
(point-marker))
833 (setq wesnoth-define-blocks
(wesnoth-find-macro-definitions))
834 (or (bolp) (forward-line 1))
835 (while (< (point) end
)
836 (if (looking-at "^[\t ]*$")
838 (funcall indent-line-function
))
840 (setq wesnoth-define-blocks nil
)))
842 (defun wesnoth-determine-context (position)
843 "Determine the type of the last relevant element.
845 POSITION is the buffer position of the element for which to
846 determine the context."
848 (search-backward-regexp (wesnoth-element t
)
849 (wesnoth-wml-start-pos) t
)
850 (let ((match (or (match-string 1) ""))
851 (depth (wesnoth-within-define position
)))
852 (while (and (> (wesnoth-within-define (point)) depth
)
853 (not (= (point) (wesnoth-wml-start-pos))))
854 (search-backward-regexp (wesnoth-element t
)
855 (wesnoth-wml-start-pos) t
)
856 (setq match
(match-string 1)))
857 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth
0)
858 (string-match "#define" match
))
859 ;; Found nothing of use; reset match and assume top-level tag.
862 ((string-match "\\[/\\|#enddef" match
)
863 (values 'closing
(current-indentation)))
864 ((string-match "\\[[^/]?\\|#define" match
)
865 (values 'opening
(current-indentation)))))))
867 (defun wesnoth-newline-and-indent (&optional indent
)
868 "Indent both the current line and the newline created.
869 If `wesnoth-auto-indent-flag' is nil, indentation will not be
872 If the optional argument, INDENT is non-nil, force indentation to
876 (when (or wesnoth-auto-indent-flag indent
)
880 (defun wesnoth-check-element-type (position last-tag
)
881 "Determine the context of the element.
882 POSITION is the position of the element in the list.
883 LAST-TAG is the parent element."
884 (let ((inhibit-changing-match-data t
))
885 (if (or (not last-tag
) (string-match "#\\(?:define\\|ifn?def\\)" last-tag
))
886 (member (match-string-no-properties 1)
887 (mapcar 'car wesnoth-tag-data
))
888 (member (match-string-no-properties 1)
889 (nth position
(gethash last-tag
890 wesnoth-tag-hash-table
))))))
892 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
893 (defun wesnoth-line-number-at-pos (&optional pos
)
894 "Return (narrowed) buffer line number at position POS.
895 If POS is nil, use current buffer location.
896 Counting starts at (point-min), so the value refers
897 to the contents of the accessible portion of the buffer."
898 (let ((opoint (or pos
(point))) start
)
900 (goto-char (point-min))
904 (1+ (count-lines start
(point))))))
906 (defun wesnoth-check-output (buffer format-string
&rest args
)
907 "Output the string as passed to `format'.
908 BUFFER is the buffer to output the result.
909 FORMAT-STRING is the string as the first argument of `format'.
910 ARGS is any additional data required by `format' to handle FORMAT-STRING."
912 (let ((lnap (wesnoth-line-number-at-pos)))
914 (insert (apply 'format
(concat "Line %d: " format-string
"\n")
917 (defun wesnoth-check-wml ()
918 "Perform context-sensitive analysis of WML-code."
920 (wesnoth-update-project-information)
921 (when (= 0 (hash-table-count wesnoth-tag-hash-table
))
922 (error "WML data not available; can not generate report"))
923 (let ((unmatched '())
924 (outbuf (get-buffer-create "*WML*")))
926 (let ((buffer (buffer-name)))
929 (insert (format "Checking %s...\n" buffer
))
930 (message (format "Checking %s..." buffer
))))
932 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
933 (while (search-forward-regexp
934 ;; Match tags, preprocessor statements, macros and attributes.
935 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
936 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
937 wesnoth-preprocessor-regexp
"\\)")
940 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
941 (unless (wesnoth-check-element-type 0 (car unmatched
))
942 (wesnoth-check-output outbuf
943 "Tag not available in this context: '%s'"
944 (match-string-no-properties 1)))
945 (setq unmatched
(cons (match-string-no-properties 1)
948 (concat "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\|#undef\\)"
949 "\\( \\(\\w\\|_\\)+\\)*"))
950 (unless (match-string-no-properties 2)
951 (wesnoth-check-output
952 outbuf
(concat "Preprocessor statement has no argument: "
953 (match-string-no-properties 1))))
954 (unless (string= (match-string-no-properties 1) "#undef")
955 (setq unmatched
(cons (match-string-no-properties 1)
957 ((looking-at wesnoth-preprocessor-closing-regexp
)
960 (cdr (assoc (match-string-no-properties 1)
961 '(("enddef" .
"#define")
962 ("endif" .
"#ifn?def"))))
964 (wesnoth-check-output
966 "Preprocessor statement does not nest correctly"))
967 (setq unmatched
(cdr unmatched
)))
968 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
969 (unless (wesnoth-check-element-type 1 (car unmatched
))
970 (wesnoth-check-output
971 outbuf
"Attribute not available in this context: '%s'"
972 (match-string-no-properties 1)))
973 (unless (match-string 3)
974 (wesnoth-check-output
975 outbuf
"Attribute has no value")))
976 ((looking-at "^[\t ]*#else")
977 (unless (string-match "ifn?def" (car unmatched
))
978 (if (string= (car unmatched
) "#define")
979 (wesnoth-check-output outbuf
"Expecting: '%s'"
981 (wesnoth-check-output outbuf
"Expecting: '[/%s]'"
983 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
984 (unless (assoc (match-string-no-properties 1)
985 (append wesnoth-local-macro-data
987 (wesnoth-check-output outbuf
"Unknown macro definition: '{%s}'"
988 (match-string-no-properties 1))))
989 ((looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]")
991 (not (string= (match-string-no-properties 1)
993 (wesnoth-check-output outbuf
"Expecting: '[/%s]'"
995 (setq unmatched
(cdr unmatched
))))
998 (dolist (tag unmatched
)
999 (wesnoth-check-output outbuf
"Unmatched element: '%s'"
1002 (let ((buffer (buffer-name)))
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 list of unmatched elements."
1017 `(when (string= ,element
(match-string-no-properties 1))
1019 (if (string-match ,requirement
(car unmatched
))
1021 (and ,pop
(setq unmatched
(cdr unmatched
)))
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
))
1032 (cond ((string= ,element
"define ") (setq expected
"#enddef"))
1033 ((string-match "ifn?def " ,element
) (setq expected
"#endif"))))
1035 (if (or ,element
,position
)
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."
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)
1062 (let ((unmatched '())
1063 (error-position nil
))
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
))
1071 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
1072 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
1073 (setq unmatched
(cons (match-string-no-properties 1)
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)
1083 (setq unmatched
(cdr unmatched
))
1084 (setq error-position
(point))))))
1086 (wesnoth-structure-result error-position
(car unmatched
))))
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
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 (wesnoth-update-project-information)
1108 (run-hooks 'wesnoth-mode-hook
))
1110 (provide 'wesnoth-mode
)
1112 ;;; wesnoth-mode.el ends here