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 mode
24 ;; features syntax highlighting support, automatic indentation,
25 ;; tag-completion and preliminary support for syntax 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 ;; * Added support for Xemacs.
38 ;; * WML checking is now context sensitive; checks attributes and macros.
39 ;; * WML checks are now always performed on the entire buffer, with results
40 ;; displayed in a temporary buffer.
41 ;; * Context-sensitive completion for attributes and tags.
42 ;; * Completion for built-in and project-specific macros.
43 ;; * Changed the following bindings:
44 ;; `wesnoth-insert-tag' - C-c e -> C-c t
45 ;; `wesnoth-jump-to-matching' - C-c m -> C-c o
46 ;; `wesnoth-check-structure' -> `wesnoth-check-wml' - C-c c
47 ;; * Added the following bindings:
48 ;; `wesnoth-complete-attribute' - C-c a
49 ;; `wesnoth-complete-macro' - C-c m
50 ;; `wesnoth-complete-tag' - C-c t
51 ;; * Removed the following bindings:
52 ;; `wesnoth-check-tag-names' - C-c n
53 ;; * Removed `wesnoth-check-tag-names'. Replaced by `wesnoth-check-wml'.
54 ;; * Completion for an incomplete attribute, tag, or macro at point is
57 ;; * Fixed support for GNU Emacs 21.
58 ;; * Added several new tags to `wesnoth-tags-list'.
59 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
60 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
61 ;; how many blocks to wrap across instead of a region.
62 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
63 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
64 ;; causing tags not to be inserted in the correct position.
65 ;; * Fixed highlighting of array indexes as tags.
67 ;; * Improved syntax-highlighting for macro calls.
68 ;; * Underscore is now treated as whitespace.
69 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
70 ;; * Point is now placed at the first non-whitespace character of the line,
71 ;; instead of the last.
72 ;; * Corrected minor indentation bugs.
73 ;; * Indenting across large regions is now much more efficient.
74 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
77 ;; * Now compatible with GNU Emacs 21.4.
78 ;; * Added support for several new tags.
79 ;; * Added menu entry for wesnoth-mode.
80 ;; * Significant speed increase to indentation.
81 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
82 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
84 ;; * Trailing whitespace is no longer created when creating a second
85 ;; consecutive newline.
86 ;; * Spurious newlines are no longer created when inserting a tag elements
89 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
90 ;; `wesnoth-element', `wesnoth-element-opening',
91 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
92 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
93 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
94 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
95 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
96 ;; * Fixed a bug in indentation where content was needed between elements pairs
97 ;; for indentation to work.
98 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
99 ;; `wesnoth-auto-indent-flag'.
100 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
101 ;; * Added indentation styles: `wesnoth-indent-default',
102 ;; `wesnoth-indent-withtags' which implement a a similar indentation
103 ;; style to the existing styles, however all preprocessor statements are
104 ;; indented to the first column.
105 ;; * Added support for several new tags.
106 ;; * Modified `wesnoth-newline' to behave more consistently.
107 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
108 ;; now leaves point at the beginning (when moving backward) or end (when
109 ;; moving forward) of the match.
110 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
111 ;; will now work on preprocessor statements. Will now warn if jump
112 ;; destination may not be correct (due to errors in WML structure).
113 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
114 ;; * `wesnoth-check-structure' can now be applied over an active region and
115 ;; now checks preprocessor statements for correct nesting.
116 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
117 ;; perform indentation by providing a prefix argument.
118 ;; * Indentation styles now leave point at the first non-whitespace character
120 ;; * `wesnoth-check-tag-names' now reports on success.
121 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
122 ;; * `outline-minor-mode' now works on macro definitions.
124 ;; * Base indent now defaults to 4.
125 ;; * Added support for #ifndef.
131 (require 'wesnoth-update
)
132 (require 'wesnoth-wml-data
)
134 (defconst wesnoth-mode-version
"1.3.0-git"
135 "The current version of `wesnoth-mode'.")
137 (defgroup wesnoth-mode nil
"Wesnoth-mode access"
141 (defcustom wesnoth-auto-indent-flag t
142 "Non-nil means indent the current line upon creating a newline."
144 :group
'wesnoth-mode
)
146 (defcustom wesnoth-indent-savefile t
147 "Non-nil means to use the current indentation conventions.
148 If nil, use the old convention for indentation.
149 The current convention is all attributes are indented a level deeper
150 than their parent; in the past attributes were indented to the same
151 level as their parent.")
153 (defcustom wesnoth-base-indent
4
154 "The number of columns to indent WML."
156 :group
'wesnoth-mode
)
158 (defconst wesnoth-preprocessor-regexp
159 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def\\)"
160 "Regular expression to match all preprocessor statements.")
162 (defconst wesnoth-preprocessor-opening-regexp
163 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
164 "Regular expression to match \"opening\" preprocessor statements.")
166 (defconst wesnoth-preprocessor-closing-regexp
167 "[\t ]*#\\(e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\)"
168 "Regular expression to match \"closing\" preprocessor statements.")
170 (defvar wesnoth-define-blocks
'()
171 "Cache of all toplevel #define and #enddef pairs.")
173 (defvar wesnoth-mode-hook nil
)
175 (defvar wesnoth-mode-map
176 (let ((map (make-sparse-keymap)))
177 (define-key map
(kbd "C-M-a") 'wesnoth-backward-element
)
178 (define-key map
(kbd "C-M-e") 'wesnoth-forward-element
)
179 (define-key map
(kbd "C-m") 'wesnoth-newline
)
180 (define-key map
(kbd "C-j") 'wesnoth-newline-and-indent
)
181 (define-key map
(kbd "C-c c") 'wesnoth-check-wml
)
182 (define-key map
(kbd "C-c C-c") 'wesnoth-check-wml
)
183 (define-key map
(kbd "C-c a") 'wesnoth-complete-attribute
)
184 (define-key map
(kbd "C-c C-a") 'wesnoth-complete-attribute
)
185 (define-key map
(kbd "C-c t") 'wesnoth-complete-tag
)
186 (define-key map
(kbd "C-c C-t") 'wesnoth-complete-tag
)
187 (define-key map
(kbd "M-TAB") 'wesnoth-complete-tag
)
188 (define-key map
(kbd "C-c m") 'wesnoth-complete-macro
)
189 (define-key map
(kbd "C-c C-m") 'wesnoth-complete-macro
)
190 (define-key map
(kbd "C-c o") 'wesnoth-jump-to-matching
)
191 (define-key map
(kbd "C-c C-o") 'wesnoth-jump-to-matching
)
192 (define-key map
(kbd "C-c /") 'wesnoth-insert-missing-closing
)
193 (define-key map
(kbd "C-c C-/") 'wesnoth-insert-missing-closing
)
194 (define-key map
(kbd "TAB") 'wesnoth-indent-or-complete
)
196 "Keymap used in wesnoth-mode.")
198 (easy-menu-define wesnoth-menu wesnoth-mode-map
"Menu for wesnoth-mode"
200 ["Check WML" wesnoth-check-wml t
]
201 ["Indent buffer" (lambda ()
203 (wesnoth-indent-region (point-min) (point-max))) t
]
204 ["Insert Tag" wesnoth-insert-tag t
]
205 ["Insert Attribute" wesnoth-complete-attribute t
]
206 ["Insert Macro" wesnoth-complete-macro t
]
207 ["Jump to Matching" wesnoth-jump-to-matching t
]
208 ["Insert Missing Tag" wesnoth-insert-missing-closing t
]))
210 (defvar wesnoth-syntax-table
211 (let ((wesnoth-syntax-table (make-syntax-table)))
212 (modify-syntax-entry ?
= "." wesnoth-syntax-table
)
213 (modify-syntax-entry ?_
"_" wesnoth-syntax-table
)
214 (modify-syntax-entry ?-
"_" wesnoth-syntax-table
)
215 (modify-syntax-entry ?.
"_" wesnoth-syntax-table
)
216 (modify-syntax-entry ?
\n ">" wesnoth-syntax-table
)
217 (modify-syntax-entry ?
\r ">" wesnoth-syntax-table
)
218 wesnoth-syntax-table
)
219 "Syntax table for `wesnoth-mode'.")
221 ;; Prevents automatic syntax-highlighting of elements which might be
222 ;; pre-processor statements.
223 (defvar wesnoth-syntactic-keywords
225 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
226 '("\\(#[\t ]*.*$\\)" 1 "<"))
227 "Highlighting syntactic keywords within `wesnoth-mode'.")
229 (defvar wesnoth-font-lock-keywords
231 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" .
232 'font-lock-keyword-face
)
233 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
234 'font-lock-keyword-face
)
235 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
236 2 font-lock-function-name-face
)
237 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)"
238 (1 font-lock-function-name-face
))
239 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)"
240 (1 font-lock-function-name-face
))
241 '("}" . font-lock-function-name-face
)
242 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face
)
243 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face
)
244 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
245 1 font-lock-variable-name-face
))
246 "Syntax highlighting for `wesnoth-mode'.")
248 (defconst wesnoth-element-closing
"^[\t ]*\\(\\[/\\|#enddef\\)"
249 "String to use for a closing element.")
251 (defconst wesnoth-element-opening
"^[\t ]*\\(\\[[^/]\\|#define\\)"
252 "String to use for an opening element.")
254 (defconst wesnoth-element
"^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
255 "String to use for an opening or closing element.")
257 ;;; Insertion and completion
258 (defmacro wesnoth-element-completion
(completions prompt partial
)
259 "Process completion of COMPLETIONS, displaying PROMPT."
260 `(let* ((element (when ,partial
(try-completion ,partial
,completions
))))
261 (cond ((eq element t
)
265 (completing-read ,prompt
,completions
)))
266 ((not (member element
,completions
))
268 (completing-read ,prompt
,completions
272 (defun wesnoth-parent-tag ()
273 "Return the name of the parent tag, nil otherwise."
275 (let ((parent (when (and (wesnoth-wml-start-pos)
276 (> (point) (wesnoth-wml-start-pos)))
277 (wesnoth-check-structure (wesnoth-wml-start-pos)
280 (if (string-match wesnoth-preprocessor-closing-regexp parent
)
282 (substring parent
2 (1- (length parent
))))))))
284 (defun wesnoth-indent-or-complete ()
285 "Indent or complete the line at point, depending on context."
289 (back-to-indentation)
290 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
291 (wesnoth-complete-attribute t
))
292 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
293 (wesnoth-complete-tag t
))
294 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
295 (wesnoth-complete-macro t
))
296 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
297 (delete-region (point) (progn (end-of-line) (point)))
298 (wesnoth-insert-missing-closing)
302 (setq target
(point)))
305 (defun wesnoth-complete-macro (&optional completep
)
306 "Complete and insert the macro at point.
307 If COMPLETEP is non-nil, attempt to complete the macro at point."
309 (let* ((macro-information (append wesnoth-macro-data
310 wesnoth-local-macro-data
))
311 (completions (wesnoth-emacs-completion-formats
312 (mapcar 'car macro-information
)))
313 (partial (when completep
315 (back-to-indentation)
316 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
318 (macro (or (wesnoth-element-completion completions
"Macro: " partial
)
320 (args (cadr (assoc macro macro-information
))))
324 (delete-region (progn (back-to-indentation) (point))
325 (progn (end-of-line) (point)))
326 (insert "{" macro
(if args
" }" "}")))
327 (wesnoth-insert-element-separately "{" macro
(if args
" }" "}")))
331 (forward-char -
1)))))
333 (defun wesnoth-complete-attribute (&optional completep
)
334 "Insert the attribute at point.
335 If COMPLETEP is non-nil, attempt to complete the attribute at point."
337 (let* ((completions (wesnoth-build-completion 2))
338 (partial (when completep
340 (back-to-indentation)
341 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
343 (attribute (or (wesnoth-element-completion completions
"Attribute: "
347 (if (and partial completep
)
349 (delete-region (progn (back-to-indentation) (point))
350 (progn (end-of-line) (point)))
351 (insert attribute
"="))
352 (wesnoth-insert-element-separately attribute
353 (if (string-match "=" attribute
)
359 (defun wesnoth-complete-tag (&optional completep
)
360 "Complete and insert the tag at point.
361 If COMPLETEP is non-nil, attempt to complete tag at point."
363 (let* ((completions (wesnoth-build-completion 1))
364 (partial (when completep
366 (back-to-indentation)
367 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
369 (tag (or (wesnoth-element-completion completions
"Tag: " partial
)
371 (let ((closed-p nil
))
373 (wesnoth-jump-to-matching)
374 (back-to-indentation)
375 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
376 (string= tag
(match-string 1)))
379 (delete-region (progn (back-to-indentation) (point))
380 (progn (end-of-line) (point))))
381 (if (and closed-p completep
)
383 (wesnoth-insert-and-indent "[" tag
"]")
385 (wesnoth-insert-tag nil tag
)))))
387 (defun wesnoth-build-completion (position)
388 "Create a new list for tag completion if necessary.
389 Rebuilding list is required for versions of GNU Emacs earlier
390 than 22. POSITION is the argument passed to `nth' for
393 (let* ((parent (wesnoth-parent-tag))
395 (if (or (stringp parent
) (null parent
))
396 (dolist (tag wesnoth-tag-data
)
397 (when (string= (car tag
) (wesnoth-parent-tag))
398 (return (nth position tag
))))
399 (mapcar 'car wesnoth-tag-data
))))
400 (wesnoth-emacs-completion-formats candidates
)))
402 (defun wesnoth-emacs-completion-formats (candidates)
403 "Return the completions in the correct format for `emacs-major-version'.
404 CANDIDATES is a list of all possible completions."
405 (if (> emacs-major-version
21)
409 (dolist (tag candidates
)
410 (setq iter
(1+ iter
))
411 (setq tags
(append tags
(list (cons tag iter
)))))
414 (defun wesnoth-insert-tag (&optional elements tagname
)
415 "Insert the specified opening tag and it's matching closing tag.
416 Both the opening and closing tags will be placed on their own
417 lines with point positioned between them. Completion of tags at
418 the prompt uses `wesnoth-tags-list'.
420 ELEMENTS is specifies the number of following blocks which the
421 tag should wrap around.
423 TAGNAME is the name of the tag to be inserted."
426 (setq tagname
(completing-read "Tag: " (wesnoth-build-completion 1))))
427 (or elements
(setq elements
0))
429 (start (save-excursion (forward-line -
1) (point)))
430 (end (unless (= elements
0)
431 (wesnoth-nth-pair-position elements
))))
432 (wesnoth-insert-element-separately "[" tagname
"]")
435 (goto-char (marker-position end
))
437 (wesnoth-insert-element-separately "[/" tagname
"]")
438 (indent-region start
(point) nil
))
443 (defun wesnoth-nth-pair-position (count)
444 "Return `point' after COUNT number of matching element pairs.
445 COUNT is a positive number representing the number of balanced
446 pairs to move across.
447 `point' is returned as a marker object."
450 ;; Currently looking-at target tag. Stop here to avoid
451 ;; incorrect nesting.
452 (unless (wesnoth-search-for-matching-tag
453 'search-forward-regexp wesnoth-element-closing
'point-max
)
455 (search-backward-regexp wesnoth-element-closing
(point-min) t
))
456 (and (> (decf count
) 0) (forward-line 1)))
460 (defun wesnoth-insert-element-separately (&rest strings
)
461 "Concatenate STRINGS and insert them on a line of their own."
462 (let ((create-newline (save-excursion
464 (if (looking-at "^[\t ]*$") nil t
))))
466 (if (> (point) (save-excursion (back-to-indentation) (point)))
472 (insert (apply 'concat strings
))))
474 (defun wesnoth-insert-missing-closing (&optional start end
)
475 "Insert the next expected closing element at point.
477 START and END define the region to check for missing closing
478 elements. If function `transient-mark-mode' is enabled, the region
479 specified will be used as START and END. Otherwise, START and
480 END will be the minimum and maximum positions of the buffer,
483 (if (and (boundp 'transient-mark-mode
)
486 (setq start
(region-beginning)
487 end
(copy-marker (region-end)))
488 (setq start
(point-min)
490 (let ((element (wesnoth-check-structure start end
)))
492 (error "%s" "Unable to find element to insert")
493 (when (string= element
"Unexpected end of file")
494 (error "%s" element
))
495 (wesnoth-insert-element-separately element
)))
499 (defun wesnoth-insert-and-indent (&rest args
)
500 "Concatenate and insert the given string(s) before indenting.
502 ARGS is a list of strings to be inserted."
503 (insert (apply 'concat args
))
506 (defun wesnoth-newline (&optional indent
)
507 "Indent both the current line and the newline created.
508 If `wesnoth-auto-indent-flag' is nil, indentation will not be
509 performed. Indentation can be forced by setting INDENT to
513 (when (and (or wesnoth-auto-indent-flag indent
)
514 (not (looking-at "^[\t ]*$")))
519 (defmacro wesnoth-navigate-element
(repeat search-function bound
)
520 "Move point to the tag in the given direction REPEAT times.
522 SEARCH-FUNCTION is the symbol of the function for searching in
523 the required direction, with BOUND marking the furthest point to
526 (or ,repeat
(setq ,repeat
1))
528 (and (eq ,search-function
'search-forward-regexp
) (end-of-line))
529 (funcall ,search-function wesnoth-element-opening
,bound t
)
530 (back-to-indentation)
533 (defun wesnoth-forward-element (repeat)
534 "Move point to the end of the next tag.
535 REPEAT is an optional numeric argument. If REPEAT is non-nil,
536 jump forward the specified number of tags."
539 (wesnoth-backward-element (abs repeat
))
540 (wesnoth-navigate-element repeat
'search-forward-regexp
(point-max))))
542 (defun wesnoth-backward-element (repeat)
543 "Move point to the beginning of the previous tag.
544 REPEAT is an optional numeric argument. If REPEAT is non-nil,
545 jump backward the specified number of tags."
548 (wesnoth-forward-element (abs repeat
))
549 (wesnoth-navigate-element repeat
'search-backward-regexp
(point-min))))
551 (defmacro wesnoth-search-for-matching-tag
(search-function search-string bound
)
552 "Search for the matching tag for the current line.
554 SEARCH-FUNCTION is the name of the function used to perform the search.
555 SEARCH-STRING is a string representing the matching tag type.
556 BOUND is the bound to be passed to the search function."
558 (unless (looking-at ,search-string
)
559 (unless (and (funcall ,bound
) (> (point) (funcall ,bound
)))
561 (while (and (> depth
0)
562 (funcall ,search-function wesnoth-element
564 (if (string-match ,search-string
(match-string 0))
569 (defun wesnoth-jump-to-matching ()
570 "Jump point to the matching opening/closing tag."
573 (if (looking-at wesnoth-element-opening
)
574 (wesnoth-search-for-matching-tag
575 'search-forward-regexp wesnoth-element-closing
'point-max
)
576 (wesnoth-search-for-matching-tag
577 'search-backward-regexp wesnoth-element-opening
'wesnoth-wml-start-pos
))
578 (back-to-indentation))
580 (defun wesnoth-wml-start-pos ()
581 "Determine the position of `point' relative to where the actual WML begins.
582 Return the likely starting position of the WML if it is found.
583 Otherwise return nil."
585 (goto-char (point-min))
586 (when (search-forward-regexp wesnoth-element
(point-max) t
)
590 (defun first-column-indent-p (point)
591 "Return non-nil if the current line should not be indented.
593 POINT is the position in the buffer to check.
594 CONTEXT represents the type of element which precedes the current element."
595 (or (not (wesnoth-wml-start-pos))
596 (<= (point) (wesnoth-wml-start-pos))
597 (nth 3 (parse-partial-sexp (point-min) point
))
598 (looking-at wesnoth-preprocessor-regexp
)))
600 (defun wesnoth-indent ()
601 "Indent the current line as WML."
603 (let ((cur-indent 0))
604 (unless (first-column-indent-p (point))
605 (multiple-value-bind (context ref-indent
)
606 (wesnoth-determine-context (point))
608 ((eq context
'opening
)
609 (if (or (and wesnoth-indent-savefile
610 (not (looking-at wesnoth-element-closing
)))
611 (looking-at wesnoth-element-opening
))
612 (setq cur-indent
(+ ref-indent wesnoth-base-indent
))
613 (setq cur-indent ref-indent
)))
614 ((eq context
'closing
)
615 (if (or (looking-at "^[\t ]*\\[/")
616 (and (not wesnoth-indent-savefile
)
617 (not (looking-at wesnoth-element-opening
))))
618 (setq cur-indent
(- ref-indent wesnoth-base-indent
))
619 (setq cur-indent ref-indent
))))))
620 (indent-line-to (max cur-indent
0))))
622 (defun wesnoth-within-define (position)
623 "Determine whether point is currently inside a #define block.
624 POSITION is the initial cursor position."
626 (dolist (element (or wesnoth-define-blocks
627 (wesnoth-find-macro-definitions)))
628 (when (= (cadr (sort (append (mapcar 'marker-position
(cadr element
))
629 (list position
)) '>)) position
)
630 (setq depth
(max (car element
) depth
))))
633 (defun wesnoth-find-macro-definitions ()
634 "Return information regarding positioning of macro definitions."
636 (goto-char (point-min))
639 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t
)
640 (and (string= (match-string 1) "#define") (beginning-of-line))
642 (if (string= (match-string 1) "#define")
644 (add-to-list 'openings
(point-marker))
647 (list depth
(list (car openings
) (point-marker))))
648 (setq openings
(cdr openings
))
653 (defun wesnoth-indent-region (start end
)
654 "Indent the region from START to END.
656 Creates and destroys a cache of macro definition details as necessary."
661 (setq end
(point-marker))
663 (setq wesnoth-define-blocks
(wesnoth-find-macro-definitions))
664 (or (bolp) (forward-line 1))
665 (while (< (point) end
)
666 (if (looking-at "^[\t ]*$")
668 (funcall indent-line-function
))
670 (setq wesnoth-define-blocks nil
)))
672 (defun wesnoth-determine-context (position)
673 "Determine the type of the last relevant element.
675 POSITION is the buffer position of the element for which to
676 determine the context."
678 (search-backward-regexp wesnoth-element
(wesnoth-wml-start-pos) t
)
679 (let ((match (or (match-string 1) ""))
680 (depth (wesnoth-within-define position
)))
681 (while (and (> (wesnoth-within-define (point)) depth
)
682 (not (= (point) (wesnoth-wml-start-pos))))
683 (search-backward-regexp wesnoth-element
684 (wesnoth-wml-start-pos) t
)
685 (setq match
(match-string 1)))
686 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth
0)
687 (string-match "#define" match
))
688 ;; Found nothing of use; reset match and assume top-level tag.
691 ((string-match "\\[/\\|#enddef" match
)
692 (values 'closing
(current-indentation)))
693 ((string-match "\\[[^/]?\\|#define" match
)
694 (values 'opening
(current-indentation)))))))
696 (defun wesnoth-newline-and-indent (&optional indent
)
697 "Indent both the current line and the newline created.
698 If `wesnoth-auto-indent-flag' is nil, indentation will not be
701 If the optional argument, INDENT is non-nil, force indentation to
705 (when (or wesnoth-auto-indent-flag indent
)
709 (defun wesnoth-check-element-type (position last-tag
)
710 "Determine the context of the element.
711 POSITION is the position of the element in the list.
712 LAST-TAG is the parent element."
713 (if (or (string= last-tag
"#define")
714 (string= last-tag
"#ifndef")
715 (string= last-tag
"#ifdef"))
716 (member (match-string-no-properties 1)
717 (mapcar 'car wesnoth-tag-data
))
719 (dolist (tag wesnoth-tag-data
)
720 (when (member (match-string-no-properties 1)
721 (funcall position tag
))
722 (add-to-list 'result
(car tag
))))
723 (member last-tag result
))))
725 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
726 (defun wesnoth-line-number-at-pos (&optional pos
)
727 "Return (narrowed) buffer line number at position POS.
728 If POS is nil, use current buffer location.
729 Counting starts at (point-min), so the value refers
730 to the contents of the accessible portion of the buffer."
731 (let ((opoint (or pos
(point))) start
)
733 (goto-char (point-min))
737 (1+ (count-lines start
(point))))))
739 (defun wesnoth-check-output (buffer format-string
&rest args
)
740 "Output the string as passed to `format'.
741 BUFFER is the buffer to output the result.
742 FORMAT-STRING is the string as the first argument of `format'.
743 ARGS is any additional data required by `format' to handle FORMAT-STRING."
745 (let ((lnap (wesnoth-line-number-at-pos)))
747 (insert (apply 'format
(concat "%d: " format-string
"\n")
750 (defun wesnoth-check-wml ()
751 "Perform context-sensitive analysis of WML-code."
753 (wesnoth-update-project-information)
754 (unless wesnoth-tag-data
755 (error "WML data not available; can not generate report"))
756 (let ((unmatched-tag-list '())
757 (outbuf (get-buffer-create "*WML*")))
759 (let ((buffer (buffer-name)))
762 (message (format "Checking %s..." buffer
))))
764 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
765 (while (search-forward-regexp
766 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
767 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
768 wesnoth-preprocessor-regexp
"\\)")
771 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
772 (unless (wesnoth-check-element-type 'second
773 (car unmatched-tag-list
))
774 (wesnoth-check-output outbuf
775 "Tag not available in this context: '%s'"
776 (match-string-no-properties 1)))
777 (setq unmatched-tag-list
(cons
778 (match-string-no-properties 1)
779 unmatched-tag-list
)))
780 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
781 (setq unmatched-tag-list
(cons (match-string-no-properties 1)
782 unmatched-tag-list
)))
783 ((looking-at wesnoth-preprocessor-closing-regexp
)
784 (unless (string= (car unmatched-tag-list
)
785 (second (assoc (match-string-no-properties 1)
786 '(("enddef" "#define")
788 ("ifndef" "#endif")))))
789 (wesnoth-check-output
791 "Preprocessor statement does not nest correctly"))
792 (setq unmatched-tag-list
(cdr unmatched-tag-list
)))
793 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
794 (unless (wesnoth-check-element-type 'third
795 (car unmatched-tag-list
))
796 (wesnoth-check-output
797 outbuf
"Attribute not available in this context: '%s'"
798 (match-string-no-properties 1)))
799 (unless (match-string 3)
800 (wesnoth-check-output
801 outbuf
"Attribute has no value")))
802 ((looking-at "^[\t ]*#else")
803 (unless (string-match "ifn?def" (car unmatched-tag-list
))
804 (if (string= (car unmatched-tag-list
) "#define")
805 (wesnoth-check-output outbuf
"Expecting: '%s'"
806 (car unmatched-tag-list
))
807 (wesnoth-check-output outbuf
"Expecting: '[/%s]'"
808 (car unmatched-tag-list
)))))
809 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
810 (unless (assoc (match-string-no-properties 1)
811 (append wesnoth-local-macro-data
813 (wesnoth-check-output outbuf
"Unknown macro definition: '{%s}'"
814 (match-string-no-properties 1))))
815 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
816 (unless (string= (match-string-no-properties 1)
817 (car unmatched-tag-list
))
818 (if (string-match "^#.+" (car unmatched-tag-list
))
819 (wesnoth-check-output outbuf
"Expecting: '#%s'"
821 (assoc (car unmatched-tag-list
)
822 '(("define" "#enddef")
824 ("endif" "#ifndef")))))
825 (wesnoth-check-output outbuf
"Expecting: '[/%s]'"
826 (car unmatched-tag-list
))))
827 (setq unmatched-tag-list
(cdr unmatched-tag-list
))))
829 (if unmatched-tag-list
830 (dolist (tag unmatched-tag-list
)
831 (wesnoth-check-output outbuf
"Unmatched tag: '%s'"
832 (car unmatched-tag-list
)))))
834 (let ((buffer (buffer-name)))
836 (display-buffer outbuf t
)
837 (message (format "Checking %s...done" buffer
))))))
839 (defmacro wesnoth-element-requires
(element requirement
&optional pop
)
840 "Process requirements for corresponding preprocessor elements.
841 ELEMENT is the current element being tested.
842 REQUIREMENT is the element required to exist for correct nesting.
843 POP is an optional argument indicating the element should be
844 removed from the unmatched-tag-list."
845 `(when (string= ,element
(match-string-no-properties 1))
847 (if (string-match ,requirement
(car unmatched-tag-list
))
849 (and ,pop
(setq unmatched-tag-list
(cdr unmatched-tag-list
)))
851 (setq error-position
(point)))))
853 (defmacro wesnoth-structure-result
(position element
)
854 "Process results of the structure check.
855 POSITION is the error position or nil, if no error was found.
856 ELEMENT is the last unmatched element, or nil if all opening
857 elements have been matched."
858 `(let ((expected nil
))
860 (cond ((string= ,element
"define ") (setq expected
"#enddef"))
861 ((string-match "ifn?def " ,element
) (setq expected
"#endif"))))
863 (if (or ,element
,position
)
865 (and ,position
(goto-char ,position
))
866 (message "Error: Expecting %s" (or expected
867 (concat "[/" ,element
"]"))))
868 (message "%s" "Structure appears consistent."))
869 (when (or expected
,element
)
870 (or expected
(concat "[/" ,element
"]"))))))
872 (defun wesnoth-check-structure (&optional start end
)
873 "Check the buffer for correct nesting of elements.
874 If a problem is found in the structure, point will be placed at
875 the location which an element was expected and the expected
876 element will be displayed in the mini-buffer.
878 START and END define the region to be checked. If
879 function `transient-mark-mode' is enabled, the region specified will be
880 checked. Otherwise START and END will be the minimum and maximum
881 positions of the buffer, respectively."
883 (unless (or start end
)
884 (if (and (boundp 'transient-mark-mode
)
885 transient-mark-mode mark-active
)
886 (setq start
(region-beginning)
887 end
(copy-marker (region-end)))
888 (setq start
(point-min)
890 (let ((unmatched-tag-list '())
891 (error-position nil
))
893 (and start
(goto-char start
))
894 (while (and (search-forward-regexp
895 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
896 wesnoth-preprocessor-regexp
"\\)") end t
)
897 (not error-position
))
899 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
900 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
901 (setq unmatched-tag-list
(cons (match-string-no-properties 1)
904 ((wesnoth-element-requires "#else" "ifn?def "))
905 ((wesnoth-element-requires "#endif" "ifn?def " t
))
906 ((wesnoth-element-requires "#enddef" "define " t
))
907 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
908 wesnoth-preprocessor-closing-regexp
))
909 (if (string= (match-string-no-properties 1)
910 (car unmatched-tag-list
))
911 (setq unmatched-tag-list
(cdr unmatched-tag-list
))
912 (setq error-position
(point))))))
914 (wesnoth-structure-result error-position
(car unmatched-tag-list
))))
917 (define-derived-mode wesnoth-mode fundamental-mode
"wesnoth-mode"
918 "Major mode for editing WML."
919 (kill-all-local-variables)
920 (use-local-map wesnoth-mode-map
)
921 (setq major-mode
'wesnoth-mode
)
922 (setq mode-name
"WML")
923 (set-syntax-table wesnoth-syntax-table
)
924 (set (make-local-variable 'outline-regexp
) "[\t ]*#define")
925 (set (make-local-variable 'comment-start
) "#")
926 (set (make-local-variable 'indent-line-function
) 'wesnoth-indent
)
927 (set (make-local-variable 'indent-region-function
) 'wesnoth-indent-region
)
928 (set (make-local-variable 'font-lock-defaults
)
929 '(wesnoth-font-lock-keywords
931 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords
)))
932 (setq indent-tabs-mode nil
)
933 (easy-menu-add wesnoth-menu wesnoth-mode-map
)
934 (run-hooks 'wesnoth-mode-hook
))
936 (provide 'wesnoth-mode
)
938 ;;; wesnoth-mode.el ends here