* wesnoth-mode.el (wesnoth-guess-element-type): Rewritten to avoid recursion.
[wesnoth-mode.git] / wesnoth-mode.el
blob8f5d022bf6debff7050095d3cb24219affd99191
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 (interactive)
786 (let ((match nil))
787 (save-excursion
788 (when (wesnoth-search-for-matching-tag
789 'search-backward-regexp (wesnoth-element-opening) 'point-min
790 (if completep nil 1))
791 (setq match (and (looking-at (wesnoth-element-opening))
792 (match-string-no-properties 1)))))
793 (when match
794 (if (string= (substring match 0 1) "[")
795 (wesnoth-insert-element-separately
796 "[/" (substring match 1 (1- (length match))) "]")
797 (wesnoth-insert-element-separately
798 (cdr (assoc match '(("#define " . "#enddef")
799 ("#ifndef " . "#endif")
800 ("#ifdef " . "#endif")))))))
801 (wesnoth-indent)
802 (end-of-line)
803 match))
805 (defun wesnoth-insert-and-indent (&rest args)
806 "Concatenate and insert the given string(s) before indenting.
808 ARGS is a list of strings to be inserted."
809 (insert (apply 'concat args))
810 (wesnoth-indent))
812 (defun wesnoth-newline (&optional indent)
813 "Indent both the current line and the newline created.
814 If `wesnoth-auto-indent-flag' is nil, indentation will not be
815 performed. Indentation can be forced by setting INDENT to
816 non-nil."
817 (interactive "P")
818 (newline)
819 (save-excursion
820 (forward-line -1)
821 (when (and (or wesnoth-auto-indent-flag indent)
822 (not (looking-at "^[\t ]*$")))
823 (wesnoth-indent))))
825 ;;; Movement
826 (defun wesnoth-navigate-element (repeat search-function bound)
827 "Move point to the tag in the given direction REPEAT times.
829 SEARCH-FUNCTION is the symbol of the function for searching in
830 the required direction, with BOUND marking the furthest point to
831 search."
832 (or repeat (setq repeat 1))
833 (while (> repeat 0)
834 (and (eq search-function 'search-forward-regexp) (end-of-line))
835 (funcall search-function (wesnoth-element-opening) bound t)
836 (back-to-indentation)
837 (setq repeat (1- repeat))))
839 (defun wesnoth-nth-pair-position (count)
840 "Return `point' after COUNT number of matching element pairs.
841 COUNT is a positive number representing the number of balanced
842 pairs to move across.
843 `point' is returned as a marker object."
844 (save-excursion
845 (let ((failed nil))
846 (if (> (point) (save-excursion (back-to-indentation) (point)))
847 (end-of-line)
848 (beginning-of-line))
849 (while (> count 0)
850 ;; Currently looking-at target tag. Stop here to avoid
851 ;; incorrect nesting.
852 (unless (wesnoth-search-for-matching-tag
853 'search-forward-regexp (wesnoth-element-closing) 'point-max)
854 (setq count 0)
855 (setq failed t))
856 (and (> (setq count (1- count)) 0) (forward-line 1)))
857 (if failed
858 (beginning-of-line)
859 (end-of-line))
860 (point-marker))))
862 (defun wesnoth-forward-element (repeat)
863 "Move point to the end of the next tag.
864 REPEAT is an optional numeric argument. If REPEAT is non-nil,
865 jump forward the specified number of tags."
866 (interactive "p")
867 (if (< repeat 0)
868 (wesnoth-backward-element (abs repeat))
869 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
871 (defun wesnoth-backward-element (repeat)
872 "Move point to the beginning of the previous tag.
873 REPEAT is an optional numeric argument. If REPEAT is non-nil,
874 jump backward the specified number of tags."
875 (interactive "p")
876 (if (< repeat 0)
877 (wesnoth-forward-element (abs repeat))
878 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
880 (defmacro wesnoth-search-for-matching-tag (search-function
881 search-string bound &optional skip)
882 "Search for the matching tag for the current line.
883 SEARCH-FUNCTION is the name of the function used to perform the search.
884 SEARCH-STRING is a string representing the matching tag type.
885 BOUND is the bound to be passed to the search function.
886 If SKIP is non-nil, skip the first element and continue from there."
887 `(let ((depth 1))
888 (when (and (or (and (numberp ,skip) (forward-line ,skip))
889 (funcall ,search-function (wesnoth-element) (funcall ,bound) t))
890 (or ,skip (not (string-match ,search-string (match-string 0)))))
891 (while (and (> depth 0)
892 (funcall ,search-function (wesnoth-element)
893 (funcall ,bound) t))
894 (if (string-match ,search-string (match-string 0))
895 (setq depth (1- depth))
896 (setq depth (1+ depth))))
897 (= depth 0))))
899 (defun wesnoth-jump-to-matching (&optional element)
900 "Jump point to the matching opening/closing tag.
901 ELEMENT is an element to find a match for."
902 (interactive)
903 (beginning-of-line)
904 (let ((target nil)
905 (first-element nil))
906 (save-excursion
907 (cond
908 ((or (and (stringp element)
909 (string-match (wesnoth-element-opening) element))
910 (looking-at (wesnoth-element-opening)))
911 (setq first-element (match-string-no-properties 0 element))
912 (when (wesnoth-search-for-matching-tag
913 'search-forward-regexp (wesnoth-element-closing) 'point-max
914 (and (stringp element) 1))
915 (beginning-of-line)
916 (if (and (string-match wesnoth-preprocessor-opening-regexp
917 first-element)
918 (looking-at (wesnoth-element-closing)))
919 (when (string= (match-string-no-properties 0)
920 (cdr (assoc first-element
921 '(("#define " . "#enddef")
922 ("#ifndef " . "#endif")
923 ("#ifdef " . "#endif")))))
924 (setq target (point)))
925 (setq target (point)))))
926 ((or (and (stringp element)
927 (string-match (wesnoth-element-closing) element))
928 (looking-at (wesnoth-element-closing)))
929 (end-of-line)
930 (setq first-element (match-string-no-properties 0 element))
931 (when (wesnoth-search-for-matching-tag
932 'search-backward-regexp (wesnoth-element-opening)
933 'wesnoth-wml-start-pos (and (stringp element) -1))
934 (if (and (string-match wesnoth-preprocessor-closing-regexp
935 first-element)
936 (looking-at (wesnoth-element-opening)))
937 (progn
938 (when (or (and (string= "#enddef" first-element)
939 (string= "#define "
940 (match-string-no-properties
941 0)))
942 (and (string= "#endif" first-element)
943 (string-match
944 "#ifn?def "
945 (match-string-no-properties
946 0))))
947 (setq target (point))))
948 (setq target (point)))))
950 (search-backward-regexp (wesnoth-element-opening) (point-min) t)
951 (setq target (point)))))
952 (if target
953 (progn
954 (goto-char target)
955 (back-to-indentation))
956 (when (interactive-p)
957 (message "%s" "Tag does not appear to be matched")))))
959 ;;; Indentation
960 (defun wesnoth-wml-start-pos ()
961 "Determine the position of `point' relative to where the actual WML begins.
962 Return the likely starting position of the WML if it is found.
963 Otherwise return nil."
964 (save-excursion
965 (goto-char (point-min))
966 (when (search-forward-regexp (wesnoth-element) (point-max) t)
967 (beginning-of-line)
968 (point))))
970 (defun wesnoth-first-column-indent-p (point)
971 "Return non-nil if the current line should not be indented.
973 POINT is the position in the buffer to check.
974 CONTEXT represents the type of element which precedes the current element."
975 (or (not (wesnoth-wml-start-pos))
976 (<= (point) (wesnoth-wml-start-pos))
977 (nth 3 (parse-partial-sexp
978 (save-excursion (search-backward-regexp
979 (wesnoth-element t) (point-min) t)
980 (point))
981 point))
982 (looking-at wesnoth-preprocessor-regexp)))
984 (defun wesnoth-indent ()
985 "Indent the current line as WML."
986 (save-excursion
987 (beginning-of-line)
988 (let* ((cur-indent 0)
989 (context-data (wesnoth-determine-context (point)))
990 (context (car context-data))
991 (ref-indent (cdr context-data)))
992 (unless (wesnoth-first-column-indent-p (point))
993 (cond
994 ((eq context 'opening)
995 (if (or (and wesnoth-indent-savefile
996 (not (looking-at (wesnoth-element-closing t))))
997 (looking-at (wesnoth-element-opening t)))
998 (setq cur-indent (+ ref-indent wesnoth-base-indent))
999 (setq cur-indent ref-indent)))
1000 ((eq context 'foreach)
1001 (setq cur-indent (+ ref-indent wesnoth-base-indent)))
1002 ((eq context 'next)
1003 (if (and (looking-at (wesnoth-element-closing t))
1004 wesnoth-indent-savefile)
1005 (setq cur-indent (- ref-indent wesnoth-base-indent))
1006 (setq cur-indent ref-indent)))
1007 ((eq context 'closing)
1008 (if (or (looking-at "^[\t ]*\\(\\[/\\)")
1009 (and (not wesnoth-indent-savefile)
1010 (not (looking-at (wesnoth-element-opening t)))))
1011 (setq cur-indent (- ref-indent wesnoth-base-indent))
1012 (setq cur-indent ref-indent)))))
1013 (indent-line-to (max cur-indent 0))))
1014 (when (> (save-excursion (back-to-indentation) (point))
1015 (point))
1016 (back-to-indentation)))
1018 (defun wesnoth-within-define (position)
1019 "Determine whether point is currently inside a #define block.
1020 POSITION is the initial cursor position."
1021 (save-match-data
1022 (let ((depth 0)
1023 (defblocks (or wesnoth-define-blocks
1024 (wesnoth-find-macro-definitions))))
1025 (unless (equal (car defblocks) 'none)
1026 (dolist (element defblocks)
1027 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
1028 (list position)) '>)) position)
1029 (setq depth (max (car element) depth)))))
1030 depth)))
1032 (defun wesnoth-find-macro-definitions ()
1033 "Return information regarding positioning of macro definitions."
1034 (save-excursion
1035 (goto-char (point-min))
1036 (let ((depth 0)
1037 openings cache)
1038 (while (search-forward-regexp "#define\\|#enddef" (point-max) t)
1039 (and (string= (match-string 0) "#define") (beginning-of-line))
1040 (setq depth
1041 (if (string= (match-string 0) "#define")
1042 (progn
1043 (add-to-list 'openings (point-marker))
1044 (1+ depth))
1045 (if openings
1046 (progn
1047 (add-to-list 'cache
1048 (list depth (list (car openings)
1049 (point-marker))))
1050 (setq openings (cdr openings))
1051 (1- depth))
1052 depth)))
1053 (end-of-line))
1054 (or cache (list 'none)))))
1056 (defun wesnoth-indent-region (start end)
1057 "Indent the region from START to END.
1058 Creates and destroys a cache of macro definition details as necessary."
1059 (interactive "r")
1060 (unwind-protect
1061 (save-excursion
1062 (goto-char end)
1063 (setq end (point-marker))
1064 (goto-char start)
1065 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1066 (or (bolp) (forward-line 1))
1067 (while (< (point) end)
1068 (if (looking-at "^[\t ]*$")
1069 (indent-line-to 0)
1070 (funcall indent-line-function))
1071 (forward-line 1)))
1072 (setq wesnoth-define-blocks nil)))
1074 (defun wesnoth-determine-context (position)
1075 "Determine the type of the last relevant element.
1076 POSITION is the buffer position of the element for which to
1077 determine the context."
1078 (save-excursion
1079 (let* ((elements (concat (substring (wesnoth-element t)
1080 0 (- (length (wesnoth-element t)) 3))
1081 "\\|{FOREACH .+}\\|{NEXT .+}\\)"))
1082 (match (or
1083 (and (search-backward-regexp
1084 elements (point-min) t)
1085 (progn
1086 (while (save-match-data
1087 (looking-at "^[\t ]*\\[[^/].+\\]\\[/.+\\]"))
1088 (search-backward-regexp elements
1089 (point-min) t))
1091 (match-string 1))
1092 ""))
1093 (depth (wesnoth-within-define position)))
1094 (while (and (wesnoth-wml-start-pos)
1095 (> (wesnoth-within-define (point)) depth)
1096 (not (= (point) (wesnoth-wml-start-pos))))
1097 (search-backward-regexp elements
1098 (wesnoth-wml-start-pos) t)
1099 (setq match (match-string 1)))
1100 (when (and (wesnoth-wml-start-pos)
1101 (= (point) (wesnoth-wml-start-pos))
1102 (= depth 0)
1103 (string-match "#define" match))
1104 ;; Found nothing of use; reset match and assume top-level tag.
1105 (setq match ""))
1106 (cond
1107 ((string-match "\\[/\\|#enddef" match)
1108 (cons 'closing (current-indentation)))
1109 ((string-match "{NEXT " match)
1110 (cons 'next (- (current-indentation) wesnoth-base-indent)))
1111 ((string-match "\\[[^/]?\\|#define" match)
1112 (cons 'opening (current-indentation)))
1113 ((string-match "{FOREACH" match)
1114 (cons 'foreach (current-indentation)))))))
1116 (defun wesnoth-newline-and-indent (&optional indent)
1117 "Indent both the current line and the newline created.
1118 If `wesnoth-auto-indent-flag' is nil, indentation will not be
1119 performed.
1121 If the optional argument, INDENT is non-nil, force indentation to
1122 be performed."
1123 (interactive)
1124 (wesnoth-newline)
1125 (when (or wesnoth-auto-indent-flag indent)
1126 (wesnoth-indent)))
1128 ;;; WML checks
1129 (defun wesnoth-check-element-type (position)
1130 "Determine the context of the element.
1131 POSITION is the position of the element in the list."
1132 (let ((parent (save-match-data (wesnoth-parent-tag))))
1133 (if (or (stringp parent) (null parent))
1134 (member (match-string-no-properties 1)
1135 (nth position (gethash parent wesnoth-tag-hash-table)))
1136 (member (match-string-no-properties 1)
1137 (mapcar 'car wesnoth-tag-data)))))
1139 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
1140 (defun wesnoth-line-number-at-pos (&optional pos)
1141 "Return (narrowed) buffer line number at position POS.
1142 If POS is nil, use current buffer location.
1143 Counting starts at (point-min), so the value refers
1144 to the contents of the accessible portion of the buffer."
1145 (let ((opoint (or pos (point))) start)
1146 (save-excursion
1147 (goto-char (point-min))
1148 (setq start (point))
1149 (goto-char opoint)
1150 (forward-line 0)
1151 (1+ (count-lines start (point))))))
1153 (defun wesnoth-check-output (buffer format-string &rest args)
1154 "Output the string as passed to `format'.
1155 BUFFER is the buffer to output the result.
1156 FORMAT-STRING is the string as the first argument of `format'.
1157 ARGS is any additional data required by `format' to handle FORMAT-STRING."
1158 (save-excursion
1159 (let ((lnap (wesnoth-line-number-at-pos)))
1160 (set-buffer buffer)
1161 (let ((buffer-read-only nil))
1162 (insert (apply 'format (concat "Line %d: " format-string "\n")
1163 lnap args))))))
1165 (defun wesnoth-extract-macro-details (macro-arguments)
1166 "Return a list of all macros in MACRO-ARGUMENTS."
1167 (when macro-arguments
1168 (let ((results '()))
1169 (dolist (macro (split-string macro-arguments "[{}][\t ]*"))
1170 (when (string-match "^\\(\\(?:\\w\\|_\\)+\\)"
1171 macro)
1172 (add-to-list 'results (match-string-no-properties 1 macro))))
1173 results)))
1175 (defmacro wesnoth-check-process (format-string &rest args)
1176 "Output to buffer where requested and position overlays as required.
1177 FORMAT-STRING is the string to pass as the first argument to
1178 `format' for the error. ARGS is a list of arguments required by
1179 FORMAT-STRING."
1180 `(progn
1181 (wesnoth-check-output outbuf ,format-string ,@args)
1182 (wesnoth-place-overlay (match-beginning 0) (match-end 0))))
1184 (defmacro wesnoth-overlay-at-pos-p (position)
1185 "Return non-nil when there is an overlay at POSITION."
1186 `(and (overlays-at (goto-char ,position))
1187 (overlay-get (car (overlays-at (point))) 'wesnoth-error)
1188 (overlay-start (car (overlays-at (point))))))
1190 (defmacro wesnoth-locate-warning (string start end)
1191 "Search for STRING and move to the warning in the given direction.
1192 Searching starts from `point' and will wrap from START if no
1193 match was found. STRING is a form to locate the warning in the
1194 required direction. START is the start of the region searched.
1195 END is the end of the region searched."
1196 `(let ((target nil))
1197 (save-excursion
1198 (cond
1199 ((setq target (wesnoth-overlay-at-pos-p ,string)))
1200 ((setq target (wesnoth-overlay-at-pos-p ,start)))
1201 ((and (not (= (goto-char ,string) ,end))
1202 (setq target (wesnoth-overlay-at-pos-p (point)))))))
1203 target))
1205 (defun wesnoth-forward-warning ()
1206 "Move to the next warning."
1207 (interactive)
1208 (let ((target
1209 (if (fboundp 'next-overlay-change)
1210 (save-excursion
1211 (end-of-line)
1212 (wesnoth-locate-warning (next-overlay-change (point))
1213 (point-min)
1214 (point-max)))
1215 (wesnoth-target-position '< '>))))
1216 (if target
1217 (goto-char target)
1218 (message "%s" "No warnings found"))))
1220 (defun wesnoth-backward-warning ()
1221 "Move to the previous warning."
1222 (interactive)
1223 (let ((target
1224 (if (fboundp 'previous-overlay-change)
1225 (save-excursion
1226 (beginning-of-line)
1227 (wesnoth-locate-warning (1- (previous-overlay-change (point)))
1228 (point-max)
1229 (point-min)))
1230 (wesnoth-target-position '> '< t))))
1231 (if target
1232 (goto-char target)
1233 (message "%s" "No warnings found"))))
1235 (defun wesnoth-target-position (predicate search &optional lastp)
1236 "Return the target marker position.
1237 PREDICATE is the function to use to sort
1238 `wesnoth-warning-markers'. SEARCH must be a function which
1239 returns non-nil when the match is correct. If LASTP is non-nil,
1240 swap the order of the sorted positions when attempting to
1241 fallback."
1242 (let ((positions (sort (mapcar 'marker-position wesnoth-warning-markers)
1243 predicate)))
1244 (or (catch 'pos
1245 (dolist (position positions)
1246 (when (funcall search position (point))
1247 (throw 'pos position))))
1248 (car positions))))
1250 (defun wesnoth-place-overlay (start end)
1251 "Place overlay in the region and apply necessary properties.
1252 START is the start of the region to place the overlay. END is
1253 the end of the region to place the overlay."
1254 (if (fboundp 'overlay-put)
1255 (let ((overlay (make-overlay start end)))
1256 (overlay-put overlay 'wesnoth-error t)
1257 (overlay-put overlay 'face 'wesnoth-warning-face))
1258 (add-to-list 'wesnoth-warning-markers (save-excursion
1259 (goto-char start)
1260 (point-marker)))))
1262 (defun wesnoth-check-wml ()
1263 "Perform context-sensitive analysis of WML-code."
1264 (interactive)
1265 (wesnoth-update-project-information)
1266 (if (fboundp 'delete-overlay)
1267 (dolist (overlay (overlays-in (point-min) (point-max)))
1268 (if (eq 'wesnoth-warning-face (overlay-get overlay 'face))
1269 (delete-overlay overlay)))
1270 (setq wesnoth-warning-markers nil))
1271 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
1272 (error "WML data not available; unable to generate report"))
1273 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1274 (let ((unmatched '())
1275 (outbuf (and (interactive-p) (get-buffer-create "*WML*")))
1276 (last-match-pos 1)
1277 (details nil)
1278 (foreach '()))
1279 (save-excursion
1280 (set-buffer outbuf)
1281 (let ((buffer (buffer-name))
1282 (buffer-read-only nil))
1283 (erase-buffer)
1284 (insert (format "Checking %s...\n" buffer))
1285 (message (format "Checking %s..." buffer))))
1286 (save-excursion
1287 (goto-char (point-min))
1288 (while (setq details (wesnoth-find-next
1289 '(tag-opening tag-closing preprocessor attribute
1290 macro)))
1291 (save-excursion
1292 (goto-char (match-beginning 0))
1293 (cond ((nth 3 (parse-partial-sexp last-match-pos (point)))
1294 nil)
1295 ((eq (car details) 'macro)
1296 (dolist (macro (save-match-data
1297 (wesnoth-extract-macro-details
1298 (match-string-no-properties 0))))
1299 (unless (assoc macro
1300 (append (wesnoth-macro-arguments)
1301 wesnoth-local-macro-data
1302 wesnoth-macro-data))
1303 (wesnoth-check-process "Unknown macro: '%s'"
1304 macro)))
1305 (save-match-data
1306 (when
1307 (looking-at
1308 "{\\(FOREACH\\|NEXT\\).*[\t ]+\\(\\(?:\\w\\|_\\)+\\)}")
1309 (if (string= (match-string-no-properties 1) "FOREACH")
1310 (setq foreach
1311 (cons (match-string-no-properties 2) foreach))
1312 (if (string= (match-string-no-properties 1) "NEXT")
1313 (progn
1314 (unless (string= (car foreach)
1315 (match-string-no-properties 2))
1316 (wesnoth-check-process
1317 (concat "NEXT does not match corresponding "
1318 "FOREACH: '%s' found; '%s' expected.")
1319 (match-string-no-properties 2)
1320 (car foreach)))
1321 (setq foreach (cdr foreach))))))))
1322 ((looking-at "[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
1323 (unless (wesnoth-check-element-type 0)
1324 (wesnoth-check-process
1325 "Tag not available in this context: '%s'"
1326 (match-string-no-properties 1)))
1327 (setq unmatched (cons (match-string-no-properties 1)
1328 unmatched)))
1329 ((looking-at
1330 (concat "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\|#undef\\)"
1331 "\\( \\(\\w\\|_\\)+\\)*"))
1332 (unless (match-string-no-properties 2)
1333 (wesnoth-check-process
1334 (concat "Preprocessor statement has no argument: "
1335 (match-string-no-properties 1))))
1336 (unless (string= (match-string-no-properties 1) "#undef")
1337 (setq unmatched (cons (match-string-no-properties 1)
1338 unmatched))))
1339 ((looking-at wesnoth-preprocessor-closing-regexp)
1340 (when (and unmatched
1341 (not (string-match
1342 (cdr (assoc (match-string-no-properties 1)
1343 '(("enddef" . "#define")
1344 ("endif" . "#ifn?def"))))
1345 (car unmatched))))
1346 (wesnoth-check-process
1347 "Preprocessor statement does not nest correctly"))
1348 (setq unmatched (cdr unmatched)))
1349 ((looking-at "[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
1350 (unless (wesnoth-check-element-type 1)
1351 (wesnoth-check-process
1352 "Attribute not available in this context: '%s'"
1353 (match-string-no-properties 1)))
1354 (unless (match-string 3)
1355 (wesnoth-check-process
1356 "Attribute has no value")))
1357 ((looking-at "[\t ]*#else")
1358 (unless (string-match "ifn?def" (car unmatched))
1359 (if (string= (car unmatched) "#define")
1360 (wesnoth-check-process "Expecting: '%s'"
1361 (car unmatched))
1362 (wesnoth-check-process "Expecting: '[/%s]'"
1363 (car unmatched)))))
1364 ((looking-at "[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]")
1365 (when (and unmatched
1366 (not (string= (match-string-no-properties 1)
1367 (car unmatched))))
1368 (wesnoth-check-process
1369 "Expecting '%s'"
1370 (or (cdr (assoc (car unmatched)
1371 '(("#define" . "#enddef")
1372 ("#ifdef" . "#endif")
1373 ("#ifndef" . "#endif"))))
1374 (concat "[/" (car unmatched) "]"))))
1375 (setq unmatched (cdr unmatched)
1376 last-match-pos (point))))))
1377 (when foreach
1378 (dolist (var foreach)
1379 (wesnoth-check-process "Unmatched FOREACH: '%s'" var)))
1380 (when unmatched
1381 (dolist (element unmatched)
1382 (wesnoth-check-process "Unmatched element: '%s'" element))))
1383 (save-excursion
1384 (setq wesnoth-define-blocks nil)
1385 (set-buffer outbuf)
1386 (toggle-read-only t)
1387 (let ((buffer (buffer-name))
1388 (buffer-read-only nil))
1389 (display-buffer outbuf t)
1390 (let ((warnings (- (wesnoth-line-number-at-pos
1391 (save-excursion (goto-char (point-max)))) 2)))
1392 (insert (format (concat "\nCheck complete. %d warning"
1393 (if (= warnings 1) "." "s.")) warnings)))
1394 (message (format "Checking %s...done" buffer))))))
1397 ;;; wesnoth-mode
1398 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
1399 "Major mode for editing WML."
1400 (kill-all-local-variables)
1401 (use-local-map wesnoth-mode-map)
1402 (setq major-mode 'wesnoth-mode)
1403 (setq mode-name "WML")
1404 (set-syntax-table wesnoth-syntax-table)
1405 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
1406 (set (make-local-variable 'comment-start) "#")
1407 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
1408 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
1409 (set (make-local-variable 'wesnoth-warning-markers) '())
1410 (set (make-local-variable 'font-lock-defaults)
1411 '(wesnoth-font-lock-keywords
1412 nil t nil nil
1413 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
1414 (setq indent-tabs-mode nil)
1415 (easy-menu-add wesnoth-menu wesnoth-mode-map)
1416 (wesnoth-create-wml-hash-table)
1417 (wesnoth-update-project-information)
1418 (run-hooks 'wesnoth-mode-hook))
1420 (provide 'wesnoth-mode)
1422 ;;; wesnoth-mode.el ends here