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