* wesnoth-mode.el (wesnoth-menu): Added wesnoth-indent-or-complete.
[wesnoth-mode.git] / wesnoth-mode.el
blob398416ae76491b2cc5d2581c4a73f4daceb15bf8
1 ;;; wesnoth-mode.el --- A major mode for editing WML.
2 ;; Copyright (C) 2006, 2007, 2008 Chris Mann
4 ;; This file is part of wesnoth-mode.
6 ;; This program is free software; you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation; either version 2 of the
9 ;; License, or (at your option) any later version.
11 ;; This program is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;; General Public License for more details.
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with this program; see the file COPYING. If not, write to the
18 ;; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
19 ;; MA 02139, USA.
21 ;;; Description:
22 ;; wesnoth-mode is a major mode for Emacs which assists in the editing
23 ;; of Wesnoth Markup Language (WML) files. Currently, this mode
24 ;; features syntax highlighting support, automatic indentation,
25 ;; tag-completion and preliminary support for syntax checking.
27 ;;; Commentary:
28 ;; Add the following to your .emacs:
29 ;; (add-to-list 'load-path "path/to/wesnoth-mode")
30 ;; (autoload 'wesnoth-mode "wesnoth-mode" "Major mode for editing WML." t)
31 ;; Optionally adding:
32 ;; (add-to-list 'auto-mode-alist '("\\.cfg\\'" . wesnoth-mode))
33 ;; to automatically load wesnoth-mode for all files ending in '.cfg'.
35 ;;; History:
36 ;; 1.3.0
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
55 ;; attempted via TAB.
56 ;; 1.2.5
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.
66 ;; 1.2.4
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
75 ;; applied.
76 ;; 1.2.3
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'
83 ;; has been removed.
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
87 ;; around a region.
88 ;; 1.2.2
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
119 ;; of the line.
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.
123 ;; 1.2.1
124 ;; * Base indent now defaults to 4.
125 ;; * Added support for #ifndef.
127 ;;; Code:
128 (eval-when-compile
129 (require 'cl))
130 (require 'easymenu)
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"
138 :group 'languages
139 :prefix "wesnoth-")
141 (defcustom wesnoth-auto-indent-flag t
142 "Non-nil means indent the current line upon creating a newline."
143 :type 'boolean
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."
155 :type 'integer
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)
195 map)
196 "Keymap used in wesnoth-mode.")
198 (easy-menu-define wesnoth-menu wesnoth-mode-map "Menu for wesnoth-mode"
199 '("WML"
200 ["Check WML" wesnoth-check-wml t]
201 ["Indent or Complete" wesnoth-indent-or-complete t]
202 ["Indent buffer" (lambda ()
203 (interactive)
204 (wesnoth-indent-region (point-min) (point-max))) t]
205 ["Insert Tag" wesnoth-complete-tag t]
206 ["Insert Attribute" wesnoth-complete-attribute t]
207 ["Insert Macro" wesnoth-complete-macro t]
208 ["Jump to Matching" wesnoth-jump-to-matching t]
209 ["Insert Missing Tag" wesnoth-insert-missing-closing t]))
211 (defvar wesnoth-syntax-table
212 (let ((wesnoth-syntax-table (make-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 ?. "_" wesnoth-syntax-table)
217 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
218 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
219 wesnoth-syntax-table)
220 "Syntax table for `wesnoth-mode'.")
222 ;; Prevents automatic syntax-highlighting of elements which might be
223 ;; pre-processor statements.
224 (defvar wesnoth-syntactic-keywords
225 (list
226 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
227 '("\\(#[\t ]*.*$\\)" 1 "<"))
228 "Highlighting syntactic keywords within `wesnoth-mode'.")
230 (defvar wesnoth-font-lock-keywords
231 (list
232 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" .
233 'font-lock-keyword-face)
234 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
235 'font-lock-keyword-face)
236 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
237 2 font-lock-function-name-face)
238 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)"
239 (1 font-lock-function-name-face))
240 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)"
241 (1 font-lock-function-name-face))
242 '("}" . font-lock-function-name-face)
243 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face)
244 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
245 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
246 1 font-lock-variable-name-face))
247 "Syntax highlighting for `wesnoth-mode'.")
249 (defconst wesnoth-element-closing "^[\t ]*\\(\\[/\\|#enddef\\)"
250 "String to use for a closing element.")
252 (defconst wesnoth-element-opening "^[\t ]*\\(\\[[^/]\\|#define\\)"
253 "String to use for an opening element.")
255 (defconst wesnoth-element "^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
256 "String to use for an opening or closing element.")
258 ;;; Insertion and completion
259 (defmacro wesnoth-element-completion (completions prompt partial)
260 "Process completion of COMPLETIONS, displaying PROMPT."
261 `(let* ((element (when ,partial (try-completion ,partial ,completions))))
262 (cond ((eq element t)
263 (setq element nil))
264 ((null element)
265 (setq element
266 (completing-read ,prompt ,completions)))
267 ((not (if (listp (car ,completions))
268 (assoc element ,completions)
269 (member element ,completions)))
270 (setq element
271 (completing-read ,prompt ,completions
272 nil nil ,partial))))
273 element))
275 (defun wesnoth-parent-tag ()
276 "Return the name of the parent tag, nil otherwise."
277 (save-excursion
278 (let ((parent (when (and (wesnoth-wml-start-pos)
279 (> (point) (wesnoth-wml-start-pos)))
280 (wesnoth-check-structure (wesnoth-wml-start-pos)
281 (point)))))
282 (when parent
283 (if (string-match wesnoth-preprocessor-closing-regexp parent)
285 (substring parent 2 (1- (length parent))))))))
287 (defun wesnoth-indent-or-complete ()
288 "Indent or complete the line at point, depending on context."
289 (interactive)
290 (let ((target nil))
291 (save-excursion
292 (back-to-indentation)
293 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
294 (wesnoth-complete-attribute t))
295 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
296 (wesnoth-complete-tag t))
297 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
298 (wesnoth-complete-macro t))
299 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
300 (delete-region (point) (progn (end-of-line) (point)))
301 (wesnoth-insert-missing-closing)
302 (end-of-line))
304 (wesnoth-indent)))
305 (setq target (point)))
306 (goto-char target)))
308 (defun wesnoth-complete-macro (&optional completep)
309 "Complete and insert the macro at point.
310 If COMPLETEP is non-nil, attempt to complete the macro at point."
311 (interactive)
312 (let* ((macro-information (append wesnoth-macro-data
313 wesnoth-local-macro-data))
314 (completions (wesnoth-emacs-completion-formats
315 (mapcar 'car macro-information)))
316 (partial (when completep
317 (save-excursion
318 (back-to-indentation)
319 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
320 (match-string 1)))))
321 (macro (or (wesnoth-element-completion completions "Macro: " partial)
322 partial))
323 (args (cadr (assoc macro macro-information))))
324 (when macro
325 (if partial
326 (progn
327 (delete-region (progn (back-to-indentation) (point))
328 (progn (end-of-line) (point)))
329 (insert "{" macro (if args " }" "}")))
330 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
331 (save-excursion
332 (wesnoth-indent))
333 (when args
334 (forward-char -1)))))
336 (defun wesnoth-complete-attribute (&optional completep)
337 "Insert the attribute at point.
338 If COMPLETEP is non-nil, attempt to complete the attribute at point."
339 (interactive)
340 (let* ((completions (wesnoth-build-completion 2))
341 (partial (when completep
342 (save-excursion
343 (back-to-indentation)
344 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
345 (match-string 1)))))
346 (attribute (or (wesnoth-element-completion completions "Attribute: "
347 partial)
348 partial)))
349 (when attribute
350 (if (and partial completep)
351 (progn
352 (delete-region (progn (back-to-indentation) (point))
353 (progn (end-of-line) (point)))
354 (insert attribute "="))
355 (wesnoth-insert-element-separately attribute
356 (if (string-match "=" attribute)
358 "=")))
359 (save-excursion
360 (wesnoth-indent)))))
362 (defun wesnoth-complete-tag (&optional completep)
363 "Complete and insert the tag at point.
364 If COMPLETEP is non-nil, attempt to complete tag at point."
365 (interactive)
366 (let* ((completions (wesnoth-build-completion 1))
367 (partial (when completep
368 (save-excursion
369 (back-to-indentation)
370 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
371 (match-string 1)))))
372 (tag (or (wesnoth-element-completion completions "Tag: " partial)
373 partial)))
374 (let ((closed-p nil))
375 (save-excursion
376 (wesnoth-jump-to-matching)
377 (back-to-indentation)
378 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
379 (string= tag (match-string 1)))
380 (setq closed-p t)))
381 (when completep
382 (delete-region (progn (back-to-indentation) (point))
383 (progn (end-of-line) (point))))
384 (if (and closed-p completep)
385 (progn
386 (wesnoth-insert-and-indent "[" tag "]")
387 (end-of-line))
388 (wesnoth-insert-tag nil tag)))))
390 (defun wesnoth-build-completion (position)
391 "Create a new list for tag completion if necessary.
392 Rebuilding list is required for versions of GNU Emacs earlier
393 than 22. POSITION is the argument passed to `nth' for
394 `wesnoth-tag-data'."
395 (interactive "P")
396 (let* ((parent (wesnoth-parent-tag))
397 (candidates
398 (if (or (stringp parent) (null parent))
399 (dolist (tag wesnoth-tag-data)
400 (when (string= (car tag) (wesnoth-parent-tag))
401 (return (nth position tag))))
402 (mapcar 'car wesnoth-tag-data))))
403 (wesnoth-emacs-completion-formats candidates)))
405 (defun wesnoth-emacs-completion-formats (candidates)
406 "Return the completions in the correct format for `emacs-major-version'.
407 CANDIDATES is a list of all possible completions."
408 (if (> emacs-major-version 21)
409 candidates
410 (let ((tags '())
411 (iter 0))
412 (dolist (tag candidates)
413 (setq iter (1+ iter))
414 (setq tags (append tags (list (cons tag iter)))))
415 tags)))
417 (defun wesnoth-insert-tag (&optional elements tagname)
418 "Insert the specified opening tag and it's matching closing tag.
419 Both the opening and closing tags will be placed on their own
420 lines with point positioned between them. Completion of tags at
421 the prompt uses `wesnoth-tags-list'.
423 ELEMENTS is specifies the number of following blocks which the
424 tag should wrap around.
426 TAGNAME is the name of the tag to be inserted."
427 (interactive "Ps")
428 (unless tagname
429 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 1))))
430 (or elements (setq elements 0))
431 (let ((depth 0)
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 "]")
436 (save-excursion
437 (if end
438 (goto-char (marker-position end))
439 (newline 2))
440 (wesnoth-insert-element-separately "[/" tagname "]")
441 (indent-region start (point) nil))
442 (unless end
443 (forward-line 1)))
444 (wesnoth-indent))
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."
451 (save-excursion
452 (while (> count 0)
453 ;; Currently looking-at target tag. Stop here to avoid
454 ;; incorrect nesting.
455 (unless (wesnoth-search-for-matching-tag
456 'search-forward-regexp wesnoth-element-closing 'point-max)
457 (setq count 0)
458 (search-backward-regexp wesnoth-element-closing (point-min) t))
459 (and (> (decf count) 0) (forward-line 1)))
460 (end-of-line)
461 (point-marker)))
463 (defun wesnoth-insert-element-separately (&rest strings)
464 "Concatenate STRINGS and insert them on a line of their own."
465 (let ((create-newline (save-excursion
466 (beginning-of-line)
467 (if (looking-at "^[\t ]*$") nil t))))
468 (when create-newline
469 (if (> (point) (save-excursion (back-to-indentation) (point)))
470 (progn
471 (end-of-line)
472 (newline))
473 (beginning-of-line)
474 (open-line 1)))
475 (insert (apply 'concat strings))))
477 (defun wesnoth-insert-missing-closing (&optional start end)
478 "Insert the next expected closing element at point.
480 START and END define the region to check for missing closing
481 elements. If function `transient-mark-mode' is enabled, the region
482 specified will be used as START and END. Otherwise, START and
483 END will be the minimum and maximum positions of the buffer,
484 respectively."
485 (interactive)
486 (if (and (boundp 'transient-mark-mode)
487 transient-mark-mode
488 mark-active)
489 (setq start (region-beginning)
490 end (copy-marker (region-end)))
491 (setq start (point-min)
492 end (point-max)))
493 (let ((element (wesnoth-check-structure start end)))
494 (if (not element)
495 (error "%s" "Unable to find element to insert")
496 (when (string= element "Unexpected end of file")
497 (error "%s" element))
498 (wesnoth-insert-element-separately element)))
499 (wesnoth-indent)
500 (end-of-line))
502 (defun wesnoth-insert-and-indent (&rest args)
503 "Concatenate and insert the given string(s) before indenting.
505 ARGS is a list of strings to be inserted."
506 (insert (apply 'concat args))
507 (wesnoth-indent))
509 (defun wesnoth-newline (&optional indent)
510 "Indent both the current line and the newline created.
511 If `wesnoth-auto-indent-flag' is nil, indentation will not be
512 performed. Indentation can be forced by setting INDENT to
513 non-nil."
514 (interactive)
515 (save-excursion
516 (when (and (or wesnoth-auto-indent-flag indent)
517 (not (looking-at "^[\t ]*$")))
518 (wesnoth-indent)))
519 (newline))
521 ;;; Movement
522 (defmacro wesnoth-navigate-element (repeat search-function bound)
523 "Move point to the tag in the given direction REPEAT times.
525 SEARCH-FUNCTION is the symbol of the function for searching in
526 the required direction, with BOUND marking the furthest point to
527 search."
528 `(progn
529 (or ,repeat (setq ,repeat 1))
530 (while (> ,repeat 0)
531 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
532 (funcall ,search-function wesnoth-element-opening ,bound t)
533 (back-to-indentation)
534 (decf ,repeat))))
536 (defun wesnoth-forward-element (repeat)
537 "Move point to the end of the next tag.
538 REPEAT is an optional numeric argument. If REPEAT is non-nil,
539 jump forward the specified number of tags."
540 (interactive "p")
541 (if (< repeat 0)
542 (wesnoth-backward-element (abs repeat))
543 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
545 (defun wesnoth-backward-element (repeat)
546 "Move point to the beginning of the previous tag.
547 REPEAT is an optional numeric argument. If REPEAT is non-nil,
548 jump backward the specified number of tags."
549 (interactive "p")
550 (if (< repeat 0)
551 (wesnoth-forward-element (abs repeat))
552 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
554 (defmacro wesnoth-search-for-matching-tag (search-function search-string bound)
555 "Search for the matching tag for the current line.
557 SEARCH-FUNCTION is the name of the function used to perform the search.
558 SEARCH-STRING is a string representing the matching tag type.
559 BOUND is the bound to be passed to the search function."
560 `(let ((depth 1))
561 (unless (looking-at ,search-string)
562 (unless (and (funcall ,bound) (> (point) (funcall ,bound)))
563 (end-of-line))
564 (while (and (> depth 0)
565 (funcall ,search-function wesnoth-element
566 (funcall ,bound) t))
567 (if (string-match ,search-string (match-string 0))
568 (decf depth)
569 (incf depth)))
570 t)))
572 (defun wesnoth-jump-to-matching ()
573 "Jump point to the matching opening/closing tag."
574 (interactive)
575 (beginning-of-line)
576 (if (looking-at wesnoth-element-opening)
577 (wesnoth-search-for-matching-tag
578 'search-forward-regexp wesnoth-element-closing 'point-max)
579 (wesnoth-search-for-matching-tag
580 'search-backward-regexp wesnoth-element-opening 'wesnoth-wml-start-pos))
581 (back-to-indentation))
583 (defun wesnoth-wml-start-pos ()
584 "Determine the position of `point' relative to where the actual WML begins.
585 Return the likely starting position of the WML if it is found.
586 Otherwise return nil."
587 (save-excursion
588 (goto-char (point-min))
589 (when (search-forward-regexp wesnoth-element (point-max) t)
590 (beginning-of-line)
591 (point))))
593 (defun first-column-indent-p (point)
594 "Return non-nil if the current line should not be indented.
596 POINT is the position in the buffer to check.
597 CONTEXT represents the type of element which precedes the current element."
598 (or (not (wesnoth-wml-start-pos))
599 (<= (point) (wesnoth-wml-start-pos))
600 (nth 3 (parse-partial-sexp (point-min) point))
601 (looking-at wesnoth-preprocessor-regexp)))
603 (defun wesnoth-indent ()
604 "Indent the current line as WML."
605 (beginning-of-line)
606 (let ((cur-indent 0))
607 (unless (first-column-indent-p (point))
608 (multiple-value-bind (context ref-indent)
609 (wesnoth-determine-context (point))
610 (cond
611 ((eq context 'opening)
612 (if (or (and wesnoth-indent-savefile
613 (not (looking-at wesnoth-element-closing)))
614 (looking-at wesnoth-element-opening))
615 (setq cur-indent (+ ref-indent wesnoth-base-indent))
616 (setq cur-indent ref-indent)))
617 ((eq context 'closing)
618 (if (or (looking-at "^[\t ]*\\[/")
619 (and (not wesnoth-indent-savefile)
620 (not (looking-at wesnoth-element-opening))))
621 (setq cur-indent (- ref-indent wesnoth-base-indent))
622 (setq cur-indent ref-indent))))))
623 (indent-line-to (max cur-indent 0))))
625 (defun wesnoth-within-define (position)
626 "Determine whether point is currently inside a #define block.
627 POSITION is the initial cursor position."
628 (let ((depth 0))
629 (dolist (element (or wesnoth-define-blocks
630 (wesnoth-find-macro-definitions)))
631 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
632 (list position)) '>)) position)
633 (setq depth (max (car element) depth))))
634 depth))
636 (defun wesnoth-find-macro-definitions ()
637 "Return information regarding positioning of macro definitions."
638 (save-excursion
639 (goto-char (point-min))
640 (let ((depth 0)
641 openings cache)
642 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t)
643 (and (string= (match-string 1) "#define") (beginning-of-line))
644 (setq depth
645 (if (string= (match-string 1) "#define")
646 (progn
647 (add-to-list 'openings (point-marker))
648 (1+ depth))
649 (add-to-list 'cache
650 (list depth (list (car openings) (point-marker))))
651 (setq openings (cdr openings))
652 (1- depth)))
653 (end-of-line))
654 cache)))
656 (defun wesnoth-indent-region (start end)
657 "Indent the region from START to END.
659 Creates and destroys a cache of macro definition details as necessary."
660 (interactive "r")
661 (unwind-protect
662 (save-excursion
663 (goto-char end)
664 (setq end (point-marker))
665 (goto-char start)
666 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
667 (or (bolp) (forward-line 1))
668 (while (< (point) end)
669 (if (looking-at "^[\t ]*$")
670 (indent-line-to 0)
671 (funcall indent-line-function))
672 (forward-line 1)))
673 (setq wesnoth-define-blocks nil)))
675 (defun wesnoth-determine-context (position)
676 "Determine the type of the last relevant element.
678 POSITION is the buffer position of the element for which to
679 determine the context."
680 (save-excursion
681 (search-backward-regexp wesnoth-element (wesnoth-wml-start-pos) t)
682 (let ((match (or (match-string 1) ""))
683 (depth (wesnoth-within-define position)))
684 (while (and (> (wesnoth-within-define (point)) depth)
685 (not (= (point) (wesnoth-wml-start-pos))))
686 (search-backward-regexp wesnoth-element
687 (wesnoth-wml-start-pos) t)
688 (setq match (match-string 1)))
689 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth 0)
690 (string-match "#define" match))
691 ;; Found nothing of use; reset match and assume top-level tag.
692 (setq match ""))
693 (cond
694 ((string-match "\\[/\\|#enddef" match)
695 (values 'closing (current-indentation)))
696 ((string-match "\\[[^/]?\\|#define" match)
697 (values 'opening (current-indentation)))))))
699 (defun wesnoth-newline-and-indent (&optional indent)
700 "Indent both the current line and the newline created.
701 If `wesnoth-auto-indent-flag' is nil, indentation will not be
702 performed.
704 If the optional argument, INDENT is non-nil, force indentation to
705 be performed."
706 (interactive)
707 (wesnoth-newline)
708 (when (or wesnoth-auto-indent-flag indent)
709 (wesnoth-indent)))
711 ;;; WML checks
712 (defun wesnoth-check-element-type (position last-tag)
713 "Determine the context of the element.
714 POSITION is the position of the element in the list.
715 LAST-TAG is the parent element."
716 (if (or (string= last-tag "#define")
717 (string= last-tag "#ifndef")
718 (string= last-tag "#ifdef"))
719 (member (match-string-no-properties 1)
720 (mapcar 'car wesnoth-tag-data))
721 (let ((result '()))
722 (dolist (tag wesnoth-tag-data)
723 (when (member (match-string-no-properties 1)
724 (funcall position tag))
725 (add-to-list 'result (car tag))))
726 (member last-tag result))))
728 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
729 (defun wesnoth-line-number-at-pos (&optional pos)
730 "Return (narrowed) buffer line number at position POS.
731 If POS is nil, use current buffer location.
732 Counting starts at (point-min), so the value refers
733 to the contents of the accessible portion of the buffer."
734 (let ((opoint (or pos (point))) start)
735 (save-excursion
736 (goto-char (point-min))
737 (setq start (point))
738 (goto-char opoint)
739 (forward-line 0)
740 (1+ (count-lines start (point))))))
742 (defun wesnoth-check-output (buffer format-string &rest args)
743 "Output the string as passed to `format'.
744 BUFFER is the buffer to output the result.
745 FORMAT-STRING is the string as the first argument of `format'.
746 ARGS is any additional data required by `format' to handle FORMAT-STRING."
747 (save-excursion
748 (let ((lnap (wesnoth-line-number-at-pos)))
749 (set-buffer buffer)
750 (insert (apply 'format (concat "%d: " format-string "\n")
751 lnap args)))))
753 (defun wesnoth-check-wml ()
754 "Perform context-sensitive analysis of WML-code."
755 (interactive)
756 (wesnoth-update-project-information)
757 (unless wesnoth-tag-data
758 (error "WML data not available; can not generate report"))
759 (let ((unmatched-tag-list '())
760 (outbuf (get-buffer-create "*WML*")))
761 (save-excursion
762 (let ((buffer (buffer-name)))
763 (set-buffer outbuf)
764 (erase-buffer)
765 (message (format "Checking %s..." buffer))))
766 (save-excursion
767 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
768 (while (search-forward-regexp
769 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
770 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
771 wesnoth-preprocessor-regexp "\\)")
772 (point-max) t)
773 (beginning-of-line)
774 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
775 (unless (wesnoth-check-element-type 'second
776 (car unmatched-tag-list))
777 (wesnoth-check-output outbuf
778 "Tag not available in this context: '%s'"
779 (match-string-no-properties 1)))
780 (setq unmatched-tag-list (cons
781 (match-string-no-properties 1)
782 unmatched-tag-list)))
783 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
784 (setq unmatched-tag-list (cons (match-string-no-properties 1)
785 unmatched-tag-list)))
786 ((looking-at wesnoth-preprocessor-closing-regexp)
787 (unless (string= (car unmatched-tag-list)
788 (second (assoc (match-string-no-properties 1)
789 '(("enddef" "#define")
790 ("ifdef" "#endif")
791 ("ifndef" "#endif")))))
792 (wesnoth-check-output
793 outbuf
794 "Preprocessor statement does not nest correctly"))
795 (setq unmatched-tag-list (cdr unmatched-tag-list)))
796 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
797 (unless (wesnoth-check-element-type 'third
798 (car unmatched-tag-list))
799 (wesnoth-check-output
800 outbuf "Attribute not available in this context: '%s'"
801 (match-string-no-properties 1)))
802 (unless (match-string 3)
803 (wesnoth-check-output
804 outbuf "Attribute has no value")))
805 ((looking-at "^[\t ]*#else")
806 (unless (string-match "ifn?def" (car unmatched-tag-list))
807 (if (string= (car unmatched-tag-list) "#define")
808 (wesnoth-check-output outbuf "Expecting: '%s'"
809 (car unmatched-tag-list))
810 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
811 (car unmatched-tag-list)))))
812 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
813 (unless (assoc (match-string-no-properties 1)
814 (append wesnoth-local-macro-data
815 wesnoth-macro-data))
816 (wesnoth-check-output outbuf "Unknown macro definition: '{%s}'"
817 (match-string-no-properties 1))))
818 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
819 (unless (string= (match-string-no-properties 1)
820 (car unmatched-tag-list))
821 (if (string-match "^#.+" (car unmatched-tag-list))
822 (wesnoth-check-output outbuf "Expecting: '#%s'"
823 (car
824 (assoc (car unmatched-tag-list)
825 '(("define" "#enddef")
826 ("endif" "#ifdef")
827 ("endif" "#ifndef")))))
828 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
829 (car unmatched-tag-list))))
830 (setq unmatched-tag-list (cdr unmatched-tag-list))))
831 (end-of-line))
832 (if unmatched-tag-list
833 (dolist (tag unmatched-tag-list)
834 (wesnoth-check-output outbuf "Unmatched tag: '%s'"
835 (car unmatched-tag-list)))))
836 (save-excursion
837 (let ((buffer (buffer-name)))
838 (set-buffer outbuf)
839 (display-buffer outbuf t)
840 (message (format "Checking %s...done" buffer))))))
842 (defmacro wesnoth-element-requires (element requirement &optional pop)
843 "Process requirements for corresponding preprocessor elements.
844 ELEMENT is the current element being tested.
845 REQUIREMENT is the element required to exist for correct nesting.
846 POP is an optional argument indicating the element should be
847 removed from the unmatched-tag-list."
848 `(when (string= ,element (match-string-no-properties 1))
850 (if (string-match ,requirement (car unmatched-tag-list))
851 (progn
852 (and ,pop (setq unmatched-tag-list (cdr unmatched-tag-list)))
854 (setq error-position (point)))))
856 (defmacro wesnoth-structure-result (position element)
857 "Process results of the structure check.
858 POSITION is the error position or nil, if no error was found.
859 ELEMENT is the last unmatched element, or nil if all opening
860 elements have been matched."
861 `(let ((expected nil))
862 (when ,element
863 (cond ((string= ,element "define ") (setq expected "#enddef"))
864 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
865 (if (interactive-p)
866 (if (or ,element ,position)
867 (progn
868 (and ,position (goto-char ,position))
869 (message "Error: Expecting %s" (or expected
870 (concat "[/" ,element "]"))))
871 (message "%s" "Structure appears consistent."))
872 (when (or expected ,element)
873 (or expected (concat "[/" ,element "]"))))))
875 (defun wesnoth-check-structure (&optional start end)
876 "Check the buffer for correct nesting of elements.
877 If a problem is found in the structure, point will be placed at
878 the location which an element was expected and the expected
879 element will be displayed in the mini-buffer.
881 START and END define the region to be checked. If
882 function `transient-mark-mode' is enabled, the region specified will be
883 checked. Otherwise START and END will be the minimum and maximum
884 positions of the buffer, respectively."
885 (interactive)
886 (unless (or start end)
887 (if (and (boundp 'transient-mark-mode)
888 transient-mark-mode mark-active)
889 (setq start (region-beginning)
890 end (copy-marker (region-end)))
891 (setq start (point-min)
892 end (point-max))))
893 (let ((unmatched-tag-list '())
894 (error-position nil))
895 (save-excursion
896 (and start (goto-char start))
897 (while (and (search-forward-regexp
898 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
899 wesnoth-preprocessor-regexp "\\)") end t)
900 (not error-position))
901 (beginning-of-line)
902 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
903 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
904 (setq unmatched-tag-list (cons (match-string-no-properties 1)
905 unmatched-tag-list))
906 (cond
907 ((wesnoth-element-requires "#else" "ifn?def "))
908 ((wesnoth-element-requires "#endif" "ifn?def " t))
909 ((wesnoth-element-requires "#enddef" "define " t))
910 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
911 wesnoth-preprocessor-closing-regexp))
912 (if (string= (match-string-no-properties 1)
913 (car unmatched-tag-list))
914 (setq unmatched-tag-list (cdr unmatched-tag-list))
915 (setq error-position (point))))))
916 (end-of-line)))
917 (wesnoth-structure-result error-position (car unmatched-tag-list))))
919 ;;; wesnoth-mode
920 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
921 "Major mode for editing WML."
922 (kill-all-local-variables)
923 (use-local-map wesnoth-mode-map)
924 (setq major-mode 'wesnoth-mode)
925 (setq mode-name "WML")
926 (set-syntax-table wesnoth-syntax-table)
927 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
928 (set (make-local-variable 'comment-start) "#")
929 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
930 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
931 (set (make-local-variable 'font-lock-defaults)
932 '(wesnoth-font-lock-keywords
933 nil t nil nil
934 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
935 (setq indent-tabs-mode nil)
936 (easy-menu-add wesnoth-menu wesnoth-mode-map)
937 (run-hooks 'wesnoth-mode-hook))
939 (provide 'wesnoth-mode)
941 ;;; wesnoth-mode.el ends here