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