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