b8f0f5fe4aca4dc355b6388d7718c5af03649858
[wesnoth-mode.git] / wesnoth-mode.el
blobb8f0f5fe4aca4dc355b6388d7718c5af03649858
1 ;;; wesnoth-mode.el --- A major mode for editing WML.
2 ;; Copyright (C) 2006, 2007, 2008, 2009 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 of
23 ;; Wesnoth Markup Language (WML) files. Features of wesnoth-mode include
24 ;; syntax highlighting support, automatic indentation, context-sensitive
25 ;; completion and WML 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.5+git
37 ;; * Improve and add support for prefix arg to `wesnoth-kill-block' to kill
38 ;; multiple blocks.
39 ;; * Add support for attributes where whitespace is between the key and `='.
40 ;; 1.3.5
41 ;; * Added navigation commands: C-M-n and C-M-p can be used to move to the
42 ;; next and previous children of the current parent element, respectively.
43 ;; C-M-u and C-M-d can be used to move to the parent element and the next
44 ;; child element, respectively.
45 ;; * Added commands for structured editing: C-M-k kills the block at point.
46 ;; C-M-SPC sets the mark to the position of the end of the block at point.
47 ;; * Fixed a bug where the parent tag would be unknown if a macro was defined
48 ;; between point and the position of the parent element.
49 ;; * Fixed a bug where an incorrectly formatted closing tag could be inserted
50 ;; in some circumstances.
51 ;; 1.3.4a
52 ;; * #ifdef, #ifndef preprocessor statements now indent their contents
53 ;; relative to themselves when `wesnoth-indent-preprocessor-bol' is nil.
54 ;; * Fixed a bug which could prevent element completion immediately within a
55 ;; preprocessor statement.
56 ;; 1.3.4
57 ;; * Fixed some errors produced when wesnoth-mode.el is byte-compiled.
58 ;; * Improve detection and position of inserted closing tags in some
59 ;; circustances.
60 ;; * Improved context detection for completion in some circumstances.
61 ;; * Read `wesnoth-addition-file' as needed; M-x wesnoth-update no longer
62 ;; required.
63 ;; * `wesnoth-indent-preprocessor-bol' has been re-introduced to control
64 ;; whether preprocessor statements are indented to the beginning of the line
65 ;; or as tags.
66 ;; * Many minor bug fixes.
67 ;; 1.3.3
68 ;; * Improve performance when inserting missing elements. Support for
69 ;; searching for missing elements over a region has been removed;
70 ;; `narrow-to-region' can be used to provide the functionality when
71 ;; required.
72 ;; * All warnings found when checking WML are now underlined in the buffer.
73 ;; * Next and previous warning can be jumped to using C-c C-f (or C-x `) and
74 ;; C-c C-b, respectively.
75 ;; * Any macro arguments are now prompted for and inserted when performing
76 ;; completing, as suggested by fabi.
77 ;; * Improved handling of completion; no longer prompt when no completion
78 ;; found, as suggested by uzytkownik.
79 ;; * Added indentation for FOREACH, as suggested by fabi.
80 ;; * Several bugs and inconsistencies corrected.
81 ;; 1.3.2
82 ;; * Major performance improvements to indentation and WML checking.
83 ;; * Fixed a bug where nesting could break when inserting multiple elements
84 ;; near the last element in a buffer.
85 ;; * Fixed a bug where attributes immediately within #ifn?def were always
86 ;; reported to be illegal.
87 ;; * Fixed a bug where tags immediately within #ifn?def were always legal.
88 ;; * Fixed a bug where when inserting missing tags, scanning would only be
89 ;; performed up to point.
90 ;; * Fixed a bug when jumping between preprocessor statements.
91 ;; 1.3.1
92 ;; * Completion history available is now specific to wesnoth-mode.
93 ;; * Added binding to explicitly update macro information from the current
94 ;; buffer (C-c C-u).
95 ;; * Significantly improved performance of completion and WML checking.
96 ;; * Improved performance for inserting missing tags.
97 ;; * Fixed a bug where #ifdef was never matched when checking WML.
98 ;; * Added completion for preprocessor statements.
99 ;; * Improved macro completion and checking.
100 ;; 1.3.0
101 ;; * Added support for Xemacs.
102 ;; * WML checking is now context sensitive; checks attributes and macros.
103 ;; * WML checks are now always performed on the entire buffer, with results
104 ;; displayed in a temporary buffer.
105 ;; * Context-sensitive completion for attributes and tags.
106 ;; * Completion for built-in and project-specific macros.
107 ;; * Changed the following bindings:
108 ;; `wesnoth-insert-tag' - C-c e -> C-c t
109 ;; `wesnoth-jump-to-matching' - C-c m -> C-c o
110 ;; `wesnoth-check-structure' -> `wesnoth-check-wml' - C-c c
111 ;; * Added the following bindings:
112 ;; `wesnoth-complete-attribute' - C-c a
113 ;; `wesnoth-complete-macro' - C-c m
114 ;; `wesnoth-complete-tag' - C-c t
115 ;; * Removed the following bindings:
116 ;; `wesnoth-check-tag-names' - C-c n
117 ;; * Removed `wesnoth-check-tag-names'. Replaced by `wesnoth-check-wml'.
118 ;; * Completion for an incomplete attribute, tag, or macro at point is
119 ;; attempted via TAB.
120 ;; 1.2.5
121 ;; * Fixed support for GNU Emacs 21.
122 ;; * Added several new tags to `wesnoth-tags-list'.
123 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
124 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
125 ;; how many blocks to wrap across instead of a region.
126 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
127 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
128 ;; causing tags not to be inserted in the correct position.
129 ;; * Fixed highlighting of array indexes as tags.
130 ;; 1.2.4
131 ;; * Improved syntax-highlighting for macro calls.
132 ;; * Underscore is now treated as whitespace.
133 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
134 ;; * Point is now placed at the first non-whitespace character of the line,
135 ;; instead of the last.
136 ;; * Corrected minor indentation bugs.
137 ;; * Indenting across large regions is now much more efficient.
138 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
139 ;; applied.
140 ;; 1.2.3
141 ;; * Now compatible with GNU Emacs 21.4.
142 ;; * Added support for several new tags.
143 ;; * Added menu entry for wesnoth-mode.
144 ;; * Significant speed increase to indentation.
145 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
146 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
147 ;; has been removed.
148 ;; * Trailing whitespace is no longer created when creating a second
149 ;; consecutive newline.
150 ;; * Spurious newlines are no longer created when inserting a tag elements
151 ;; around a region.
152 ;; 1.2.2
153 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
154 ;; `wesnoth-element', `wesnoth-element-opening',
155 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
156 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
157 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
158 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
159 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
160 ;; * Fixed a bug in indentation where content was needed between elements
161 ;; pairs for indentation to work.
162 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
163 ;; `wesnoth-auto-indent-flag'.
164 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
165 ;; * Added indentation styles: `wesnoth-indent-default',
166 ;; `wesnoth-indent-withtags' which implement a a similar indentation
167 ;; style to the existing styles, however all preprocessor statements are
168 ;; indented to the first column.
169 ;; * Added support for several new tags.
170 ;; * Modified `wesnoth-newline' to behave more consistently.
171 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
172 ;; now leaves point at the beginning (when moving backward) or end (when
173 ;; moving forward) of the match.
174 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
175 ;; will now work on preprocessor statements. Will now warn if jump
176 ;; destination may not be correct (due to errors in WML structure).
177 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
178 ;; * `wesnoth-check-structure' can now be applied over an active region and
179 ;; now checks preprocessor statements for correct nesting.
180 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
181 ;; perform indentation by providing a prefix argument.
182 ;; * Indentation styles now leave point at the first non-whitespace character
183 ;; of the line.
184 ;; * `wesnoth-check-tag-names' now reports on success.
185 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
186 ;; * `outline-minor-mode' now works on macro definitions.
187 ;; 1.2.1
188 ;; * Base indent now defaults to 4.
189 ;; * Added support for #ifndef.
191 ;;; Code:
192 (require 'easymenu)
193 (require 'wesnoth-update)
194 (require 'wesnoth-wml-data)
196 (defconst wesnoth-mode-version "1.3.5+git"
197 "The current version of `wesnoth-mode'.")
199 (defgroup wesnoth-mode nil "Wesnoth-mode access"
200 :group 'languages
201 :prefix "wesnoth-")
203 (defcustom wesnoth-auto-indent-flag t
204 "Non-nil means indent the current line upon creating a newline."
205 :type 'boolean
206 :group 'wesnoth-mode)
208 (defcustom wesnoth-indent-preprocessor-bol t
209 "Whether to indent Preprocessor statements to the beginning of the line."
210 :type 'boolean
211 :group 'wesnoth-mode)
213 (defcustom wesnoth-indent-savefile t
214 "Non-nil means to use the current indentation conventions.
215 If nil, use the old convention for indentation.
216 The current convention is all attributes are indented a level deeper
217 than their parent; in the past attributes were indented to the same
218 level as their parent.")
220 (defcustom wesnoth-base-indent 4
221 "The number of columns to indent WML."
222 :type 'integer
223 :group 'wesnoth-mode)
225 (defconst wesnoth-preprocessor-regexp
226 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\
227 \\|\\(ifn?\\|un\\)def \\)"
228 "Regular expression to match all preprocessor statements.")
230 (defconst wesnoth-preprocessor-opening-regexp
231 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
232 "Regular expression to match \"opening\" preprocessor statements.")
234 (defconst wesnoth-preprocessor-closing-regexp
235 "[\t ]*#\\(end\\(\\(de\\|i\\)f\\)\\)"
236 "Regular expression to match \"closing\" preprocessor statements.")
238 (defvar wesnoth-define-blocks '()
239 "Cache of all toplevel #define and #enddef pairs.")
241 (defvar wesnoth-history-list '()
242 "History of inserted WML elements.")
244 (defvar wesnoth-warning-markers '()
245 "Markers for warnings in the buffer.")
247 (defvar wesnoth-mode-hook nil)
249 (defface wesnoth-warning-face
250 '((t (:underline "tomato1")))
251 "Face to use for warnings in wesnoth-mode"
252 :group 'wesnoth-mode)
254 (defvar wesnoth-mode-map
255 (let ((map (make-sparse-keymap)))
256 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
257 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
258 (define-key map (kbd "C-M-n") 'wesnoth-forward-list)
259 (define-key map (kbd "C-M-p") 'wesnoth-backward-list)
260 (define-key map (kbd "C-M-d") 'wesnoth-down-list)
261 (define-key map (kbd "C-M-u") 'wesnoth-backward-up-list)
262 (define-key map (kbd "C-M-k") 'wesnoth-kill-block)
263 (define-key map (kbd "C-M-SPC") 'wesnoth-mark-block)
264 (define-key map (kbd "C-m") 'wesnoth-newline)
265 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
266 (define-key map (kbd "C-c C-c") 'wesnoth-check-wml)
267 (define-key map (kbd "C-c C-a") 'wesnoth-complete-attribute)
268 (define-key map (kbd "C-c C-t") 'wesnoth-complete-tag)
269 (define-key map (kbd "C-c C-p") 'wesnoth-complete-preprocessor)
270 (define-key map (kbd "C-c C-u") 'wesnoth-update-project-information)
271 (define-key map (kbd "M-TAB") 'wesnoth-complete-tag)
272 (define-key map (kbd "C-c C-m") 'wesnoth-complete-macro)
273 (define-key map (kbd "C-c C-o") 'wesnoth-jump-to-matching)
274 (define-key map (kbd "C-c C-f") 'wesnoth-forward-warning)
275 (define-key map (kbd "C-x `") 'wesnoth-forward-warning)
276 (define-key map (kbd "C-c C-b") 'wesnoth-backward-warning)
277 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
278 (define-key map (kbd "TAB") 'wesnoth-indent-or-complete)
279 map)
280 "Keymap used in `wesnoth-mode'.")
282 (easy-menu-define wesnoth-menu wesnoth-mode-map "Menu for wesnoth-mode"
283 '("WML"
284 ["Check WML" wesnoth-check-wml t]
285 ["Indent or Complete" wesnoth-indent-or-complete t]
286 ["Indent buffer" (lambda ()
287 (interactive)
288 (wesnoth-indent-region (point-min) (point-max))) t]
289 ["Insert Tag" wesnoth-complete-tag t]
290 ["Insert Attribute" wesnoth-complete-attribute t]
291 ["Insert Macro" wesnoth-complete-macro t]
292 ["Insert Preprocessor" wesnoth-complete-preprocessor t]
293 ["Insert Missing Tag" wesnoth-insert-missing-closing t]
294 ["Jump to Matching" wesnoth-jump-to-matching t]
295 ["Update Macros" wesnoth-update-project-information t]))
297 (defvar wesnoth-syntax-table
298 (let ((wesnoth-syntax-table (make-syntax-table)))
299 (modify-syntax-entry ?# "<" wesnoth-syntax-table)
300 (modify-syntax-entry ?\" "\"" wesnoth-syntax-table)
301 (modify-syntax-entry ?= "." wesnoth-syntax-table)
302 (modify-syntax-entry ?| "w" wesnoth-syntax-table)
303 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
304 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
305 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
306 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
307 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
308 wesnoth-syntax-table)
309 "Syntax table for `wesnoth-mode'.")
311 ;; Prevents automatic syntax-highlighting of elements which might be
312 ;; pre-processor statements.
313 (defvar wesnoth-syntactic-keywords
314 (list
315 '("\\([\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\
316 \\(?:ifn?\\|un\\)def \\)\\)\\)" 1 "w"))
317 "Syntactic keywords for preprocessor statements within `wesnoth-mode'.")
319 (defvar wesnoth-font-lock-keywords
320 (list
321 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face)
322 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
323 font-lock-keyword-face)
324 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
325 2 font-lock-function-name-face)
326 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face))
327 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face))
328 '("}" . font-lock-function-name-face)
329 '("[\t ]*\\(\\[/?[^$]\\(\\w\\|_\\)+\\]\\)" 1 font-lock-type-face)
330 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
331 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)[\t ]*="
332 1 font-lock-variable-name-face))
333 "Syntax highlighting for `wesnoth-mode'.")
335 (defun wesnoth-element-closing (&optional limited)
336 "Return the regexp to match a closing element.
337 If LIMITED is non-nil, return a regexp which matches only the
338 #enddef preprocessor."
339 (concat "^[\t ]*\\(\\[/\\(\\w\\|_\\)+\\]\\|"
340 (if limited
341 "#enddef"
342 "#end\\(?:def\\|if\\)")
343 (if (and (not wesnoth-indent-preprocessor-bol) limited)
344 "\\|#endif"
346 "\\)"))
348 (defun wesnoth-element-opening (&optional limited)
349 "Return the regexp to match a closing element.
350 If LIMITED is non-nil, return a regexp which matches only the
351 #define preprocessor."
352 (concat "^[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define "
353 (if limited
354 "\\|{FOREACH .+}"
355 "\\|#ifn?def ")
356 (if (and (not wesnoth-indent-preprocessor-bol) limited)
357 "\\|#ifn?def \\|#else"
359 "\\)"))
361 (defun wesnoth-element (&optional limited)
362 "Return the regexp to match a closing element.
363 If LIMITED is non-nil, return a regexp which matches only the
364 #define and #enddef preprocessors."
365 (concat "^[\t ]*\\(\\[[+/]?\\(\\w\\|_\\)+\\]?\\|"
366 (if limited
367 "#define \\|#enddef"
368 (substring wesnoth-preprocessor-regexp 5))
369 (if (and (not wesnoth-indent-preprocessor-bol) limited)
370 "\\|#\\(ifn?def \\|endif\\|else\\)"
372 "\\)"))
374 (defun wesnoth-find-next (type)
375 "Find the next element of TYPE.
376 TYPE is a symbol representing an element type, or a list of
377 element types to find."
378 (let ((element (wesnoth-next-element)))
379 (while (and element (if (listp type)
380 (not (member (car element) type))
381 (not (eq (car element) type))))
382 (setq element (wesnoth-next-element)))
383 (when (if (listp type)
384 (member (car element) type)
385 (eq (car element) type))
386 element)))
388 (defun wesnoth-next-element ()
389 "Move to the next element in the buffer.
390 Return non-nil when an element is found. Otherwise, return nil."
391 (interactive)
392 (save-match-data
393 (and (or (eolp) (looking-at "[}\t ]"))
394 (search-forward-regexp "[^}
395 \t ]" (point-max) t)
396 (forward-char -1)))
397 (let ((details (wesnoth-element-type (point))))
398 (save-match-data
399 (when (nth 2 details)
400 (goto-char (nth 2 details))
401 (while (nth 3 (parse-partial-sexp
402 (save-excursion (search-backward-regexp
403 (wesnoth-element t) (point-min) t)
404 (point))
405 (point)))
406 (search-forward "\"" (point-max) t))))
407 details))
409 (defun wesnoth-element-type (point)
410 "Return details regarding the element at POINT.
411 A list is returned, the elements of the list represent the
412 following, respectively: A symbol representing the type of
413 element; the position of the start of the element and the
414 position of the end of the element. POINT must be at the start
415 of the element."
416 (let ((element-matches
417 '(("{\\(.*?[/\]\\)+}" . nil) ;; pathnames
418 ("{\\(\\w\\|_\\)+" . macro)
419 ("\\[\\+?[^/]+?\\]" . tag-opening)
420 ("\\[/.+?\\]" . tag-closing)
421 ("\\(\\w\\|_\\)+[\t ]*=" . attribute)
422 ("#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\
423 \\(ifn?\\|un\\)def \\)"
424 . preprocessor)
425 ("#.*$" . comment)
426 ("[^\t ]+") . nil)))
427 (catch 'result
428 (dolist (pair element-matches)
429 (when (looking-at (car pair))
430 (throw 'result (list (cdr pair)
431 (match-beginning 0)
432 (min (save-excursion (forward-line 1) (point))
433 (match-end 0)))))))))
435 (defun wesnoth-estimate-element-type (point)
436 "Return match data for a partial element at POINT."
437 (save-excursion
438 (goto-char point)
439 (let ((element-matches
440 '(("{\\(.*?[/\]\\)+$" . nil) ; pathnames
441 ("{\\(\\w\\|_\\)*$" . macro)
442 ("\\[/\\(\\w\\|_\\)*$" . tag-closing)
443 ("\\[\\+?\\(\\w\\|_\\)*$" . tag-opening)
444 ("^[\t ]*\\(\\w\\|_\\)+$" . attribute)
445 ("[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\
446 \\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def \\)"
447 . nil) ; not a partial match
448 ("[\t ]*#\\w*$" . preprocessor))))
449 (catch 'result
450 (dolist (pair element-matches)
451 (when (looking-at (car pair))
452 (throw 'result (list (cdr pair)
453 (match-beginning 0)
454 (match-end 0)))))))))
456 (defun wesnoth-guess-element-type (point)
457 "Return details for the the element near POINT.
458 Locate the start of the element before determining details.
459 BOUND is the limit to search backwards."
460 (let ((details (wesnoth-estimate-element-type point))
461 (bound (save-excursion
462 (goto-char point)
463 (beginning-of-line)
464 (point))))
465 (while (and (not (car details)) (> point bound))
466 (setq point (1- point)
467 details (wesnoth-estimate-element-type point)))
468 (and (nth 1 details)
469 (>= (point) (nth 1 details))
470 (nth 2 details)
471 (<= (point) (nth 2 details))
472 details)))
475 ;;; Insertion and completion
476 (defmacro wesnoth-element-completion (completions prompt partial
477 &optional completep)
478 "Process completion of COMPLETIONS, displaying PROMPT.
479 PARTIAL is the partial string on which to attempt completion.
480 If COMPLETEP is non-nil, do not prompt if no completion is found."
481 `(let* ((element (when ,partial (try-completion ,partial ,completions))))
482 (cond ((eq element t)
483 ,partial)
484 ((and ,completep (null element))
485 nil)
486 ((and element (eq (try-completion element ,completions) t))
487 element)
488 ((> (length (all-completions (or element "") ,completions)) 1)
489 (completing-read ,prompt ,completions
490 nil nil element
491 'wesnoth-history-list))
492 ((= (length ,completions) 1)
493 (car ,completions))
495 element))))
497 (defun wesnoth-active-parent-tag ()
498 "Return the name of the active parent tag.
499 Finds the relevant parent tag, ignoring any conditional tags."
500 (save-excursion
501 (let ((parent (wesnoth-parent-tag)))
502 (while (and (stringp (car parent))
503 (string-match "else\\|then"
504 (car parent)))
505 (goto-char (cdr parent))
506 (setq parent (wesnoth-parent-tag))
507 (when (string= (car parent) "if")
508 (goto-char (cdr parent))
509 (setq parent (wesnoth-parent-tag))))
510 (car parent))))
512 (defun wesnoth-parent-tag ()
513 "Return the name of the parent tag.
514 If the parent is a preprocessor statement, return non-nil.
515 If the element does not have a parent, return nil.
516 Otherwise, return a string containing the name of the parent tag."
517 (save-excursion
518 (let ((start-point (point))
519 (depth 1))
520 (when (save-excursion (> (point) (progn (back-to-indentation)
521 (point))))
522 (end-of-line))
523 (while (and (> depth 0)
524 (search-backward-regexp (wesnoth-element t) (point-min) t))
525 (if (string-match "[\t ]*\\[/\\|#enddef" (match-string 0))
526 (setq depth (1+ depth))
527 (setq depth (1- depth))))
528 (beginning-of-line)
529 (if (> depth 0)
530 (cons nil nil)
531 (when (looking-at (wesnoth-element-opening))
532 (let ((parent (match-string-no-properties 1))
533 (position (point)))
534 (if (or (string-match wesnoth-preprocessor-opening-regexp parent)
535 ;; Check if we're immediately within a macro
536 (and (goto-char start-point)
537 (search-backward-regexp "[}{]" (point-min) t)
538 (string= (match-string 0) "{")
539 (goto-char start-point)
540 (not (and (search-backward parent (point-min) t)
541 (search-backward-regexp "[}{]" (point-min)
543 (string= (match-string 0) "{")))))
544 (cons t position)
545 (cons (substring parent (if (string-match "[\\+.+]" parent)
548 (1- (length parent))) position))))))))
550 (defun wesnoth-partial-macro-p ()
551 "Return non-nil if point is in a partial macro."
552 (save-excursion
553 (let ((opened 0))
554 (search-backward-regexp "{" (point-min) t)
555 (while (search-forward-regexp "[{}]" (point-max) t)
556 (if (string= (match-string 0) "{")
557 (setq opened (1+ opened))
558 (setq opened (1- opened))))
559 (> opened 0))))
561 (defun wesnoth-indent-or-complete (&optional elements)
562 "Indent or complete the line at point, depending on context.
563 ELEMENTS is the number of elements to wrap around if inserting
564 matching tags."
565 (interactive "P")
566 (or elements (setq elements 0))
567 (let ((details (wesnoth-guess-element-type (point))))
568 (cond
569 ((eq (car details) 'tag-opening)
570 (wesnoth-complete-tag elements t))
571 ((and (eq (car details) 'macro)
572 (wesnoth-partial-macro-p))
573 (wesnoth-complete-macro t))
574 ((eq (car details) 'preprocessor)
575 (wesnoth-complete-preprocessor elements t))
576 ((eq (car details) 'tag-closing)
577 ;; FIXME: Solve incorrect behaviour when partial closing is "[/"
578 (insert "a")
579 (and (wesnoth-insert-missing-closing t)
580 (delete-region (nth 1 details)
581 (save-excursion (beginning-of-line) (point))))
582 (end-of-line)
583 (wesnoth-indent))
584 ((eq (car details) 'attribute)
585 (wesnoth-complete-attribute t))
587 (wesnoth-indent)))))
589 (defun wesnoth-preprocessor-closed-p (preprocessor)
590 "Determine whether PREPROCESSOR has been closed.
591 PREPROCESSOR is a string matching the preprocessor statement to
592 be inserted."
593 (save-excursion
594 (back-to-indentation)
595 (wesnoth-jump-to-matching preprocessor)
596 (looking-at
597 (if (string= preprocessor "#define ")
598 "#enddef"
599 "#endif"))))
601 (defun wesnoth-complete-preprocessor (&optional elements completep)
602 "Complete and insert the preprocessor at point.
603 ELEMENTS is the number of elements to wrap around.
604 If COMPLETEP is non-nil, attempt to complete preprocessor at point."
605 (interactive "P")
606 (or elements (setq elements 0))
607 (let* ((completions (wesnoth-emacs-completion-formats
608 '("define" "else" "ifdef" "ifndef"
609 "enddef" "endif" "undef")))
610 (partial (when completep
611 (save-excursion
612 (back-to-indentation)
613 (when (looking-at "#\\(\\w*\\)$")
614 (match-string-no-properties 1)))))
615 (preprocessor (wesnoth-element-completion
616 completions "Preprocessor: " partial completep))
617 (details (wesnoth-guess-element-type (point)))
618 (closedp
619 (save-excursion
620 (when preprocessor
621 (unless (string= "#" (substring preprocessor 0 1))
622 (setq preprocessor (concat "#" preprocessor)))
623 (when (string-match "#\\(define\\|ifn?def\\|undef\\)"
624 preprocessor)
625 (setq preprocessor (concat preprocessor " ")))
626 (when partial
627 (delete-region (nth 1 details) (nth 2 details)))
628 (wesnoth-preprocessor-closed-p preprocessor)))))
629 (when preprocessor
630 (when partial
631 (delete-region
632 (save-excursion
633 (progn (search-backward
634 "#" (save-excursion (back-to-indentation)
635 (point))
637 (point)))
638 (point)))
639 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor)
640 (not closedp))
641 (progn
642 (wesnoth-insert-tag elements preprocessor)
643 (forward-line -1)
644 (end-of-line))
645 (wesnoth-insert-element-separately preprocessor)))))
647 (defun wesnoth-macro-arguments ()
648 "Find any current macro arguments."
649 (let ((results '())
650 (depth (wesnoth-within-define (point))))
651 (save-excursion
652 (while (> depth 0)
653 (save-match-data
654 (search-backward-regexp
655 "[\t ]*#define \\(?:\\w+\\|_\\)*\\(\\([\t ]*\\(\\w\\|_\\)+\\)*\\)"
656 (point-min) t)
657 (when (<= (wesnoth-within-define (point)) depth)
658 (and (> depth 0)
659 (setq results
660 (append (mapcar (lambda (macro)
661 (list macro nil))
662 (split-string
663 (match-string-no-properties 1)))
664 results)))
665 (setq depth (1- depth)))))
666 results)))
668 (defun wesnoth-complete-macro (&optional completep)
669 "Complete and insert the macro at point.
670 If COMPLETEP is non-nil, attempt to complete the macro at point."
671 (interactive)
672 (wesnoth-update-project-information)
673 (let* ((macro-information (wesnoth-merge-macro-data
674 wesnoth-macro-data
675 (wesnoth-macro-additions)
676 wesnoth-local-macro-data
677 (wesnoth-macro-arguments)))
678 (completions (wesnoth-emacs-completion-formats
679 (mapcar 'car macro-information)))
680 (details (wesnoth-guess-element-type (point)))
681 (partial (when
682 (save-excursion
683 (and completep
684 (eq (car details) 'macro)
685 (goto-char (cadr details))
686 (looking-at "{\\(\\(\\w\\|_\\)*\\)")))
687 (match-string-no-properties 1)))
688 (macro (wesnoth-element-completion completions "Macro: " partial
689 completep))
690 (args (cadr (assoc macro macro-information))))
691 (when macro
692 (if partial
693 (progn
694 ;; Delete the region corresponding to the current macro.
695 (delete-region (nth 1 details) (nth 2 details))
696 (insert "{" macro (if args " }" "}"))
697 (save-excursion
698 (wesnoth-indent)))
699 (wesnoth-insert-and-indent "{" macro (if args " }" "}")))
700 (forward-char -1)
701 (when args
702 (let ((input (read-string (concat (car args) ": "))))
703 (insert input (if (and (cdr args)
704 (not (string= input "")))
705 " " ""))
706 (while (and (setq args (cdr args)) (not (string= input "")))
707 (insert (setq input (read-string (concat (car args) ": ")))
708 (if (and (not (string= input ""))
709 (cdr args))
710 " " "")))))
711 (when (null args) (forward-char 1)))))
713 (defun wesnoth-complete-attribute (&optional completep)
714 "Insert the attribute at point.
715 If COMPLETEP is non-nil, attempt to complete the attribute at point."
716 (interactive)
717 (wesnoth-refresh-wml-data)
718 (let* ((details (save-excursion
719 (back-to-indentation)
720 (wesnoth-guess-element-type (point))))
721 (completions (save-excursion (when (nth 1 details)
722 (goto-char (nth 1 details)))
723 (wesnoth-build-completion 1)))
724 (partial (when completep
725 (when (save-excursion
726 (back-to-indentation)
727 (looking-at "\\(\\(\\w\\|_\\)+\\)"))
728 (match-string-no-properties 1))))
729 (attribute (wesnoth-element-completion completions "Attribute: "
730 partial completep)))
731 (when attribute
732 (if partial
733 (progn
734 (delete-region (nth 1 details) (nth 2 details))
735 (insert attribute "="))
736 (wesnoth-insert-element-separately attribute
737 (if (string-match "=" attribute)
739 "=")))
740 (save-excursion
741 (wesnoth-indent)))))
743 (defun wesnoth-complete-tag (&optional elements completep)
744 "Complete and insert the tag at point.
745 ELEMENTS is the number of elements to wrap around.
746 If COMPLETEP is non-nil, attempt to complete tag at point."
747 (interactive "P")
748 (or elements (setq elements 0))
749 (let* ((details (wesnoth-guess-element-type (point)))
750 (completions (save-excursion (and (nth 1 details)
751 (goto-char (nth 1 details)))
752 (wesnoth-build-completion 0)))
753 (partial (save-excursion
754 (when (and completep
755 (eq (car details) 'tag-opening)
756 (goto-char (cadr details))
757 (looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$"))
758 (match-string-no-properties 1))))
759 (tag (wesnoth-element-completion completions "Tag: " partial
760 completep))
761 (closedp
762 (save-excursion
763 (wesnoth-jump-to-matching (concat "[" tag "]"))
764 (back-to-indentation)
765 (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
766 (string= tag (match-string 1))))))
767 (if tag
768 (progn
769 (if completep
770 (progn
771 (delete-region (nth 1 details) (nth 2 details))
772 (if closedp
773 (progn
774 (wesnoth-insert-and-indent "[" tag "]")
775 (end-of-line))
776 (wesnoth-insert-tag elements tag)))
777 (wesnoth-insert-tag elements tag)))
778 (or completep (wesnoth-insert-tag elements)))))
780 (defun wesnoth-build-completion (position)
781 "Create a new list for tag completion if necessary.
782 Rebuilding list is required for versions of GNU Emacs earlier
783 than 22. POSITION is the argument passed to `nth' for
784 `wesnoth-tag-data'."
785 (interactive "P")
786 (let ((parent (wesnoth-active-parent-tag))
787 (tag-data (wesnoth-refresh-wml-data)))
788 (wesnoth-emacs-completion-formats
789 (if (or (stringp parent) (null parent))
790 (nth position (gethash parent wesnoth-tag-hash-table))
791 (mapcar 'car tag-data)))))
793 (defun wesnoth-emacs-completion-formats (candidates)
794 "Return the completions in the correct format for `emacs-major-version'.
795 CANDIDATES is a list of all possible completions."
796 (if (> emacs-major-version 21)
797 candidates
798 (let ((tags '())
799 (iter 0))
800 (dolist (tag candidates)
801 (setq iter (1+ iter))
802 (setq tags (append tags (list (cons tag iter)))))
803 tags)))
805 (defun wesnoth-insert-tag (&optional elements tagname)
806 "Insert the specified opening tag and it's matching closing tag.
807 Both the opening and closing tags will be placed on their own
808 lines with point positioned between them. Completion of tags at
809 the prompt uses `wesnoth-tags-list'.
811 ELEMENTS is specifies the number of following blocks which the
812 tag should wrap around.
814 TAGNAME is the name of the tag to be inserted."
815 (interactive "Ps")
816 (unless tagname
817 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 0)
818 nil nil nil 'wesnoth-history-list)))
819 (when (or (not elements)
820 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
821 wesnoth-preprocessor-regexp "\\)")))
822 (setq elements 0))
823 (let ((start (save-excursion (forward-line -1) (point)))
824 (end (unless (= elements 0)
825 ;; Work around some strange behaviour when the target is at the
826 ;; end of the buffer.
827 (save-excursion
828 (goto-char (point-max))
829 (beginning-of-line)
830 (unless (looking-at "^[\t ]*$")
831 (end-of-line)
832 (newline)))
833 (wesnoth-nth-pair-position elements))))
834 (if (string-match wesnoth-preprocessor-regexp tagname)
835 (wesnoth-insert-element-separately tagname)
836 (wesnoth-insert-element-separately "[" tagname "]"))
837 (save-excursion
838 (if end
839 (goto-char (marker-position end))
840 (newline (if (string-match wesnoth-preprocessor-regexp tagname) 1 2)))
841 (if (string-match wesnoth-preprocessor-opening-regexp tagname)
842 (wesnoth-insert-element-separately
843 (if (string= tagname "#define ")
844 "#enddef"
845 "#endif"))
846 (wesnoth-insert-element-separately "[/" (if (string-match "^+"
847 tagname)
848 (substring tagname 1)
849 tagname)
850 "]"))
851 (indent-region start (point) nil))
852 (unless end
853 (forward-line 1)))
854 (wesnoth-indent))
856 (defun wesnoth-insert-element-separately (&rest strings)
857 "Concatenate STRINGS and insert them on a line of their own."
858 (if (save-excursion (and (> (point) (progn (back-to-indentation) (point)))))
859 (if (save-excursion (forward-line 1) (looking-at "^[\t ]*$"))
860 (progn
861 (forward-line 1)
862 (end-of-line))
863 (end-of-line)
864 (newline))
865 (beginning-of-line)
866 (if (looking-at "^[\t ]*$")
867 (end-of-line)
868 (open-line 1)))
869 (insert (apply 'concat strings)))
871 (defun wesnoth-insert-missing-closing (&optional completep)
872 "Insert the next expected closing element at point.
873 If COMPLETEP is non-nil, do not move forward a line when scanning
874 for the matching tag."
875 (interactive)
876 (let ((match nil)
877 (skip t))
878 (save-excursion
879 (when (and (null completep)
880 (<= (point) (save-excursion (back-to-indentation) (point))))
881 (if (save-excursion (beginning-of-line)
882 (looking-at (wesnoth-element-opening)))
883 (forward-line -1)
884 (when
885 (save-excursion (beginning-of-line)
886 (looking-at (wesnoth-element-closing)))
887 (setq skip nil))))
888 (when (wesnoth-search-for-matching-tag
889 'search-backward-regexp (wesnoth-element-opening) 'point-min
890 (and skip (if completep nil 1)))
891 (setq match (and (looking-at (wesnoth-element-opening))
892 (match-string-no-properties 1)))))
893 (when match
894 (if (string= (substring match 0 1) "[")
895 (wesnoth-insert-element-separately
896 "[/"
897 (let ((tagname (substring match 1 (1- (length match)))))
898 (if (string-match "^+" tagname)
899 (substring tagname 1)
900 tagname))
901 "]")
902 (wesnoth-insert-element-separately
903 (cdr (assoc match '(("#define " . "#enddef")
904 ("#ifndef " . "#endif")
905 ("#ifdef " . "#endif")))))))
906 (wesnoth-indent)
907 (end-of-line)
908 match))
910 (defun wesnoth-insert-and-indent (&rest args)
911 "Concatenate and insert the given string(s) before indenting.
913 ARGS is a list of strings to be inserted."
914 (insert (apply 'concat args))
915 (wesnoth-indent))
917 (defun wesnoth-newline (&optional indent)
918 "Indent the current line and create a newline.
919 If `wesnoth-auto-indent-flag' is nil, indentation will not be
920 performed. Indentation can be forced by setting INDENT to
921 non-nil."
922 (interactive "P")
923 (newline)
924 (save-excursion
925 (forward-line -1)
926 (when (and (or wesnoth-auto-indent-flag indent)
927 (not (looking-at "^[\t ]*$")))
928 (wesnoth-indent))))
930 ;;; Movement
931 (defun wesnoth-navigate-element (repeat search-function bound)
932 "Move point to the tag in the given direction REPEAT times.
934 SEARCH-FUNCTION is the symbol of the function for searching in
935 the required direction, with BOUND marking the furthest point to
936 search."
937 (or repeat (setq repeat 1))
938 (while (> repeat 0)
939 (and (eq search-function 'search-forward-regexp) (end-of-line))
940 (funcall search-function (wesnoth-element-opening) bound t)
941 (back-to-indentation)
942 (setq repeat (1- repeat))))
944 (defun wesnoth-nth-pair-position (count)
945 "Return `point' after COUNT number of matching element pairs.
946 COUNT is a positive number representing the number of balanced
947 pairs to move across.
948 `point' is returned as a marker object."
949 (save-excursion
950 (let ((failed nil))
951 (if (> (point) (save-excursion (back-to-indentation) (point)))
952 (end-of-line)
953 (beginning-of-line))
954 (while (> count 0)
955 ;; Currently looking-at target tag. Stop here to avoid
956 ;; incorrect nesting.
957 (unless (wesnoth-search-for-matching-tag
958 'search-forward-regexp (wesnoth-element-closing) 'point-max)
959 (setq count 0)
960 (setq failed t))
961 (and (> (setq count (1- count)) 0) (forward-line 1)))
962 (if failed
963 (beginning-of-line)
964 (end-of-line))
965 (point-marker))))
967 (defun wesnoth-forward-element (repeat)
968 "Move point to the end of the next tag.
969 REPEAT is an optional numeric argument. If REPEAT is non-nil,
970 jump forward the specified number of tags."
971 (interactive "p")
972 (if (< repeat 0)
973 (wesnoth-backward-element (abs repeat))
974 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
976 (defun wesnoth-backward-element (repeat)
977 "Move point to the beginning of the previous tag.
978 REPEAT is an optional numeric argument. If REPEAT is non-nil,
979 jump backward the specified number of tags."
980 (interactive "p")
981 (if (< repeat 0)
982 (wesnoth-forward-element (abs repeat))
983 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
985 (defun wesnoth-search-for-matching-tag (search-function
986 search-string bound &optional skip)
987 "Search for the matching tag for the current line.
988 SEARCH-FUNCTION is the name of the function used to perform the search.
989 SEARCH-STRING is a string representing the matching tag type.
990 BOUND is the bound to be passed to the search function.
991 If SKIP is non-nil, skip the first element and continue from there."
992 (let ((depth 1))
993 (when (and (or (and (numberp skip) (forward-line skip))
994 (funcall search-function (wesnoth-element)
995 (funcall bound) t))
996 (or skip (not (string-match search-string (match-string 0)))))
997 (while (and (> depth 0)
998 (funcall search-function (wesnoth-element)
999 (funcall bound) t))
1000 (if (string-match search-string (match-string 0))
1001 (setq depth (1- depth))
1002 (setq depth (1+ depth))))
1003 (= depth 0))))
1005 (defun wesnoth-jump-to-matching (&optional element)
1006 "Jump point to the matching opening/closing tag.
1007 ELEMENT is an element to find a match for."
1008 (interactive)
1009 (beginning-of-line)
1010 (let ((target nil)
1011 (first-element nil))
1012 (save-excursion
1013 (cond
1014 ((or (and (stringp element)
1015 (string-match (wesnoth-element-opening) element))
1016 (looking-at (wesnoth-element-opening)))
1017 (setq first-element (match-string-no-properties 0 element))
1018 (when (wesnoth-search-for-matching-tag
1019 'search-forward-regexp (wesnoth-element-closing) 'point-max
1020 (and (stringp element) 1))
1021 (beginning-of-line)
1022 (if (and (string-match wesnoth-preprocessor-opening-regexp
1023 first-element)
1024 (looking-at (wesnoth-element-closing)))
1025 (when (string= (match-string-no-properties 0)
1026 (cdr (assoc first-element
1027 '(("#define " . "#enddef")
1028 ("#ifndef " . "#endif")
1029 ("#ifdef " . "#endif")))))
1030 (setq target (point)))
1031 (setq target (point)))))
1032 ((or (and (stringp element)
1033 (string-match (wesnoth-element-closing) element))
1034 (looking-at (wesnoth-element-closing)))
1035 (end-of-line)
1036 (setq first-element (match-string-no-properties 0 element))
1037 (when (wesnoth-search-for-matching-tag
1038 'search-backward-regexp (wesnoth-element-opening)
1039 'wesnoth-wml-start-pos (and (stringp element) -1))
1040 (if (and (string-match wesnoth-preprocessor-closing-regexp
1041 first-element)
1042 (looking-at (wesnoth-element-opening)))
1043 (progn
1044 (when (or (and (string= "#enddef" first-element)
1045 (string= "#define "
1046 (match-string-no-properties
1047 0)))
1048 (and (string= "#endif" first-element)
1049 (string-match
1050 "#ifn?def "
1051 (match-string-no-properties
1052 0))))
1053 (setq target (point))))
1054 (setq target (point)))))
1056 (search-backward-regexp (wesnoth-element-opening) (point-min) t)
1057 (setq target (point)))))
1058 (if target
1059 (progn
1060 (goto-char target)
1061 (back-to-indentation))
1062 (when (interactive-p)
1063 (message "%s" "Tag does not appear to be matched")))))
1065 ;;; Indentation
1066 (defun wesnoth-wml-start-pos ()
1067 "Determine the position of `point' relative to where the actual WML begins.
1068 Return the likely starting position of the WML if it is found.
1069 Otherwise return nil."
1070 (save-excursion
1071 (goto-char (point-min))
1072 (when (search-forward-regexp (wesnoth-element) (point-max) t)
1073 (beginning-of-line)
1074 (point))))
1076 (defun wesnoth-first-column-indent-p (point)
1077 "Return non-nil if the current line should not be indented.
1079 POINT is the position in the buffer to check.
1080 CONTEXT represents the type of element which precedes the current element."
1081 (or (not (wesnoth-wml-start-pos))
1082 (<= (point) (wesnoth-wml-start-pos))
1083 (nth 3 (parse-partial-sexp
1084 (save-excursion (search-backward-regexp
1085 (wesnoth-element t) (point-min) t)
1086 (point))
1087 point))
1088 (and (looking-at wesnoth-preprocessor-regexp)
1089 wesnoth-indent-preprocessor-bol)))
1091 (defun wesnoth-indent ()
1092 "Indent the current line as WML."
1093 (save-excursion
1094 (beginning-of-line)
1095 (let* ((cur-indent 0)
1096 (context-data (wesnoth-determine-context (point)))
1097 (context (car context-data))
1098 (ref-indent (cdr context-data)))
1099 (unless (wesnoth-first-column-indent-p (point))
1100 (cond
1101 ((eq context 'opening)
1102 (if (and (looking-at "^[\t ]*#else")
1103 (not wesnoth-indent-preprocessor-bol))
1104 (setq cur-indent ref-indent)
1105 (if (or (and wesnoth-indent-savefile
1106 (or (looking-at "[\t ]*{NEXT ")
1107 (and (not
1108 (looking-at (wesnoth-element-closing t)))
1109 (not (looking-at "[\t ]*{NEXT ")))))
1110 (looking-at (wesnoth-element-opening t))
1111 (looking-at "[\t ]*{FOREACH "))
1112 (setq cur-indent (+ ref-indent wesnoth-base-indent))
1113 (setq cur-indent ref-indent))))
1114 ((eq context 'closing)
1115 (if (and (looking-at "^[\t ]*#else")
1116 (not wesnoth-indent-preprocessor-bol))
1117 (setq cur-indent (- ref-indent wesnoth-base-indent))
1118 (if (or (looking-at
1119 (concat "^[\t ]*\\(\\[/\\|\\#enddef"
1120 (if (not wesnoth-indent-preprocessor-bol)
1121 "\\|#endif"
1123 "\\)"))
1124 (and (not wesnoth-indent-savefile)
1125 (not (looking-at (wesnoth-element-opening t)))
1126 (not (looking-at "[\t ]*{FOREACH "))))
1127 (setq cur-indent (- ref-indent wesnoth-base-indent))
1128 (setq cur-indent ref-indent))))))
1129 (indent-line-to (max cur-indent 0))))
1130 (when (> (save-excursion (back-to-indentation) (point))
1131 (point))
1132 (back-to-indentation)))
1134 (defun wesnoth-within-define (position)
1135 "Determine whether point is currently inside a #define block.
1136 POSITION is the initial cursor position."
1137 (save-match-data
1138 (let ((depth 0)
1139 (defblocks (or wesnoth-define-blocks
1140 (wesnoth-find-macro-definitions))))
1141 (unless (equal (car defblocks) 'none)
1142 (dolist (element defblocks)
1143 (when (= (cadr (sort (append (mapcar 'marker-position
1144 (cadr element))
1145 (list position)) '>)) position)
1146 (setq depth (max (car element) depth)))))
1147 depth)))
1149 (defun wesnoth-find-macro-definitions ()
1150 "Return information regarding positioning of macro definitions."
1151 (save-excursion
1152 (goto-char (point-min))
1153 (let ((depth 0)
1154 openings cache)
1155 (while (search-forward-regexp "#define\\|#enddef" (point-max) t)
1156 (and (string= (match-string 0) "#define") (beginning-of-line))
1157 (setq depth
1158 (if (string= (match-string 0) "#define")
1159 (progn
1160 (add-to-list 'openings (point-marker))
1161 (1+ depth))
1162 (if openings
1163 (progn
1164 (add-to-list 'cache
1165 (list depth (list (car openings)
1166 (point-marker))))
1167 (setq openings (cdr openings))
1168 (1- depth))
1169 depth)))
1170 (end-of-line))
1171 (or cache (list 'none)))))
1173 (defun wesnoth-indent-region (start end)
1174 "Indent the region from START to END.
1175 Creates and destroys a cache of macro definition details as necessary."
1176 (interactive "r")
1177 (unwind-protect
1178 (save-excursion
1179 (goto-char end)
1180 (setq end (point-marker))
1181 (goto-char start)
1182 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1183 (or (bolp) (forward-line 1))
1184 (while (< (point) end)
1185 (if (looking-at "^[\t ]*$")
1186 (indent-line-to 0)
1187 (funcall indent-line-function))
1188 (forward-line 1)))
1189 (setq wesnoth-define-blocks nil)))
1191 (defun wesnoth-determine-context (position)
1192 "Determine the type of the last relevant element.
1193 POSITION is the buffer position of the element for which to
1194 determine the context."
1195 (save-excursion
1196 (let* ((elements (concat (substring (wesnoth-element t)
1197 0 (- (length (wesnoth-element t)) 2))
1198 "\\|{FOREACH .+}\\|{NEXT .+}\\)"))
1199 (match (or
1200 (and (search-backward-regexp
1201 elements (point-min) t)
1202 (progn
1203 (while
1204 (save-match-data
1205 (looking-at "^[\t ]*\\[[^/].+\\]\\[/.+\\]"))
1206 (search-backward-regexp elements
1207 (point-min) t))
1209 (match-string 1))
1210 ""))
1211 (depth (wesnoth-within-define position)))
1212 (while (and (wesnoth-wml-start-pos)
1213 (> (wesnoth-within-define (point)) depth)
1214 (not (= (point) (wesnoth-wml-start-pos))))
1215 (search-backward-regexp elements
1216 (wesnoth-wml-start-pos) t)
1217 (setq match (match-string 1)))
1218 (when (and (wesnoth-wml-start-pos)
1219 (= (point) (wesnoth-wml-start-pos))
1220 (= depth 0)
1221 (string-match "#define" match))
1222 ;; Found nothing of use; reset match and assume top-level tag.
1223 (setq match ""))
1224 (cond
1225 ((string-match (concat "\\[/\\|#enddef"
1226 (if (not wesnoth-indent-preprocessor-bol)
1227 "\\|#endif"
1228 ""))
1229 match)
1230 (cons 'closing (current-indentation)))
1231 ((string-match "{NEXT " match)
1232 (cons 'closing (if wesnoth-indent-savefile
1233 (- (current-indentation) wesnoth-base-indent)
1234 (current-indentation))))
1235 ((string-match (concat "\\[[^/]?\\|#define\\|{FOREACH "
1236 (if (not wesnoth-indent-preprocessor-bol)
1237 "\\|#ifn?def \\|#else"
1238 "")) match)
1239 (cons 'opening (current-indentation)))))))
1241 (defun wesnoth-newline-and-indent (&optional indent)
1242 "Indent both the current line and the newline created.
1243 If `wesnoth-auto-indent-flag' is nil, indentation will not be
1244 performed.
1246 If the optional argument, INDENT is non-nil, force indentation to
1247 be performed."
1248 (interactive)
1249 (wesnoth-newline)
1250 (when (or wesnoth-auto-indent-flag indent)
1251 (wesnoth-indent)))
1253 ;;; WML checks
1254 (defun wesnoth-check-element-type (position)
1255 "Determine the context of the element.
1256 POSITION is the position of the element in the list."
1257 (let ((parent (save-match-data (car (wesnoth-parent-tag)))))
1258 (if (or (stringp parent) (null parent))
1259 (member (match-string-no-properties 1)
1260 (nth position (gethash parent wesnoth-tag-hash-table)))
1261 (member (match-string-no-properties 1)
1262 (let ((result '()))
1263 (mapc
1264 '(lambda (x)
1265 (let ((value (nth position (cdr x))))
1266 (and value (mapc '(lambda (y)
1267 (setq result (cons y result)))
1268 value))))
1269 (or wesnoth-tmp-tag-data (wesnoth-refresh-wml-data)))
1270 result)))))
1272 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
1273 (defun wesnoth-line-number-at-pos (&optional pos)
1274 "Return (narrowed) buffer line number at position POS.
1275 If POS is nil, use current buffer location.
1276 Counting starts at (point-min), so the value refers
1277 to the contents of the accessible portion of the buffer."
1278 (let ((opoint (or pos (point))) start)
1279 (save-excursion
1280 (goto-char (point-min))
1281 (setq start (point))
1282 (goto-char opoint)
1283 (forward-line 0)
1284 (1+ (count-lines start (point))))))
1286 (defun wesnoth-check-output (buffer format-string &rest args)
1287 "Output the string as passed to `format'.
1288 BUFFER is the buffer to output the result.
1289 FORMAT-STRING is the string as the first argument of `format'.
1290 ARGS is any additional data required by `format' to handle FORMAT-STRING."
1291 (save-excursion
1292 (let ((lnap (wesnoth-line-number-at-pos)))
1293 (set-buffer buffer)
1294 (let ((buffer-read-only nil))
1295 (insert (apply 'format (concat "Line %d: " format-string "\n")
1296 lnap args))))))
1298 (defun wesnoth-extract-macro-details (macro-arguments)
1299 "Return a list of all macros in MACRO-ARGUMENTS."
1300 (when macro-arguments
1301 (let ((results '()))
1302 (dolist (macro (split-string macro-arguments "[{}][\t ]*"))
1303 (when (string-match "^\\(\\(?:\\w\\|_\\)+\\)"
1304 macro)
1305 (add-to-list 'results (match-string-no-properties 1 macro))))
1306 results)))
1308 (defmacro wesnoth-check-process (format-string &rest args)
1309 "Output to buffer where requested and position overlays as required.
1310 FORMAT-STRING is the string to pass as the first argument to
1311 `format' for the error. ARGS is a list of arguments required by
1312 FORMAT-STRING."
1313 `(progn
1314 (wesnoth-check-output outbuf ,format-string ,@args)
1315 (wesnoth-place-overlay (match-beginning 0) (match-end 0))))
1317 (defmacro wesnoth-overlay-at-pos-p (position)
1318 "Return non-nil when there is an overlay at POSITION."
1319 `(and (overlays-at (goto-char ,position))
1320 (overlay-get (car (overlays-at (point))) 'wesnoth-error)
1321 (overlay-start (car (overlays-at (point))))))
1323 (defmacro wesnoth-locate-warning (string start end)
1324 "Search for STRING and move to the warning in the given direction.
1325 Searching starts from `point' and will wrap from START if no
1326 match was found. STRING is a form to locate the warning in the
1327 required direction. START is the start of the region searched.
1328 END is the end of the region searched."
1329 `(let ((target nil))
1330 (save-excursion
1331 (cond
1332 ((setq target (wesnoth-overlay-at-pos-p ,string)))
1333 ((setq target (wesnoth-overlay-at-pos-p ,start)))
1334 ((and (not (= (goto-char ,string) ,end))
1335 (setq target (wesnoth-overlay-at-pos-p (point)))))))
1336 target))
1338 (defun wesnoth-forward-warning ()
1339 "Move to the next warning."
1340 (interactive)
1341 (let ((target
1342 (if (fboundp 'next-overlay-change)
1343 (save-excursion
1344 (end-of-line)
1345 (wesnoth-locate-warning (next-overlay-change (point))
1346 (point-min)
1347 (point-max)))
1348 (wesnoth-target-position '< '>))))
1349 (if target
1350 (goto-char target)
1351 (message "%s" "No warnings found"))))
1353 (defun wesnoth-backward-warning ()
1354 "Move to the previous warning."
1355 (interactive)
1356 (let ((target
1357 (if (fboundp 'previous-overlay-change)
1358 (save-excursion
1359 (beginning-of-line)
1360 (wesnoth-locate-warning (1- (previous-overlay-change (point)))
1361 (point-max)
1362 (point-min)))
1363 (wesnoth-target-position '> '< t))))
1364 (if target
1365 (goto-char target)
1366 (message "%s" "No warnings found"))))
1368 (defun wesnoth-target-position (predicate search &optional lastp)
1369 "Return the target marker position.
1370 PREDICATE is the function to use to sort
1371 `wesnoth-warning-markers'. SEARCH must be a function which
1372 returns non-nil when the match is correct. If LASTP is non-nil,
1373 swap the order of the sorted positions when attempting to
1374 fallback."
1375 (let ((positions (sort (mapcar 'marker-position wesnoth-warning-markers)
1376 predicate)))
1377 (or (catch 'pos
1378 (dolist (position positions)
1379 (when (funcall search position (point))
1380 (throw 'pos position))))
1381 (car positions))))
1383 (defun wesnoth-place-overlay (start end)
1384 "Place overlay in the region and apply necessary properties.
1385 START is the start of the region to place the overlay. END is
1386 the end of the region to place the overlay."
1387 (if (fboundp 'overlay-put)
1388 (let ((overlay (make-overlay start end)))
1389 (overlay-put overlay 'wesnoth-error t)
1390 (overlay-put overlay 'face 'wesnoth-warning-face))
1391 (add-to-list 'wesnoth-warning-markers (save-excursion
1392 (goto-char start)
1393 (point-marker)))))
1395 (defun wesnoth-kill-block (arg)
1396 "Kill ARG blocks at point."
1397 (interactive "p")
1398 (save-excursion
1399 (while (> arg 0)
1400 (let ((kill-whole-line t))
1401 (while (and (looking-at "[\t ]*$") (= (forward-line 1) 0)))
1402 (if (looking-at "[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|\
1403 #ifn?def\\)")
1404 (kill-region (point)
1405 (save-excursion
1406 (wesnoth-jump-to-matching)
1407 (forward-line 1)
1408 (point)))
1409 (kill-line))
1410 (setq arg (1- arg)))
1411 (wesnoth-indent))))
1413 (defun wesnoth-mark-block ()
1414 "Mark the block at point."
1415 (interactive)
1416 (save-excursion
1417 (while (and (save-excursion (beginning-of-line)
1418 (looking-at "[\t ]*$"))
1419 (= (forward-line 1) 0)))
1420 (when (looking-at "[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|\
1421 #ifn?def\\)")
1422 (push-mark (save-excursion
1423 (wesnoth-jump-to-matching)
1424 (end-of-line)
1425 (point))))))
1427 (defun wesnoth-down-list (&optional arg)
1428 "Move forward down ARG levels of elements.
1429 If ARG is not specified, move forward down one level."
1430 (interactive "p")
1431 (unless arg
1432 (setq arg 1))
1433 (when (looking-at "\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|\
1434 #ifn?def\\|\\(\\w\\|_\\)+[\t ]*=\\)")
1435 (forward-char 1))
1436 (let ((target nil))
1437 (save-excursion
1438 (when (looking-at "\\(\\w\\|_\\)+[\t ]*=")
1439 (if (and (search-forward-regexp (wesnoth-element) (point-max) t)
1440 (progn (beginning-of-line)
1441 (looking-at (wesnoth-element-opening t))))
1442 (setq target (point))
1443 (message "%s" "Innermost level"))))
1444 (when target (goto-char target)))
1445 (while (> arg 0)
1446 (when (> (save-excursion (wesnoth-jump-to-matching) (point)) (point))
1447 (search-forward-regexp
1448 "\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|#ifn?def\\|\\(\\w\\|_\\)+[\t ]*=\\)"
1449 (save-excursion
1450 (wesnoth-jump-to-matching)
1451 (point))
1453 (setq arg (1- arg)))
1454 (back-to-indentation))
1456 (defun wesnoth-backward-up-list (&optional arg)
1457 "Move backward up ARG levels of elements.
1458 If ARG is not specified, move backward up one level."
1459 (interactive "p")
1460 (unless arg
1461 (setq arg 1))
1462 (let ((parent nil))
1463 (while (> arg 0)
1464 (setq parent (cdr (wesnoth-parent-tag)))
1465 (if (numberp parent)
1466 (progn
1467 (goto-char parent)
1468 (setq arg (1- arg)))
1469 (message "%s" "Outermost level")
1470 (setq arg 0))
1471 (when (numberp parent)
1472 (back-to-indentation)))))
1474 (defun wesnoth-forward-list (arg)
1475 "Move to forward ARG elements at the current depth.
1476 If ARG is not specifed, move forward one element."
1477 (interactive "p")
1478 (while (and (save-excursion (beginning-of-line)
1479 (looking-at "[\t ]*$"))
1480 (= (forward-line 1) 0)))
1481 (when (save-excursion (beginning-of-line)
1482 (looking-at (wesnoth-element-opening)))
1483 (wesnoth-jump-to-matching)
1484 (setq arg (1- arg)))
1485 (let ((revert-target (point)))
1486 (while (> arg 0)
1487 (beginning-of-line)
1488 (unless (looking-at (wesnoth-element-closing))
1489 (wesnoth-jump-to-matching))
1490 (end-of-line)
1491 (if (and (search-forward-regexp (wesnoth-element) (point-max) t)
1492 (save-excursion (beginning-of-line)
1493 (looking-at (wesnoth-element-opening))))
1494 (setq revert-target (point))
1495 (goto-char revert-target)
1496 (message "%s" "End of block"))
1497 (setq arg (1- arg))))
1498 (when (save-excursion (beginning-of-line)
1499 (looking-at (wesnoth-element-opening)))
1500 (wesnoth-jump-to-matching))
1501 (end-of-line))
1503 (defun wesnoth-backward-list (arg)
1504 "Move to backward ARG elements at the current depth.
1505 If ARG is not specifed, move backward one element."
1506 (interactive "p")
1507 (while (and (save-excursion (beginning-of-line) (looking-at "[\t ]*$"))
1508 (= (forward-line -1) 0)))
1509 (when (save-excursion (beginning-of-line)
1510 (looking-at (wesnoth-element-closing)))
1511 (wesnoth-jump-to-matching)
1512 (setq arg (1- arg)))
1513 (let ((revert-target (point)))
1514 (while (> arg 0)
1515 (beginning-of-line)
1516 (unless (looking-at (wesnoth-element-opening))
1517 (wesnoth-jump-to-matching))
1518 (if (and (search-backward-regexp (wesnoth-element) (point-min) t)
1519 (save-excursion (beginning-of-line)
1520 (looking-at (wesnoth-element-closing))))
1521 (setq revert-target (point))
1522 (goto-char revert-target)
1523 (message "%s" "Beginning of block"))
1524 (setq arg (1- arg))))
1525 (when (looking-at (wesnoth-element-closing))
1526 (wesnoth-jump-to-matching)))
1528 (defun wesnoth-check-wml ()
1529 "Perform context-sensitive analysis of WML-code."
1530 (interactive)
1531 ;; Temporarily cache all tag-data.
1532 (setq wesnoth-tmp-tag-data (wesnoth-refresh-wml-data))
1533 (wesnoth-update-project-information)
1534 (if (fboundp 'delete-overlay)
1535 (dolist (overlay (overlays-in (point-min) (point-max)))
1536 (if (eq 'wesnoth-warning-face (overlay-get overlay 'face))
1537 (delete-overlay overlay)))
1538 (setq wesnoth-warning-markers nil))
1539 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
1540 (error "WML data not available; unable to generate report"))
1541 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1542 (let ((unmatched '())
1543 (outbuf (and (interactive-p) (get-buffer-create "*WML*")))
1544 (last-match-pos 1)
1545 (details nil)
1546 (foreach '()))
1547 (save-excursion
1548 (set-buffer outbuf)
1549 (let ((buffer (buffer-name))
1550 (buffer-read-only nil))
1551 (erase-buffer)
1552 (insert (format "Checking %s...\n" buffer))
1553 (message (format "Checking %s..." buffer))))
1554 (save-excursion
1555 (goto-char (point-min))
1556 (while (setq details (wesnoth-find-next
1557 '(tag-opening tag-closing preprocessor attribute
1558 macro)))
1559 (save-excursion
1560 (goto-char (match-beginning 0))
1561 (cond ((nth 3 (parse-partial-sexp last-match-pos (point)))
1562 nil)
1563 ((eq (car details) 'macro)
1564 (dolist (macro (save-match-data
1565 (wesnoth-extract-macro-details
1566 (match-string-no-properties 0))))
1567 (unless (assoc macro
1568 (wesnoth-merge-macro-data
1569 wesnoth-macro-data
1570 (wesnoth-macro-additions)
1571 wesnoth-local-macro-data
1572 (wesnoth-macro-arguments)))
1573 (wesnoth-check-process "Unknown macro: '%s'"
1574 macro)))
1575 (save-match-data
1576 (when
1577 (looking-at
1578 "{\\(FOREACH\\|NEXT\\).*[\t ]+\
1579 \\(\\(?:\\w\\|_\\)+\\)}")
1580 (if (string= (match-string-no-properties 1) "FOREACH")
1581 (setq foreach
1582 (cons (match-string-no-properties 2) foreach))
1583 (if (string= (match-string-no-properties 1) "NEXT")
1584 (progn
1585 (unless (string= (car foreach)
1586 (match-string-no-properties 2))
1587 (wesnoth-check-process
1588 (concat "NEXT does not match corresponding "
1589 "FOREACH: '%s' found; '%s' expected.")
1590 (match-string-no-properties 2)
1591 (car foreach)))
1592 (setq foreach (cdr foreach))))))))
1593 ((looking-at "[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
1594 (unless (wesnoth-check-element-type 0)
1595 (wesnoth-check-process
1596 "Tag not available in this context: '%s'"
1597 (match-string-no-properties 1)))
1598 (setq unmatched (cons (match-string-no-properties 1)
1599 unmatched)))
1600 ((looking-at
1601 (concat "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\|#undef\\)"
1602 "\\( \\(\\w\\|_\\)+\\)*"))
1603 (unless (match-string-no-properties 2)
1604 (wesnoth-check-process
1605 (concat "Preprocessor statement has no argument: "
1606 (match-string-no-properties 1))))
1607 (unless (string= (match-string-no-properties 1) "#undef")
1608 (setq unmatched (cons (match-string-no-properties 1)
1609 unmatched))))
1610 ((looking-at wesnoth-preprocessor-closing-regexp)
1611 (when (and unmatched
1612 (not (string-match
1613 (cdr (assoc (match-string-no-properties 1)
1614 '(("enddef" . "#define")
1615 ("endif" . "#ifn?def"))))
1616 (car unmatched))))
1617 (wesnoth-check-process
1618 "Preprocessor statement does not nest correctly"))
1619 (setq unmatched (cdr unmatched)))
1620 ((looking-at "[\t ]*\\(\\(\\w\\|_\\)+\\)[\t ]*=\\(.+\\)?")
1621 (unless (wesnoth-check-element-type 1)
1622 (wesnoth-check-process
1623 "Attribute not available in this context: '%s'"
1624 (match-string-no-properties 1)))
1625 (unless (match-string 3)
1626 (wesnoth-check-process
1627 "Attribute has no value")))
1628 ((looking-at "[\t ]*#else")
1629 (unless (string-match "ifn?def" (car unmatched))
1630 (if (string= (car unmatched) "#define")
1631 (wesnoth-check-process "Expecting: '%s'"
1632 (car unmatched))
1633 (wesnoth-check-process "Expecting: '[/%s]'"
1634 (car unmatched)))))
1635 ((looking-at "[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]")
1636 (when (and unmatched
1637 (not (string= (match-string-no-properties 1)
1638 (car unmatched))))
1639 (wesnoth-check-process
1640 "Expecting '%s'"
1641 (or (cdr (assoc (car unmatched)
1642 '(("#define" . "#enddef")
1643 ("#ifdef" . "#endif")
1644 ("#ifndef" . "#endif"))))
1645 (concat "[/" (car unmatched) "]"))))
1646 (setq unmatched (cdr unmatched)
1647 last-match-pos (point))))))
1648 (when foreach
1649 (dolist (var foreach)
1650 (wesnoth-check-process "Unmatched FOREACH: '%s'" var)))
1651 (when unmatched
1652 (dolist (element unmatched)
1653 (wesnoth-check-process "Unmatched element: '%s'" element))))
1654 (save-excursion
1655 (setq wesnoth-define-blocks nil
1656 wesnoth-tmp-tag-data nil)
1657 (set-buffer outbuf)
1658 (toggle-read-only t)
1659 (let ((buffer (buffer-name))
1660 (buffer-read-only nil))
1661 (display-buffer outbuf t)
1662 (let ((warnings (- (wesnoth-line-number-at-pos
1663 (save-excursion (goto-char (point-max)))) 2)))
1664 (insert (format (concat "\nCheck complete. %d warning"
1665 (if (= warnings 1) "." "s.")) warnings)))
1666 (message (format "Checking %s...done" buffer))))))
1669 ;;; wesnoth-mode
1670 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
1671 "Major mode for editing WML."
1672 (kill-all-local-variables)
1673 (use-local-map wesnoth-mode-map)
1674 (setq major-mode 'wesnoth-mode)
1675 (setq mode-name "WML")
1676 (set-syntax-table wesnoth-syntax-table)
1677 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
1678 (set (make-local-variable 'comment-start) "#")
1679 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
1680 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
1681 (set (make-local-variable 'wesnoth-warning-markers) '())
1682 (set (make-local-variable 'font-lock-defaults)
1683 '(wesnoth-font-lock-keywords
1684 nil t nil nil
1685 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
1686 (setq indent-tabs-mode nil)
1687 (easy-menu-add wesnoth-menu wesnoth-mode-map)
1688 (wesnoth-refresh-wml-data)
1689 (wesnoth-update-project-information)
1690 (run-hooks 'wesnoth-mode-hook))
1692 (provide 'wesnoth-mode)
1694 ;;; wesnoth-mode.el ends here