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