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 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
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
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\\|_\\)+\\|"
257 "#end\\(?:def\\|if\\)")
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 "
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\\|_\\)+\\]?\\|"
277 (substring wesnoth-preprocessor-regexp
5))
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
)
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
)))
296 (completing-read ,prompt
,completions
298 'wesnoth-history-list
))))
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."
307 (let ((start-point (point))
309 (when (save-excursion (> (point) (progn (back-to-indentation)
312 (while (and (> depth
0)
313 (search-backward-regexp (wesnoth-element)
315 (if (string-match "[\t ]*\\[/" (match-string 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
332 (or elements
(setq elements
0))
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)
350 (setq target
(point)))
353 (defun wesnoth-preprocessor-closed-p (preprocessor)
354 "Determine whether PREPROCESSOR has been closed.
355 PREPROCESSOR is a string matching the preprocessor statement to
358 (back-to-indentation)
359 (wesnoth-jump-to-matching preprocessor
)
361 (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 '("define" "else" "ifdef" "ifndef"
373 "enddef" "endif" "undef"))
374 (partial (when completep
376 (back-to-indentation)
377 (when (looking-at "#\\(\\w+\\)$")
379 (preprocessor (or (wesnoth-element-completion
380 completions
"Preprocessor: " partial
)
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
" ")))
390 (delete-region (progn (back-to-indentation) (point))
391 (progn (end-of-line) (point))))
392 (wesnoth-preprocessor-closed-p preprocessor
)))))
395 (delete-region (progn (back-to-indentation) (point))
396 (progn (end-of-line) (point))))
397 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor
)
400 (wesnoth-insert-tag elements preprocessor
)
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."
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
415 (back-to-indentation)
416 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
418 (macro (or (wesnoth-element-completion completions
"Macro: " partial
)
420 (args (cadr (assoc macro macro-information
))))
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
" }" "}")))
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."
437 (let* ((completions (wesnoth-build-completion 2))
438 (partial (when completep
440 (back-to-indentation)
441 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
443 (attribute (or (wesnoth-element-completion completions
"Attribute: "
447 (if (and partial completep
)
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
)
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."
464 (or elements
(setq elements
0))
465 (let* ((completions (wesnoth-build-completion 1))
466 (partial (when completep
468 (back-to-indentation)
469 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
471 (tag (or (wesnoth-element-completion completions
"Tag: " partial
)
475 (wesnoth-jump-to-matching)
476 (back-to-indentation)
477 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
478 (string= tag
(match-string 1)))
481 (delete-region (progn (back-to-indentation) (point))
482 (progn (end-of-line) (point))))
483 (if (and closedp completep
)
485 (wesnoth-insert-and-indent "[" tag
"]")
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
495 (let* ((parent (wesnoth-parent-tag))
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)
509 (dolist (tag candidates
)
510 (setq iter
(1+ iter
))
511 (setq tags
(append tags
(list (cons tag iter
)))))
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."
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
"\\)")))
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
"]"))
541 (goto-char (marker-position end
))
543 (if (string-match wesnoth-preprocessor-opening-regexp tagname
)
544 (wesnoth-insert-element-separately
545 (if (string= tagname
"#define ")
548 (wesnoth-insert-element-separately "[/" tagname
"]"))
549 (indent-region start
(point) nil
))
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."
560 (let ((start (point))
562 (if (> (point) (save-excursion (back-to-indentation) (point)))
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
)
571 (unless (or (= (point) (point-max))
572 (progn (beginning-of-line)
573 (search-backward-regexp (wesnoth-element-closing)
576 (and (> (decf count
) 0) (forward-line 1)))
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
586 (if (looking-at "^[\t ]*$") nil t
))))
588 (if (> (point) (save-excursion (back-to-indentation) (point)))
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,
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)
611 (let ((element (wesnoth-check-structure start end
)))
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
)))
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
))
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
634 (when (and (or wesnoth-auto-indent-flag indent
)
635 (not (looking-at "^[\t ]*$")))
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
647 (or ,repeat
(setq ,repeat
1))
649 (and (eq ,search-function
'search-forward-regexp
) (end-of-line))
650 (funcall ,search-function
(wesnoth-element-opening) ,bound t
)
651 (back-to-indentation)
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."
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."
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."
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)
687 (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))
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."
750 (goto-char (point-min))
751 (when (search-forward-regexp (wesnoth-element) (point-max) t
)
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."
768 (let ((cur-indent 0))
769 (unless (first-column-indent-p (point))
770 (multiple-value-bind (context ref-indent
)
771 (wesnoth-determine-context (point))
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."
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
))))
798 (defun wesnoth-find-macro-definitions ()
799 "Return information regarding positioning of macro definitions."
801 (goto-char (point-min))
804 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t
)
805 (and (string= (match-string 1) "#define") (beginning-of-line))
807 (if (string= (match-string 1) "#define")
809 (add-to-list 'openings
(point-marker))
814 (list depth
(list (car openings
)
816 (setq openings
(cdr openings
))
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."
830 (setq end
(point-marker))
832 (setq wesnoth-define-blocks
(wesnoth-find-macro-definitions))
833 (or (bolp) (forward-line 1))
834 (while (< (point) end
)
835 (if (looking-at "^[\t ]*$")
837 (funcall indent-line-function
))
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."
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.
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
871 If the optional argument, INDENT is non-nil, force indentation to
875 (when (or wesnoth-auto-indent-flag indent
)
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
)
899 (goto-char (point-min))
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."
911 (let ((lnap (wesnoth-line-number-at-pos)))
913 (insert (apply 'format
(concat "Line %d: " format-string
"\n")
916 (defun wesnoth-check-wml ()
917 "Perform context-sensitive analysis of WML-code."
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*")))
925 (let ((buffer (buffer-name)))
928 (insert (format "Checking %s...\n" buffer
))
929 (message (format "Checking %s..." buffer
))))
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
"\\)")
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
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
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'"
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
))))
997 (if unmatched-tag-list
998 (dolist (tag unmatched-tag-list
)
999 (wesnoth-check-output outbuf
"Unmatched tag: '%s'"
1000 (car unmatched-tag-list
)))))
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 unmatched-tag-list."
1017 `(when (string= ,element
(match-string-no-properties 1))
1019 (if (string-match ,requirement
(car unmatched-tag-list
))
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
))
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-tag-list '())
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-tag-list
(cons (match-string-no-properties 1)
1074 unmatched-tag-list
))
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))))))
1086 (wesnoth-structure-result error-position
(car unmatched-tag-list
))))
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 (run-hooks 'wesnoth-mode-hook
))
1109 (provide 'wesnoth-mode
)
1111 ;;; wesnoth-mode.el ends here