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