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