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"
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-c") 'wesnoth-check-wml
)
182 (define-key map
(kbd "C-c C-a") 'wesnoth-complete-attribute
)
183 (define-key map
(kbd "C-c C-t") 'wesnoth-complete-tag
)
184 (define-key map
(kbd "M-TAB") 'wesnoth-complete-tag
)
185 (define-key map
(kbd "C-c C-m") 'wesnoth-complete-macro
)
186 (define-key map
(kbd "C-c C-o") 'wesnoth-jump-to-matching
)
187 (define-key map
(kbd "C-c C-/") 'wesnoth-insert-missing-closing
)
188 (define-key map
(kbd "TAB") 'wesnoth-indent-or-complete
)
190 "Keymap used in `wesnoth-mode'.")
192 (easy-menu-define wesnoth-menu wesnoth-mode-map
"Menu for wesnoth-mode"
194 ["Check WML" wesnoth-check-wml t
]
195 ["Indent or Complete" wesnoth-indent-or-complete t
]
196 ["Indent buffer" (lambda ()
198 (wesnoth-indent-region (point-min) (point-max))) t
]
199 ["Insert Tag" wesnoth-complete-tag t
]
200 ["Insert Attribute" wesnoth-complete-attribute t
]
201 ["Insert Macro" wesnoth-complete-macro t
]
202 ["Jump to Matching" wesnoth-jump-to-matching t
]
203 ["Insert Missing Tag" wesnoth-insert-missing-closing t
]))
205 (defvar wesnoth-syntax-table
206 (let ((wesnoth-syntax-table (make-syntax-table)))
207 (modify-syntax-entry ?
= "." wesnoth-syntax-table
)
208 (modify-syntax-entry ?_
"_" wesnoth-syntax-table
)
209 (modify-syntax-entry ?-
"_" wesnoth-syntax-table
)
210 (modify-syntax-entry ?.
"_" wesnoth-syntax-table
)
211 (modify-syntax-entry ?
\n ">" wesnoth-syntax-table
)
212 (modify-syntax-entry ?
\r ">" wesnoth-syntax-table
)
213 wesnoth-syntax-table
)
214 "Syntax table for `wesnoth-mode'.")
216 ;; Prevents automatic syntax-highlighting of elements which might be
217 ;; pre-processor statements.
218 (defvar wesnoth-syntactic-keywords
220 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
221 '("\\(#[\t ]*.*$\\)" 1 "<"))
222 "Highlighting syntactic keywords within `wesnoth-mode'.")
224 (defvar wesnoth-font-lock-keywords
226 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face
)
227 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
228 font-lock-keyword-face
)
229 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
230 2 font-lock-function-name-face
)
231 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face
))
232 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face
))
233 '("}" . font-lock-function-name-face
)
234 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face
)
235 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face
)
236 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
237 1 font-lock-variable-name-face
))
238 "Syntax highlighting for `wesnoth-mode'.")
240 (defconst wesnoth-element-closing
"^[\t ]*\\(\\[/\\|#enddef\\)"
241 "String to use for a closing element.")
243 (defconst wesnoth-element-opening
"^[\t ]*\\(\\[[^/]\\|#define\\)"
244 "String to use for an opening element.")
246 (defconst wesnoth-element
"^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
247 "String to use for an opening or closing element.")
249 ;;; Insertion and completion
250 (defmacro wesnoth-element-completion
(completions prompt partial
)
251 "Process completion of COMPLETIONS, displaying PROMPT.
252 PARTIAL is the partial string on which to attempt completion."
253 `(let* ((element (when ,partial
(try-completion ,partial
,completions
))))
254 (cond ((eq element t
)
258 (completing-read ,prompt
,completions
)))
259 ((not (if (listp (car ,completions
))
260 (assoc element
,completions
)
261 (member element
,completions
)))
263 (completing-read ,prompt
,completions
267 (defun wesnoth-parent-tag ()
268 "Return the name of the parent tag, nil otherwise."
270 (let ((parent (when (and (wesnoth-wml-start-pos)
271 (> (point) (wesnoth-wml-start-pos)))
272 (wesnoth-check-structure (wesnoth-wml-start-pos)
275 (if (string-match wesnoth-preprocessor-closing-regexp parent
)
277 (substring parent
2 (1- (length parent
))))))))
279 (defun wesnoth-indent-or-complete (&optional elements
)
280 "Indent or complete the line at point, depending on context.
281 ELEMENTS is the number of elements to wrap around if inserting
284 (or elements
(setq elements
0))
287 (back-to-indentation)
288 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
289 (wesnoth-complete-attribute t
))
290 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
291 (wesnoth-complete-tag elements t
))
292 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
293 (wesnoth-complete-macro t
))
294 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
295 (delete-region (point) (progn (end-of-line) (point)))
296 (wesnoth-insert-missing-closing)
300 (setq target
(point)))
303 (defun wesnoth-complete-macro (&optional completep
)
304 "Complete and insert the macro at point.
305 If COMPLETEP is non-nil, attempt to complete the macro at point."
307 (let* ((macro-information (append wesnoth-macro-data
308 wesnoth-local-macro-data
))
309 (completions (wesnoth-emacs-completion-formats
310 (mapcar 'car macro-information
)))
311 (partial (when completep
313 (back-to-indentation)
314 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
316 (macro (or (wesnoth-element-completion completions
"Macro: " partial
)
318 (args (cadr (assoc macro macro-information
))))
322 (delete-region (progn (back-to-indentation) (point))
323 (progn (end-of-line) (point)))
324 (insert "{" macro
(if args
" }" "}")))
325 (wesnoth-insert-element-separately "{" macro
(if args
" }" "}")))
329 (forward-char -
1)))))
331 (defun wesnoth-complete-attribute (&optional completep
)
332 "Insert the attribute at point.
333 If COMPLETEP is non-nil, attempt to complete the attribute at point."
335 (let* ((completions (wesnoth-build-completion 2))
336 (partial (when completep
338 (back-to-indentation)
339 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
341 (attribute (or (wesnoth-element-completion completions
"Attribute: "
345 (if (and partial completep
)
347 (delete-region (progn (back-to-indentation) (point))
348 (progn (end-of-line) (point)))
349 (insert attribute
"="))
350 (wesnoth-insert-element-separately attribute
351 (if (string-match "=" attribute
)
357 (defun wesnoth-complete-tag (&optional elements completep
)
358 "Complete and insert the tag at point.
359 ELEMENTS is the number of elements to wrap around.
360 If COMPLETEP is non-nil, attempt to complete tag at point."
362 (or elements
(setq elements
0))
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 elements 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 (when (or (not elements
)
428 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
429 wesnoth-preprocessor-regexp
"\\)")))
432 (start (save-excursion (forward-line -
1) (point)))
433 (end (unless (= elements
0)
434 (wesnoth-nth-pair-position elements
))))
435 (wesnoth-insert-element-separately "[" tagname
"]")
438 (goto-char (marker-position end
))
440 (wesnoth-insert-element-separately "[/" tagname
"]")
441 (indent-region start
(point) nil
))
446 (defun wesnoth-nth-pair-position (count)
447 "Return `point' after COUNT number of matching element pairs.
448 COUNT is a positive number representing the number of balanced
449 pairs to move across.
450 `point' is returned as a marker object."
452 (let ((start (point))
454 (if (> (point) (save-excursion (back-to-indentation) (point)))
458 ;; Currently looking-at target tag. Stop here to avoid
459 ;; incorrect nesting.
460 (unless (wesnoth-search-for-matching-tag
461 'search-forward-regexp wesnoth-element-closing
'point-max
)
463 (unless (or (= (point) (point-max))
464 (progn (beginning-of-line)
465 (search-backward-regexp wesnoth-element-closing
468 (and (> (decf count
) 0) (forward-line 1)))
474 (defun wesnoth-insert-element-separately (&rest strings
)
475 "Concatenate STRINGS and insert them on a line of their own."
476 (let ((create-newline (save-excursion
478 (if (looking-at "^[\t ]*$") nil t
))))
480 (if (> (point) (save-excursion (back-to-indentation) (point)))
486 (insert (apply 'concat strings
))))
488 (defun wesnoth-insert-missing-closing (&optional start end
)
489 "Insert the next expected closing element at point.
491 START and END define the region to check for missing closing
492 elements. If function `transient-mark-mode' is enabled, the region
493 specified will be used as START and END. Otherwise, START and
494 END will be the minimum and maximum positions of the buffer,
497 (if (and (boundp 'transient-mark-mode
)
500 (setq start
(region-beginning)
501 end
(copy-marker (region-end)))
502 (setq start
(point-min)
504 (let ((element (wesnoth-check-structure start end
)))
506 (error "%s" "Unable to find element to insert")
507 (when (string= element
"Unexpected end of file")
508 (error "%s" element
))
509 (wesnoth-insert-element-separately element
)))
513 (defun wesnoth-insert-and-indent (&rest args
)
514 "Concatenate and insert the given string(s) before indenting.
516 ARGS is a list of strings to be inserted."
517 (insert (apply 'concat args
))
520 (defun wesnoth-newline (&optional indent
)
521 "Indent both the current line and the newline created.
522 If `wesnoth-auto-indent-flag' is nil, indentation will not be
523 performed. Indentation can be forced by setting INDENT to
527 (when (and (or wesnoth-auto-indent-flag indent
)
528 (not (looking-at "^[\t ]*$")))
533 (defmacro wesnoth-navigate-element
(repeat search-function bound
)
534 "Move point to the tag in the given direction REPEAT times.
536 SEARCH-FUNCTION is the symbol of the function for searching in
537 the required direction, with BOUND marking the furthest point to
540 (or ,repeat
(setq ,repeat
1))
542 (and (eq ,search-function
'search-forward-regexp
) (end-of-line))
543 (funcall ,search-function wesnoth-element-opening
,bound t
)
544 (back-to-indentation)
547 (defun wesnoth-forward-element (repeat)
548 "Move point to the end of the next tag.
549 REPEAT is an optional numeric argument. If REPEAT is non-nil,
550 jump forward the specified number of tags."
553 (wesnoth-backward-element (abs repeat
))
554 (wesnoth-navigate-element repeat
'search-forward-regexp
(point-max))))
556 (defun wesnoth-backward-element (repeat)
557 "Move point to the beginning of the previous tag.
558 REPEAT is an optional numeric argument. If REPEAT is non-nil,
559 jump backward the specified number of tags."
562 (wesnoth-forward-element (abs repeat
))
563 (wesnoth-navigate-element repeat
'search-backward-regexp
(point-min))))
565 (defmacro wesnoth-search-for-matching-tag
(search-function search-string bound
)
566 "Search for the matching tag for the current line.
568 SEARCH-FUNCTION is the name of the function used to perform the search.
569 SEARCH-STRING is a string representing the matching tag type.
570 BOUND is the bound to be passed to the search function."
572 (when (funcall ,search-function wesnoth-element
(funcall ,bound
) t
)
573 (unless (string-match ,search-string
(match-string 0))
574 (while (and (> depth
0)
575 (funcall ,search-function wesnoth-element
577 (if (string-match ,search-string
(match-string 0))
582 (defun wesnoth-jump-to-matching ()
583 "Jump point to the matching opening/closing tag."
586 (if (looking-at wesnoth-element-opening
)
587 (wesnoth-search-for-matching-tag
588 'search-forward-regexp wesnoth-element-closing
'point-max
)
590 (wesnoth-search-for-matching-tag
591 'search-backward-regexp wesnoth-element-opening
'wesnoth-wml-start-pos
))
592 (back-to-indentation))
594 (defun wesnoth-wml-start-pos ()
595 "Determine the position of `point' relative to where the actual WML begins.
596 Return the likely starting position of the WML if it is found.
597 Otherwise return nil."
599 (goto-char (point-min))
600 (when (search-forward-regexp wesnoth-element
(point-max) t
)
604 (defun first-column-indent-p (point)
605 "Return non-nil if the current line should not be indented.
607 POINT is the position in the buffer to check.
608 CONTEXT represents the type of element which precedes the current element."
609 (or (not (wesnoth-wml-start-pos))
610 (<= (point) (wesnoth-wml-start-pos))
611 (nth 3 (parse-partial-sexp (point-min) point
))
612 (looking-at wesnoth-preprocessor-regexp
)))
614 (defun wesnoth-indent ()
615 "Indent the current line as WML."
617 (let ((cur-indent 0))
618 (unless (first-column-indent-p (point))
619 (multiple-value-bind (context ref-indent
)
620 (wesnoth-determine-context (point))
622 ((eq context
'opening
)
623 (if (or (and wesnoth-indent-savefile
624 (not (looking-at wesnoth-element-closing
)))
625 (looking-at wesnoth-element-opening
))
626 (setq cur-indent
(+ ref-indent wesnoth-base-indent
))
627 (setq cur-indent ref-indent
)))
628 ((eq context
'closing
)
629 (if (or (looking-at "^[\t ]*\\[/")
630 (and (not wesnoth-indent-savefile
)
631 (not (looking-at wesnoth-element-opening
))))
632 (setq cur-indent
(- ref-indent wesnoth-base-indent
))
633 (setq cur-indent ref-indent
))))))
634 (indent-line-to (max cur-indent
0))))
636 (defun wesnoth-within-define (position)
637 "Determine whether point is currently inside a #define block.
638 POSITION is the initial cursor position."
640 (dolist (element (or wesnoth-define-blocks
641 (wesnoth-find-macro-definitions)))
642 (when (= (cadr (sort (append (mapcar 'marker-position
(cadr element
))
643 (list position
)) '>)) position
)
644 (setq depth
(max (car element
) depth
))))
647 (defun wesnoth-find-macro-definitions ()
648 "Return information regarding positioning of macro definitions."
650 (goto-char (point-min))
653 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t
)
654 (and (string= (match-string 1) "#define") (beginning-of-line))
656 (if (string= (match-string 1) "#define")
658 (add-to-list 'openings
(point-marker))
661 (list depth
(list (car openings
) (point-marker))))
662 (setq openings
(cdr openings
))
667 (defun wesnoth-indent-region (start end
)
668 "Indent the region from START to END.
670 Creates and destroys a cache of macro definition details as necessary."
675 (setq end
(point-marker))
677 (setq wesnoth-define-blocks
(wesnoth-find-macro-definitions))
678 (or (bolp) (forward-line 1))
679 (while (< (point) end
)
680 (if (looking-at "^[\t ]*$")
682 (funcall indent-line-function
))
684 (setq wesnoth-define-blocks nil
)))
686 (defun wesnoth-determine-context (position)
687 "Determine the type of the last relevant element.
689 POSITION is the buffer position of the element for which to
690 determine the context."
692 (search-backward-regexp wesnoth-element
(wesnoth-wml-start-pos) t
)
693 (let ((match (or (match-string 1) ""))
694 (depth (wesnoth-within-define position
)))
695 (while (and (> (wesnoth-within-define (point)) depth
)
696 (not (= (point) (wesnoth-wml-start-pos))))
697 (search-backward-regexp wesnoth-element
698 (wesnoth-wml-start-pos) t
)
699 (setq match
(match-string 1)))
700 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth
0)
701 (string-match "#define" match
))
702 ;; Found nothing of use; reset match and assume top-level tag.
705 ((string-match "\\[/\\|#enddef" match
)
706 (values 'closing
(current-indentation)))
707 ((string-match "\\[[^/]?\\|#define" match
)
708 (values 'opening
(current-indentation)))))))
710 (defun wesnoth-newline-and-indent (&optional indent
)
711 "Indent both the current line and the newline created.
712 If `wesnoth-auto-indent-flag' is nil, indentation will not be
715 If the optional argument, INDENT is non-nil, force indentation to
719 (when (or wesnoth-auto-indent-flag indent
)
723 (defun wesnoth-check-element-type (position last-tag
)
724 "Determine the context of the element.
725 POSITION is the position of the element in the list.
726 LAST-TAG is the parent element."
727 (if (or (string= last-tag
"#define")
728 (string= last-tag
"#ifndef")
729 (string= last-tag
"#ifdef"))
730 (member (match-string-no-properties 1)
731 (mapcar 'car wesnoth-tag-data
))
733 (dolist (tag wesnoth-tag-data
)
734 (when (member (match-string-no-properties 1)
735 (funcall position tag
))
736 (add-to-list 'result
(car tag
))))
737 (member last-tag result
))))
739 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
740 (defun wesnoth-line-number-at-pos (&optional pos
)
741 "Return (narrowed) buffer line number at position POS.
742 If POS is nil, use current buffer location.
743 Counting starts at (point-min), so the value refers
744 to the contents of the accessible portion of the buffer."
745 (let ((opoint (or pos
(point))) start
)
747 (goto-char (point-min))
751 (1+ (count-lines start
(point))))))
753 (defun wesnoth-check-output (buffer format-string
&rest args
)
754 "Output the string as passed to `format'.
755 BUFFER is the buffer to output the result.
756 FORMAT-STRING is the string as the first argument of `format'.
757 ARGS is any additional data required by `format' to handle FORMAT-STRING."
759 (let ((lnap (wesnoth-line-number-at-pos)))
761 (insert (apply 'format
(concat "Line %d: " format-string
"\n")
764 (defun wesnoth-check-wml ()
765 "Perform context-sensitive analysis of WML-code."
767 (wesnoth-update-project-information)
768 (unless wesnoth-tag-data
769 (error "WML data not available; can not generate report"))
770 (let ((unmatched-tag-list '())
771 (outbuf (get-buffer-create "*WML*")))
773 (let ((buffer (buffer-name)))
776 (insert (format "Checking %s...\n" buffer
))
777 (message (format "Checking %s..." buffer
))))
779 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
780 (while (search-forward-regexp
781 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
782 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
783 wesnoth-preprocessor-regexp
"\\)")
786 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
787 (unless (wesnoth-check-element-type 'second
788 (car unmatched-tag-list
))
789 (wesnoth-check-output outbuf
790 "Tag not available in this context: '%s'"
791 (match-string-no-properties 1)))
792 (setq unmatched-tag-list
(cons
793 (match-string-no-properties 1)
794 unmatched-tag-list
)))
795 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
796 (setq unmatched-tag-list
(cons (match-string-no-properties 1)
797 unmatched-tag-list
)))
798 ((looking-at wesnoth-preprocessor-closing-regexp
)
799 (unless (string= (car unmatched-tag-list
)
800 (second (assoc (match-string-no-properties 1)
801 '(("enddef" "#define")
803 ("ifndef" "#endif")))))
804 (wesnoth-check-output
806 "Preprocessor statement does not nest correctly"))
807 (setq unmatched-tag-list
(cdr unmatched-tag-list
)))
808 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
809 (unless (wesnoth-check-element-type 'third
810 (car unmatched-tag-list
))
811 (wesnoth-check-output
812 outbuf
"Attribute not available in this context: '%s'"
813 (match-string-no-properties 1)))
814 (unless (match-string 3)
815 (wesnoth-check-output
816 outbuf
"Attribute has no value")))
817 ((looking-at "^[\t ]*#else")
818 (unless (string-match "ifn?def" (car unmatched-tag-list
))
819 (if (string= (car unmatched-tag-list
) "#define")
820 (wesnoth-check-output outbuf
"Expecting: '%s'"
821 (car unmatched-tag-list
))
822 (wesnoth-check-output outbuf
"Expecting: '[/%s]'"
823 (car unmatched-tag-list
)))))
824 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
825 (unless (assoc (match-string-no-properties 1)
826 (append wesnoth-local-macro-data
828 (wesnoth-check-output outbuf
"Unknown macro definition: '{%s}'"
829 (match-string-no-properties 1))))
830 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
831 (unless (string= (match-string-no-properties 1)
832 (car unmatched-tag-list
))
833 (if (string-match "^#.+" (car unmatched-tag-list
))
834 (wesnoth-check-output outbuf
"Expecting: '#%s'"
836 (assoc (car unmatched-tag-list
)
837 '(("define" "#enddef")
839 ("endif" "#ifndef")))))
840 (wesnoth-check-output outbuf
"Expecting: '[/%s]'"
841 (car unmatched-tag-list
))))
842 (setq unmatched-tag-list
(cdr unmatched-tag-list
))))
844 (if unmatched-tag-list
845 (dolist (tag unmatched-tag-list
)
846 (wesnoth-check-output outbuf
"Unmatched tag: '%s'"
847 (car unmatched-tag-list
)))))
849 (let ((buffer (buffer-name)))
851 (display-buffer outbuf t
)
852 (let ((warnings (- (wesnoth-line-number-at-pos
853 (save-excursion (goto-char (point-max)))) 2)))
854 (insert (format (concat "\nCheck complete. %d warning"
855 (if (= warnings
1) "." "s.")) warnings
)))
856 (message (format "Checking %s...done" buffer
))))))
858 (defmacro wesnoth-element-requires
(element requirement
&optional pop
)
859 "Process requirements for corresponding preprocessor elements.
860 ELEMENT is the current element being tested.
861 REQUIREMENT is the element required to exist for correct nesting.
862 POP is an optional argument indicating the element should be
863 removed from the unmatched-tag-list."
864 `(when (string= ,element
(match-string-no-properties 1))
866 (if (string-match ,requirement
(car unmatched-tag-list
))
868 (and ,pop
(setq unmatched-tag-list
(cdr unmatched-tag-list
)))
870 (setq error-position
(point)))))
872 (defmacro wesnoth-structure-result
(position element
)
873 "Process results of the structure check.
874 POSITION is the error position or nil, if no error was found.
875 ELEMENT is the last unmatched element, or nil if all opening
876 elements have been matched."
877 `(let ((expected nil
))
879 (cond ((string= ,element
"define ") (setq expected
"#enddef"))
880 ((string-match "ifn?def " ,element
) (setq expected
"#endif"))))
882 (if (or ,element
,position
)
884 (and ,position
(goto-char ,position
))
885 (message "Error: Expecting %s" (or expected
886 (concat "[/" ,element
"]"))))
887 (message "%s" "Structure appears consistent."))
888 (when (or expected
,element
)
889 (or expected
(concat "[/" ,element
"]"))))))
891 (defun wesnoth-check-structure (&optional start end
)
892 "Check the buffer for correct nesting of elements.
893 If a problem is found in the structure, point will be placed at
894 the location which an element was expected and the expected
895 element will be displayed in the mini-buffer.
897 START and END define the region to be checked. If
898 function `transient-mark-mode' is enabled, the region specified will be
899 checked. Otherwise START and END will be the minimum and maximum
900 positions of the buffer, respectively."
902 (unless (or start end
)
903 (if (and (boundp 'transient-mark-mode
)
904 transient-mark-mode mark-active
)
905 (setq start
(region-beginning)
906 end
(copy-marker (region-end)))
907 (setq start
(point-min)
909 (let ((unmatched-tag-list '())
910 (error-position nil
))
912 (and start
(goto-char start
))
913 (while (and (search-forward-regexp
914 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
915 wesnoth-preprocessor-regexp
"\\)") end t
)
916 (not error-position
))
918 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
919 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
920 (setq unmatched-tag-list
(cons (match-string-no-properties 1)
923 ((wesnoth-element-requires "#else" "ifn?def "))
924 ((wesnoth-element-requires "#endif" "ifn?def " t
))
925 ((wesnoth-element-requires "#enddef" "define " t
))
926 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
927 wesnoth-preprocessor-closing-regexp
))
928 (if (string= (match-string-no-properties 1)
929 (car unmatched-tag-list
))
930 (setq unmatched-tag-list
(cdr unmatched-tag-list
))
931 (setq error-position
(point))))))
933 (wesnoth-structure-result error-position
(car unmatched-tag-list
))))
936 (define-derived-mode wesnoth-mode fundamental-mode
"wesnoth-mode"
937 "Major mode for editing WML."
938 (kill-all-local-variables)
939 (use-local-map wesnoth-mode-map
)
940 (setq major-mode
'wesnoth-mode
)
941 (setq mode-name
"WML")
942 (set-syntax-table wesnoth-syntax-table
)
943 (set (make-local-variable 'outline-regexp
) "[\t ]*#define")
944 (set (make-local-variable 'comment-start
) "#")
945 (set (make-local-variable 'indent-line-function
) 'wesnoth-indent
)
946 (set (make-local-variable 'indent-region-function
) 'wesnoth-indent-region
)
947 (set (make-local-variable 'font-lock-defaults
)
948 '(wesnoth-font-lock-keywords
950 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords
)))
951 (setq indent-tabs-mode nil
)
952 (easy-menu-add wesnoth-menu wesnoth-mode-map
)
953 (run-hooks 'wesnoth-mode-hook
))
955 (provide 'wesnoth-mode
)
957 ;;; wesnoth-mode.el ends here