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