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