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