* wesnoth-mode.el (wesnoth-element-type): Fix a bug where incorrect matches could...
[wesnoth-mode.git] / wesnoth-mode.el
blob06b2d8a26cbe5212e6f762e703517a0778f09d7c
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.3a"
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 ?| "w" wesnoth-syntax-table)
260 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
261 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
262 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
263 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
264 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
265 wesnoth-syntax-table)
266 "Syntax table for `wesnoth-mode'.")
268 ;; Prevents automatic syntax-highlighting of elements which might be
269 ;; pre-processor statements.
270 (defvar wesnoth-syntactic-keywords
271 (list
272 '("\\([\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\)" 1 "w"))
273 "Syntactic keywords for preprocessor statements within `wesnoth-mode'.")
275 (defvar wesnoth-font-lock-keywords
276 (list
277 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face)
278 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
279 font-lock-keyword-face)
280 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
281 2 font-lock-function-name-face)
282 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face))
283 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face))
284 '("}" . font-lock-function-name-face)
285 '("[\t ]*\\(\\[/?[^$]\\(\\w\\|_\\)+\\]\\)" 1 font-lock-type-face)
286 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
287 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
288 1 font-lock-variable-name-face))
289 "Syntax highlighting for `wesnoth-mode'.")
291 (defun wesnoth-element-closing (&optional limited)
292 "Return the regexp to match a closing element.
293 If LIMITED is non-nil, return a regexp which matches only the
294 #enddef preprocessor."
295 (concat "^[\t ]*\\(\\[/\\(\\w\\|_\\)+\\]\\|"
296 (if limited
297 "#enddef"
298 "#end\\(?:def\\|if\\)")
299 "\\)"))
301 (defun wesnoth-element-opening (&optional limited)
302 "Return the regexp to match a closing element.
303 If LIMITED is non-nil, return a regexp which matches only the
304 #define preprocessor."
305 (concat "^[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define "
306 (if limited
307 "{FOREACH .+}"
308 "\\|#ifn?def ")
309 "\\)"))
311 (defun wesnoth-element (&optional limited)
312 "Return the regexp to match a closing element.
313 If LIMITED is non-nil, return a regexp which matches only the
314 #define and #enddef preprocessors."
315 (concat "^[\t ]*\\(\\[[+/]?\\(\\w\\|_\\)+\\]?\\|"
316 (if limited
317 "#define \\|#enddef"
318 (substring wesnoth-preprocessor-regexp 5))
319 "\\)"))
321 (defun wesnoth-find-next (type)
322 "Find the next element of TYPE.
323 TYPE is a symbol representing an element type, or a list of
324 element types to find."
325 (let ((element (wesnoth-next-element)))
326 (while (and element (if (listp type)
327 (not (member (car element) type))
328 (not (eq (car element) type))))
329 (setq element (wesnoth-next-element)))
330 (when (if (listp type)
331 (member (car element) type)
332 (eq (car element) type))
333 element)))
335 (defun wesnoth-next-element ()
336 "Move to the next element in the buffer.
337 Return non-nil when an element is found. Otherwise, return nil."
338 (interactive)
339 (save-match-data
340 (and (or (eolp) (looking-at "[}\t ]"))
341 (search-forward-regexp "[^}
342 \t ]" (point-max) t)
343 (forward-char -1)))
344 (let ((details (wesnoth-element-type (point))))
345 (save-match-data
346 (when (nth 2 details)
347 (goto-char (nth 2 details))
348 (while (nth 3 (parse-partial-sexp
349 (save-excursion (search-backward-regexp
350 (wesnoth-element t) (point-min) t)
351 (point))
352 (point)))
353 (search-forward "\"" (point-max) t))))
354 details))
356 (defun wesnoth-element-type (point)
357 "Return details regarding the element at POINT.
358 A list is returned, the elements of the list represent the
359 following, respectively: A symbol representing the type of
360 element; the position of the start of the element and the
361 position of the end of the element. POINT must be at the start
362 of the element."
363 (let ((element-matches
364 '(("{\\(.*?[/\]\\)+}" . nil) ;; pathnames
365 ("{\\(\\w\\|_\\)+" . macro)
366 ("\\[\\+?[^/]+?\\]" . tag-opening)
367 ("\\[/.+?\\]" . tag-closing)
368 ("\\(\\w\\|_\\)+[\t ]*=" . attribute)
369 ("#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def \\)" . preprocessor)
370 ("#.*$" . comment)
371 ("[^\t ]+") . nil)))
372 (catch 'result
373 (dolist (pair element-matches)
374 (when (looking-at (car pair))
375 (throw 'result (list (cdr pair)
376 (match-beginning 0)
377 (match-end 0))))))))
379 (defun wesnoth-estimate-element-type (point)
380 "Return match data for a partial element at POINT."
381 (save-excursion
382 (goto-char point)
383 (let ((element-matches
384 '(("{\\(.*?[/\]\\)+$" . nil) ;; pathnames
385 ("{\\(\\w\\|_\\)*$" . macro)
386 ("\\[/\\(\\w\\|_\\)*$" . tag-closing)
387 ("\\[\\+?\\(\\w\\|_\\)*$" . tag-opening)
388 ("^[\t ]*\\(\\w\\|_\\)+$" . attribute)
389 ("^[\t ]*#\\w*$" . preprocessor))))
390 (catch 'result
391 (dolist (pair element-matches)
392 (when (looking-at (car pair))
393 (throw 'result (list (cdr pair)
394 (match-beginning 0)
395 (match-end 0)))))))))
397 (defun wesnoth-guess-element-type (point)
398 "Return details for the the element near POINT.
399 Locate the start of the element before determining details.
400 BOUND is the limit to search backwards."
401 (let ((details (wesnoth-estimate-element-type point))
402 (bound (save-excursion
403 (goto-char point)
404 (beginning-of-line)
405 (point))))
406 (while (and (not (car details)) (> point bound))
407 (setq point (1- point)
408 details (wesnoth-estimate-element-type point)))
409 (and (nth 1 details)
410 (>= (point) (nth 1 details))
411 (nth 2 details)
412 (<= (point) (nth 2 details))
413 details)))
416 ;;; Insertion and completion
417 (defmacro wesnoth-element-completion (completions prompt partial
418 &optional completep)
419 "Process completion of COMPLETIONS, displaying PROMPT.
420 PARTIAL is the partial string on which to attempt completion.
421 If COMPLETEP is non-nil, do not prompt if no completion is found."
422 `(let* ((element (when ,partial (try-completion ,partial ,completions))))
423 (cond ((eq element t)
424 ,partial)
425 ((and completep (null element))
426 nil)
427 ((and element (eq (try-completion element ,completions) t))
428 element)
429 ((> (length (all-completions (or element "") ,completions)) 1)
430 (completing-read ,prompt ,completions
431 nil nil element
432 'wesnoth-history-list))
434 element))))
436 (defun wesnoth-parent-tag ()
437 "Return the name of the parent tag.
438 If the parent is a preprocessor statement, return non-nil.
439 If the element does not have a parent, return nil.
440 Otherwise, return a string containing the name of the parent tag."
441 (save-excursion
442 (let ((start-point (point))
443 (depth 1))
444 (when (save-excursion (> (point) (progn (back-to-indentation)
445 (point))))
446 (end-of-line))
447 (while (and (> depth 0)
448 (search-backward-regexp (wesnoth-element t)
449 (point-min) t))
450 (if (string-match "[\t ]*\\[/" (match-string 0))
451 (setq depth (1+ depth))
452 (setq depth (1- depth))))
453 (beginning-of-line)
454 (if (> depth 0)
456 (when (looking-at (wesnoth-element-opening))
457 (let ((parent (match-string-no-properties 1)))
458 (if (or (string-match wesnoth-preprocessor-opening-regexp parent)
459 ;; Check if we're immediately within a macro
460 (and (goto-char start-point)
461 (search-backward-regexp "[}{]" (point-min) t)
462 (string= (match-string 0) "{")
463 (goto-char start-point)
464 (not (and (search-backward parent (point-min) t)
465 (search-backward-regexp "[}{]" (point-min) t)
466 (string= (match-string 0) "{")))))
468 (substring parent 1 (1- (length parent))))))))))
470 (defun wesnoth-partial-macro-p ()
471 "Return non-nil if point is in a partial macro."
472 (save-excursion
473 (let ((opened 0))
474 (search-backward-regexp "{" (point-min) t)
475 (while (search-forward-regexp "[{}]" (point-max) t)
476 (if (string= (match-string 0) "{")
477 (setq opened (1+ opened))
478 (setq opened (1- opened))))
479 (> opened 0))))
481 (defun wesnoth-indent-or-complete (&optional elements)
482 "Indent or complete the line at point, depending on context.
483 ELEMENTS is the number of elements to wrap around if inserting
484 matching tags."
485 (interactive "P")
486 (or elements (setq elements 0))
487 (let ((details (wesnoth-guess-element-type (point))))
488 (cond
489 ((eq (car details) 'tag-opening)
490 (wesnoth-complete-tag elements t))
491 ((and (eq (car details) 'macro)
492 (wesnoth-partial-macro-p))
493 (wesnoth-complete-macro t))
494 ((eq (car details) 'preprocessor)
495 (wesnoth-complete-preprocessor elements t))
496 ((eq (car details) 'tag-closing)
497 ;; FIXME: Solve incorrect behaviour when partial closing is "[/"
498 (insert "a")
499 (and (wesnoth-insert-missing-closing t)
500 (delete-region (nth 1 details)
501 (save-excursion (beginning-of-line) (point))))
502 (end-of-line)
503 (wesnoth-indent))
504 ((eq (car details) 'attribute)
505 (wesnoth-complete-attribute t))
507 (wesnoth-indent)))))
509 (defun wesnoth-preprocessor-closed-p (preprocessor)
510 "Determine whether PREPROCESSOR has been closed.
511 PREPROCESSOR is a string matching the preprocessor statement to
512 be inserted."
513 (save-excursion
514 (back-to-indentation)
515 (wesnoth-jump-to-matching preprocessor)
516 (looking-at
517 (if (string= preprocessor "#define ")
518 "#enddef"
519 "#endif"))))
521 (defun wesnoth-complete-preprocessor (&optional elements completep)
522 "Complete and insert the preprocessor at point.
523 ELEMENTS is the number of elements to wrap around.
524 If COMPLETEP is non-nil, attempt to complete preprocessor at point."
525 (interactive "P")
526 (or elements (setq elements 0))
527 (let* ((completions (wesnoth-emacs-completion-formats
528 '("define" "else" "ifdef" "ifndef"
529 "enddef" "endif" "undef")))
530 (partial (when completep
531 (save-excursion
532 (back-to-indentation)
533 (when (looking-at "#\\(\\w*\\)$")
534 (match-string-no-properties 1)))))
535 (preprocessor (wesnoth-element-completion
536 completions "Preprocessor: " partial completep))
537 (closedp
538 (save-excursion
539 (when preprocessor
540 (unless (string= "#" (substring preprocessor 0 1))
541 (setq preprocessor (concat "#" preprocessor)))
542 (when (string-match "#\\(define\\|ifn?def\\|undef\\)" preprocessor)
543 (setq preprocessor (concat preprocessor " ")))
544 (when partial
545 (delete-region
546 (save-excursion
547 (progn (search-backward
549 (save-excursion (back-to-indentation)
550 (point))
552 (point)))
553 (point)))
554 (wesnoth-preprocessor-closed-p preprocessor)))))
555 (when preprocessor
556 (when partial
557 (delete-region
558 (save-excursion
559 (progn (search-backward
560 "#" (save-excursion (back-to-indentation)
561 (point))
563 (point)))
564 (point)))
565 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor)
566 (not closedp))
567 (progn
568 (wesnoth-insert-tag elements preprocessor)
569 (forward-line -1)
570 (end-of-line))
571 (wesnoth-insert-element-separately preprocessor)))))
573 (defun wesnoth-macro-arguments ()
574 "Find any current macro arguments."
575 (let ((results '())
576 (depth (wesnoth-within-define (point))))
577 (save-excursion
578 (while (> depth 0)
579 (save-match-data
580 (search-backward-regexp
581 "[\t ]*#define \\(?:\\w+\\|_\\)*\\(\\([\t ]*\\(\\w\\|_\\)+\\)*\\)"
582 (point-min) t)
583 (when (<= (wesnoth-within-define (point)) depth)
584 (and (> depth 0)
585 (setq results
586 (append (mapcar (lambda (macro)
587 (list macro nil))
588 (split-string
589 (match-string-no-properties 1)))
590 results)))
591 (setq depth (1- depth)))))
592 results)))
594 (defun wesnoth-complete-macro (&optional completep)
595 "Complete and insert the macro at point.
596 If COMPLETEP is non-nil, attempt to complete the macro at point."
597 (interactive)
598 (wesnoth-update-project-information)
599 (let* ((macro-information (append (wesnoth-macro-arguments)
600 wesnoth-macro-data
601 wesnoth-local-macro-data))
602 (completions (wesnoth-emacs-completion-formats
603 (mapcar 'car macro-information)))
604 (details (wesnoth-guess-element-type (point)))
605 (partial (when
606 (save-excursion
607 (and completep
608 (eq (car details) 'macro)
609 (goto-char (cadr details))
610 (looking-at "{\\(\\(\\w\\|_\\)*\\)")))
611 (match-string-no-properties 1)))
612 (macro (wesnoth-element-completion completions "Macro: " partial
613 completep))
614 (args (cadr (assoc macro macro-information))))
615 (when macro
616 (if partial
617 (progn
618 ;; Delete the region corresponding to the current macro.
619 (delete-region (nth 1 details) (nth 2 details))
620 (insert "{" macro (if args " }" "}")))
621 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
622 (save-excursion
623 (wesnoth-indent))
624 (forward-char -1)
625 (when args
626 (let ((input (read-string (concat (car args) ": "))))
627 (insert input (if (and (cdr args)
628 (not (string= input "")))
629 " " ""))
630 (while (and (setq args (cdr args)) (not (string= input "")))
631 (insert (setq input (read-string (concat (car args) ": ")))
632 (if (and (not (string= input ""))
633 (cdr args))
634 " " "")))))
635 (when (null args) (forward-char 1)))))
637 (defun wesnoth-complete-attribute (&optional completep)
638 "Insert the attribute at point.
639 If COMPLETEP is non-nil, attempt to complete the attribute at point."
640 (interactive)
641 (let* ((completions (wesnoth-build-completion 1))
642 (details (save-excursion
643 (back-to-indentation)
644 (wesnoth-guess-element-type (point))))
645 (partial (when completep
646 (when (save-excursion
647 (back-to-indentation)
648 (looking-at "\\(\\(\\w\\|_\\)+\\)"))
649 (match-string-no-properties 1))))
650 (attribute (wesnoth-element-completion completions "Attribute: "
651 partial completep)))
652 (when attribute
653 (if partial
654 (progn
655 (delete-region (nth 1 details) (nth 2 details))
656 (insert attribute "="))
657 (wesnoth-insert-element-separately attribute
658 (if (string-match "=" attribute)
660 "=")))
661 (save-excursion
662 (wesnoth-indent)))))
664 (defun wesnoth-complete-tag (&optional elements completep)
665 "Complete and insert the tag at point.
666 ELEMENTS is the number of elements to wrap around.
667 If COMPLETEP is non-nil, attempt to complete tag at point."
668 (interactive "P")
669 (or elements (setq elements 0))
670 (let* ((completions (wesnoth-build-completion 0))
671 (details (wesnoth-guess-element-type (point)))
672 (partial (save-excursion
673 (when (and completep
674 (eq (car details) 'tag-opening)
675 (goto-char (cadr details))
676 (looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$"))
677 (match-string-no-properties 1))))
678 (tag (wesnoth-element-completion completions "Tag: " partial
679 completep))
680 (closedp
681 (save-excursion
682 (wesnoth-jump-to-matching (concat "[" tag "]"))
683 (back-to-indentation)
684 (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
685 (string= tag (match-string 1))))))
686 (if tag
687 (progn
688 (if completep
689 (progn
690 (delete-region (nth 1 details) (nth 2 details))
691 (if closedp
692 (progn
693 (wesnoth-insert-and-indent "[" tag "]")
694 (end-of-line))
695 (wesnoth-insert-tag elements tag)))
696 (wesnoth-insert-tag elements tag)))
697 (or completep (wesnoth-insert-tag elements)))))
699 (defun wesnoth-build-completion (position)
700 "Create a new list for tag completion if necessary.
701 Rebuilding list is required for versions of GNU Emacs earlier
702 than 22. POSITION is the argument passed to `nth' for
703 `wesnoth-tag-data'."
704 (interactive "P")
705 (let ((parent (wesnoth-parent-tag)))
706 (wesnoth-emacs-completion-formats
707 (if (or (stringp parent) (null parent))
708 (nth position (gethash parent wesnoth-tag-hash-table))
709 (mapcar 'car wesnoth-tag-data)))))
711 (defun wesnoth-emacs-completion-formats (candidates)
712 "Return the completions in the correct format for `emacs-major-version'.
713 CANDIDATES is a list of all possible completions."
714 (if (> emacs-major-version 21)
715 candidates
716 (let ((tags '())
717 (iter 0))
718 (dolist (tag candidates)
719 (setq iter (1+ iter))
720 (setq tags (append tags (list (cons tag iter)))))
721 tags)))
723 (defun wesnoth-insert-tag (&optional elements tagname)
724 "Insert the specified opening tag and it's matching closing tag.
725 Both the opening and closing tags will be placed on their own
726 lines with point positioned between them. Completion of tags at
727 the prompt uses `wesnoth-tags-list'.
729 ELEMENTS is specifies the number of following blocks which the
730 tag should wrap around.
732 TAGNAME is the name of the tag to be inserted."
733 (interactive "Ps")
734 (unless tagname
735 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 0)
736 nil nil nil 'wesnoth-history-list)))
737 (when (or (not elements)
738 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
739 wesnoth-preprocessor-regexp "\\)")))
740 (setq elements 0))
741 (let ((start (save-excursion (forward-line -1) (point)))
742 (end (unless (= elements 0)
743 ;; Work around some strange behaviour when the target is at the
744 ;; end of the buffer.
745 (save-excursion
746 (goto-char (point-max))
747 (beginning-of-line)
748 (unless (looking-at "^[\t ]*$")
749 (end-of-line)
750 (newline)))
751 (wesnoth-nth-pair-position elements))))
752 (if (string-match wesnoth-preprocessor-regexp tagname)
753 (wesnoth-insert-element-separately tagname)
754 (wesnoth-insert-element-separately "[" tagname "]"))
755 (save-excursion
756 (if end
757 (goto-char (marker-position end))
758 (newline (if (string-match wesnoth-preprocessor-regexp tagname) 1 2)))
759 (if (string-match wesnoth-preprocessor-opening-regexp tagname)
760 (wesnoth-insert-element-separately
761 (if (string= tagname "#define ")
762 "#enddef"
763 "#endif"))
764 (wesnoth-insert-element-separately "[/" tagname "]"))
765 (indent-region start (point) nil))
766 (unless end
767 (forward-line 1)))
768 (wesnoth-indent))
770 (defun wesnoth-insert-element-separately (&rest strings)
771 "Concatenate STRINGS and insert them on a line of their own."
772 (if (save-excursion (and (> (point) (progn (back-to-indentation) (point)))))
773 (if (save-excursion (forward-line 1) (looking-at "^[\t ]*$"))
774 (progn
775 (forward-line 1)
776 (end-of-line))
777 (end-of-line)
778 (newline))
779 (beginning-of-line)
780 (if (looking-at "^[\t ]*$")
781 (end-of-line)
782 (open-line 1)))
783 (insert (apply 'concat strings)))
785 (defun wesnoth-insert-missing-closing (&optional completep)
786 "Insert the next expected closing element at point.
787 If COMPLETEP is non-nil, do not move forward a line when scanning
788 for the matching tag."
789 (interactive)
790 (let ((match nil))
791 (save-excursion
792 (when (wesnoth-search-for-matching-tag
793 'search-backward-regexp (wesnoth-element-opening) 'point-min
794 (if completep nil 1))
795 (setq match (and (looking-at (wesnoth-element-opening))
796 (match-string-no-properties 1)))))
797 (when match
798 (if (string= (substring match 0 1) "[")
799 (wesnoth-insert-element-separately
800 "[/" (substring match 1 (1- (length match))) "]")
801 (wesnoth-insert-element-separately
802 (cdr (assoc match '(("#define " . "#enddef")
803 ("#ifndef " . "#endif")
804 ("#ifdef " . "#endif")))))))
805 (wesnoth-indent)
806 (end-of-line)
807 match))
809 (defun wesnoth-insert-and-indent (&rest args)
810 "Concatenate and insert the given string(s) before indenting.
812 ARGS is a list of strings to be inserted."
813 (insert (apply 'concat args))
814 (wesnoth-indent))
816 (defun wesnoth-newline (&optional indent)
817 "Indent the current line and create a newline.
818 If `wesnoth-auto-indent-flag' is nil, indentation will not be
819 performed. Indentation can be forced by setting INDENT to
820 non-nil."
821 (interactive "P")
822 (newline)
823 (save-excursion
824 (forward-line -1)
825 (when (and (or wesnoth-auto-indent-flag indent)
826 (not (looking-at "^[\t ]*$")))
827 (wesnoth-indent))))
829 ;;; Movement
830 (defun wesnoth-navigate-element (repeat search-function bound)
831 "Move point to the tag in the given direction REPEAT times.
833 SEARCH-FUNCTION is the symbol of the function for searching in
834 the required direction, with BOUND marking the furthest point to
835 search."
836 (or repeat (setq repeat 1))
837 (while (> repeat 0)
838 (and (eq search-function 'search-forward-regexp) (end-of-line))
839 (funcall search-function (wesnoth-element-opening) bound t)
840 (back-to-indentation)
841 (setq repeat (1- repeat))))
843 (defun wesnoth-nth-pair-position (count)
844 "Return `point' after COUNT number of matching element pairs.
845 COUNT is a positive number representing the number of balanced
846 pairs to move across.
847 `point' is returned as a marker object."
848 (save-excursion
849 (let ((failed nil))
850 (if (> (point) (save-excursion (back-to-indentation) (point)))
851 (end-of-line)
852 (beginning-of-line))
853 (while (> count 0)
854 ;; Currently looking-at target tag. Stop here to avoid
855 ;; incorrect nesting.
856 (unless (wesnoth-search-for-matching-tag
857 'search-forward-regexp (wesnoth-element-closing) 'point-max)
858 (setq count 0)
859 (setq failed t))
860 (and (> (setq count (1- count)) 0) (forward-line 1)))
861 (if failed
862 (beginning-of-line)
863 (end-of-line))
864 (point-marker))))
866 (defun wesnoth-forward-element (repeat)
867 "Move point to the end of the next tag.
868 REPEAT is an optional numeric argument. If REPEAT is non-nil,
869 jump forward the specified number of tags."
870 (interactive "p")
871 (if (< repeat 0)
872 (wesnoth-backward-element (abs repeat))
873 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
875 (defun wesnoth-backward-element (repeat)
876 "Move point to the beginning of the previous tag.
877 REPEAT is an optional numeric argument. If REPEAT is non-nil,
878 jump backward the specified number of tags."
879 (interactive "p")
880 (if (< repeat 0)
881 (wesnoth-forward-element (abs repeat))
882 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
884 (defmacro wesnoth-search-for-matching-tag (search-function
885 search-string bound &optional skip)
886 "Search for the matching tag for the current line.
887 SEARCH-FUNCTION is the name of the function used to perform the search.
888 SEARCH-STRING is a string representing the matching tag type.
889 BOUND is the bound to be passed to the search function.
890 If SKIP is non-nil, skip the first element and continue from there."
891 `(let ((depth 1))
892 (when (and (or (and (numberp ,skip) (forward-line ,skip))
893 (funcall ,search-function (wesnoth-element) (funcall ,bound) t))
894 (or ,skip (not (string-match ,search-string (match-string 0)))))
895 (while (and (> depth 0)
896 (funcall ,search-function (wesnoth-element)
897 (funcall ,bound) t))
898 (if (string-match ,search-string (match-string 0))
899 (setq depth (1- depth))
900 (setq depth (1+ depth))))
901 (= depth 0))))
903 (defun wesnoth-jump-to-matching (&optional element)
904 "Jump point to the matching opening/closing tag.
905 ELEMENT is an element to find a match for."
906 (interactive)
907 (beginning-of-line)
908 (let ((target nil)
909 (first-element nil))
910 (save-excursion
911 (cond
912 ((or (and (stringp element)
913 (string-match (wesnoth-element-opening) element))
914 (looking-at (wesnoth-element-opening)))
915 (setq first-element (match-string-no-properties 0 element))
916 (when (wesnoth-search-for-matching-tag
917 'search-forward-regexp (wesnoth-element-closing) 'point-max
918 (and (stringp element) 1))
919 (beginning-of-line)
920 (if (and (string-match wesnoth-preprocessor-opening-regexp
921 first-element)
922 (looking-at (wesnoth-element-closing)))
923 (when (string= (match-string-no-properties 0)
924 (cdr (assoc first-element
925 '(("#define " . "#enddef")
926 ("#ifndef " . "#endif")
927 ("#ifdef " . "#endif")))))
928 (setq target (point)))
929 (setq target (point)))))
930 ((or (and (stringp element)
931 (string-match (wesnoth-element-closing) element))
932 (looking-at (wesnoth-element-closing)))
933 (end-of-line)
934 (setq first-element (match-string-no-properties 0 element))
935 (when (wesnoth-search-for-matching-tag
936 'search-backward-regexp (wesnoth-element-opening)
937 'wesnoth-wml-start-pos (and (stringp element) -1))
938 (if (and (string-match wesnoth-preprocessor-closing-regexp
939 first-element)
940 (looking-at (wesnoth-element-opening)))
941 (progn
942 (when (or (and (string= "#enddef" first-element)
943 (string= "#define "
944 (match-string-no-properties
945 0)))
946 (and (string= "#endif" first-element)
947 (string-match
948 "#ifn?def "
949 (match-string-no-properties
950 0))))
951 (setq target (point))))
952 (setq target (point)))))
954 (search-backward-regexp (wesnoth-element-opening) (point-min) t)
955 (setq target (point)))))
956 (if target
957 (progn
958 (goto-char target)
959 (back-to-indentation))
960 (when (interactive-p)
961 (message "%s" "Tag does not appear to be matched")))))
963 ;;; Indentation
964 (defun wesnoth-wml-start-pos ()
965 "Determine the position of `point' relative to where the actual WML begins.
966 Return the likely starting position of the WML if it is found.
967 Otherwise return nil."
968 (save-excursion
969 (goto-char (point-min))
970 (when (search-forward-regexp (wesnoth-element) (point-max) t)
971 (beginning-of-line)
972 (point))))
974 (defun wesnoth-first-column-indent-p (point)
975 "Return non-nil if the current line should not be indented.
977 POINT is the position in the buffer to check.
978 CONTEXT represents the type of element which precedes the current element."
979 (or (not (wesnoth-wml-start-pos))
980 (<= (point) (wesnoth-wml-start-pos))
981 (nth 3 (parse-partial-sexp
982 (save-excursion (search-backward-regexp
983 (wesnoth-element t) (point-min) t)
984 (point))
985 point))
986 (looking-at wesnoth-preprocessor-regexp)))
988 (defun wesnoth-indent ()
989 "Indent the current line as WML."
990 (save-excursion
991 (beginning-of-line)
992 (let* ((cur-indent 0)
993 (context-data (wesnoth-determine-context (point)))
994 (context (car context-data))
995 (ref-indent (cdr context-data)))
996 (unless (wesnoth-first-column-indent-p (point))
997 (cond
998 ((eq context 'opening)
999 (if (or (and wesnoth-indent-savefile
1000 (or (looking-at "[\t ]*{NEXT ")
1001 (and (not (looking-at (wesnoth-element-closing t)))
1002 (not (looking-at "[\t ]*{NEXT ")))))
1003 (looking-at (wesnoth-element-opening t))
1004 (looking-at "[\t ]*{FOREACH "))
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 (not (looking-at "[\t ]*{FOREACH "))))
1012 (setq cur-indent (- ref-indent wesnoth-base-indent))
1013 (setq cur-indent ref-indent)))))
1014 (indent-line-to (max cur-indent 0))))
1015 (when (> (save-excursion (back-to-indentation) (point))
1016 (point))
1017 (back-to-indentation)))
1019 (defun wesnoth-within-define (position)
1020 "Determine whether point is currently inside a #define block.
1021 POSITION is the initial cursor position."
1022 (save-match-data
1023 (let ((depth 0)
1024 (defblocks (or wesnoth-define-blocks
1025 (wesnoth-find-macro-definitions))))
1026 (unless (equal (car defblocks) 'none)
1027 (dolist (element defblocks)
1028 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
1029 (list position)) '>)) position)
1030 (setq depth (max (car element) depth)))))
1031 depth)))
1033 (defun wesnoth-find-macro-definitions ()
1034 "Return information regarding positioning of macro definitions."
1035 (save-excursion
1036 (goto-char (point-min))
1037 (let ((depth 0)
1038 openings cache)
1039 (while (search-forward-regexp "#define\\|#enddef" (point-max) t)
1040 (and (string= (match-string 0) "#define") (beginning-of-line))
1041 (setq depth
1042 (if (string= (match-string 0) "#define")
1043 (progn
1044 (add-to-list 'openings (point-marker))
1045 (1+ depth))
1046 (if openings
1047 (progn
1048 (add-to-list 'cache
1049 (list depth (list (car openings)
1050 (point-marker))))
1051 (setq openings (cdr openings))
1052 (1- depth))
1053 depth)))
1054 (end-of-line))
1055 (or cache (list 'none)))))
1057 (defun wesnoth-indent-region (start end)
1058 "Indent the region from START to END.
1059 Creates and destroys a cache of macro definition details as necessary."
1060 (interactive "r")
1061 (unwind-protect
1062 (save-excursion
1063 (goto-char end)
1064 (setq end (point-marker))
1065 (goto-char start)
1066 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1067 (or (bolp) (forward-line 1))
1068 (while (< (point) end)
1069 (if (looking-at "^[\t ]*$")
1070 (indent-line-to 0)
1071 (funcall indent-line-function))
1072 (forward-line 1)))
1073 (setq wesnoth-define-blocks nil)))
1075 (defun wesnoth-determine-context (position)
1076 "Determine the type of the last relevant element.
1077 POSITION is the buffer position of the element for which to
1078 determine the context."
1079 (save-excursion
1080 (let* ((elements (concat (substring (wesnoth-element t)
1081 0 (- (length (wesnoth-element t)) 3))
1082 "\\|{FOREACH .+}\\|{NEXT .+}\\)"))
1083 (match (or
1084 (and (search-backward-regexp
1085 elements (point-min) t)
1086 (progn
1087 (while (save-match-data
1088 (looking-at "^[\t ]*\\[[^/].+\\]\\[/.+\\]"))
1089 (search-backward-regexp elements
1090 (point-min) t))
1092 (match-string 1))
1093 ""))
1094 (depth (wesnoth-within-define position)))
1095 (while (and (wesnoth-wml-start-pos)
1096 (> (wesnoth-within-define (point)) depth)
1097 (not (= (point) (wesnoth-wml-start-pos))))
1098 (search-backward-regexp elements
1099 (wesnoth-wml-start-pos) t)
1100 (setq match (match-string 1)))
1101 (when (and (wesnoth-wml-start-pos)
1102 (= (point) (wesnoth-wml-start-pos))
1103 (= depth 0)
1104 (string-match "#define" match))
1105 ;; Found nothing of use; reset match and assume top-level tag.
1106 (setq match ""))
1107 (cond
1108 ((string-match "\\[/\\|#enddef" match)
1109 (cons 'closing (current-indentation)))
1110 ((string-match "{NEXT " match)
1111 (cons 'closing (if wesnoth-indent-savefile
1112 (- (current-indentation) wesnoth-base-indent)
1113 (current-indentation))))
1114 ((string-match "\\[[^/]?\\|#define\\|{FOREACH " match)
1115 (cons 'opening (current-indentation)))))))
1117 (defun wesnoth-newline-and-indent (&optional indent)
1118 "Indent both the current line and the newline created.
1119 If `wesnoth-auto-indent-flag' is nil, indentation will not be
1120 performed.
1122 If the optional argument, INDENT is non-nil, force indentation to
1123 be performed."
1124 (interactive)
1125 (wesnoth-newline)
1126 (when (or wesnoth-auto-indent-flag indent)
1127 (wesnoth-indent)))
1129 ;;; WML checks
1130 (defun wesnoth-check-element-type (position)
1131 "Determine the context of the element.
1132 POSITION is the position of the element in the list."
1133 (let ((parent (save-match-data (wesnoth-parent-tag))))
1134 (if (or (stringp parent) (null parent))
1135 (member (match-string-no-properties 1)
1136 (nth position (gethash parent wesnoth-tag-hash-table)))
1137 (member (match-string-no-properties 1)
1138 (mapcar 'car wesnoth-tag-data)))))
1140 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
1141 (defun wesnoth-line-number-at-pos (&optional pos)
1142 "Return (narrowed) buffer line number at position POS.
1143 If POS is nil, use current buffer location.
1144 Counting starts at (point-min), so the value refers
1145 to the contents of the accessible portion of the buffer."
1146 (let ((opoint (or pos (point))) start)
1147 (save-excursion
1148 (goto-char (point-min))
1149 (setq start (point))
1150 (goto-char opoint)
1151 (forward-line 0)
1152 (1+ (count-lines start (point))))))
1154 (defun wesnoth-check-output (buffer format-string &rest args)
1155 "Output the string as passed to `format'.
1156 BUFFER is the buffer to output the result.
1157 FORMAT-STRING is the string as the first argument of `format'.
1158 ARGS is any additional data required by `format' to handle FORMAT-STRING."
1159 (save-excursion
1160 (let ((lnap (wesnoth-line-number-at-pos)))
1161 (set-buffer buffer)
1162 (let ((buffer-read-only nil))
1163 (insert (apply 'format (concat "Line %d: " format-string "\n")
1164 lnap args))))))
1166 (defun wesnoth-extract-macro-details (macro-arguments)
1167 "Return a list of all macros in MACRO-ARGUMENTS."
1168 (when macro-arguments
1169 (let ((results '()))
1170 (dolist (macro (split-string macro-arguments "[{}][\t ]*"))
1171 (when (string-match "^\\(\\(?:\\w\\|_\\)+\\)"
1172 macro)
1173 (add-to-list 'results (match-string-no-properties 1 macro))))
1174 results)))
1176 (defmacro wesnoth-check-process (format-string &rest args)
1177 "Output to buffer where requested and position overlays as required.
1178 FORMAT-STRING is the string to pass as the first argument to
1179 `format' for the error. ARGS is a list of arguments required by
1180 FORMAT-STRING."
1181 `(progn
1182 (wesnoth-check-output outbuf ,format-string ,@args)
1183 (wesnoth-place-overlay (match-beginning 0) (match-end 0))))
1185 (defmacro wesnoth-overlay-at-pos-p (position)
1186 "Return non-nil when there is an overlay at POSITION."
1187 `(and (overlays-at (goto-char ,position))
1188 (overlay-get (car (overlays-at (point))) 'wesnoth-error)
1189 (overlay-start (car (overlays-at (point))))))
1191 (defmacro wesnoth-locate-warning (string start end)
1192 "Search for STRING and move to the warning in the given direction.
1193 Searching starts from `point' and will wrap from START if no
1194 match was found. STRING is a form to locate the warning in the
1195 required direction. START is the start of the region searched.
1196 END is the end of the region searched."
1197 `(let ((target nil))
1198 (save-excursion
1199 (cond
1200 ((setq target (wesnoth-overlay-at-pos-p ,string)))
1201 ((setq target (wesnoth-overlay-at-pos-p ,start)))
1202 ((and (not (= (goto-char ,string) ,end))
1203 (setq target (wesnoth-overlay-at-pos-p (point)))))))
1204 target))
1206 (defun wesnoth-forward-warning ()
1207 "Move to the next warning."
1208 (interactive)
1209 (let ((target
1210 (if (fboundp 'next-overlay-change)
1211 (save-excursion
1212 (end-of-line)
1213 (wesnoth-locate-warning (next-overlay-change (point))
1214 (point-min)
1215 (point-max)))
1216 (wesnoth-target-position '< '>))))
1217 (if target
1218 (goto-char target)
1219 (message "%s" "No warnings found"))))
1221 (defun wesnoth-backward-warning ()
1222 "Move to the previous warning."
1223 (interactive)
1224 (let ((target
1225 (if (fboundp 'previous-overlay-change)
1226 (save-excursion
1227 (beginning-of-line)
1228 (wesnoth-locate-warning (1- (previous-overlay-change (point)))
1229 (point-max)
1230 (point-min)))
1231 (wesnoth-target-position '> '< t))))
1232 (if target
1233 (goto-char target)
1234 (message "%s" "No warnings found"))))
1236 (defun wesnoth-target-position (predicate search &optional lastp)
1237 "Return the target marker position.
1238 PREDICATE is the function to use to sort
1239 `wesnoth-warning-markers'. SEARCH must be a function which
1240 returns non-nil when the match is correct. If LASTP is non-nil,
1241 swap the order of the sorted positions when attempting to
1242 fallback."
1243 (let ((positions (sort (mapcar 'marker-position wesnoth-warning-markers)
1244 predicate)))
1245 (or (catch 'pos
1246 (dolist (position positions)
1247 (when (funcall search position (point))
1248 (throw 'pos position))))
1249 (car positions))))
1251 (defun wesnoth-place-overlay (start end)
1252 "Place overlay in the region and apply necessary properties.
1253 START is the start of the region to place the overlay. END is
1254 the end of the region to place the overlay."
1255 (if (fboundp 'overlay-put)
1256 (let ((overlay (make-overlay start end)))
1257 (overlay-put overlay 'wesnoth-error t)
1258 (overlay-put overlay 'face 'wesnoth-warning-face))
1259 (add-to-list 'wesnoth-warning-markers (save-excursion
1260 (goto-char start)
1261 (point-marker)))))
1263 (defun wesnoth-check-wml ()
1264 "Perform context-sensitive analysis of WML-code."
1265 (interactive)
1266 (wesnoth-update-project-information)
1267 (if (fboundp 'delete-overlay)
1268 (dolist (overlay (overlays-in (point-min) (point-max)))
1269 (if (eq 'wesnoth-warning-face (overlay-get overlay 'face))
1270 (delete-overlay overlay)))
1271 (setq wesnoth-warning-markers nil))
1272 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
1273 (error "WML data not available; unable to generate report"))
1274 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1275 (let ((unmatched '())
1276 (outbuf (and (interactive-p) (get-buffer-create "*WML*")))
1277 (last-match-pos 1)
1278 (details nil)
1279 (foreach '()))
1280 (save-excursion
1281 (set-buffer outbuf)
1282 (let ((buffer (buffer-name))
1283 (buffer-read-only nil))
1284 (erase-buffer)
1285 (insert (format "Checking %s...\n" buffer))
1286 (message (format "Checking %s..." buffer))))
1287 (save-excursion
1288 (goto-char (point-min))
1289 (while (setq details (wesnoth-find-next
1290 '(tag-opening tag-closing preprocessor attribute
1291 macro)))
1292 (save-excursion
1293 (goto-char (match-beginning 0))
1294 (cond ((nth 3 (parse-partial-sexp last-match-pos (point)))
1295 nil)
1296 ((eq (car details) 'macro)
1297 (dolist (macro (save-match-data
1298 (wesnoth-extract-macro-details
1299 (match-string-no-properties 0))))
1300 (unless (assoc macro
1301 (append (wesnoth-macro-arguments)
1302 wesnoth-local-macro-data
1303 wesnoth-macro-data))
1304 (wesnoth-check-process "Unknown macro: '%s'"
1305 macro)))
1306 (save-match-data
1307 (when
1308 (looking-at
1309 "{\\(FOREACH\\|NEXT\\).*[\t ]+\\(\\(?:\\w\\|_\\)+\\)}")
1310 (if (string= (match-string-no-properties 1) "FOREACH")
1311 (setq foreach
1312 (cons (match-string-no-properties 2) foreach))
1313 (if (string= (match-string-no-properties 1) "NEXT")
1314 (progn
1315 (unless (string= (car foreach)
1316 (match-string-no-properties 2))
1317 (wesnoth-check-process
1318 (concat "NEXT does not match corresponding "
1319 "FOREACH: '%s' found; '%s' expected.")
1320 (match-string-no-properties 2)
1321 (car foreach)))
1322 (setq foreach (cdr foreach))))))))
1323 ((looking-at "[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
1324 (unless (wesnoth-check-element-type 0)
1325 (wesnoth-check-process
1326 "Tag not available in this context: '%s'"
1327 (match-string-no-properties 1)))
1328 (setq unmatched (cons (match-string-no-properties 1)
1329 unmatched)))
1330 ((looking-at
1331 (concat "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\|#undef\\)"
1332 "\\( \\(\\w\\|_\\)+\\)*"))
1333 (unless (match-string-no-properties 2)
1334 (wesnoth-check-process
1335 (concat "Preprocessor statement has no argument: "
1336 (match-string-no-properties 1))))
1337 (unless (string= (match-string-no-properties 1) "#undef")
1338 (setq unmatched (cons (match-string-no-properties 1)
1339 unmatched))))
1340 ((looking-at wesnoth-preprocessor-closing-regexp)
1341 (when (and unmatched
1342 (not (string-match
1343 (cdr (assoc (match-string-no-properties 1)
1344 '(("enddef" . "#define")
1345 ("endif" . "#ifn?def"))))
1346 (car unmatched))))
1347 (wesnoth-check-process
1348 "Preprocessor statement does not nest correctly"))
1349 (setq unmatched (cdr unmatched)))
1350 ((looking-at "[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
1351 (unless (wesnoth-check-element-type 1)
1352 (wesnoth-check-process
1353 "Attribute not available in this context: '%s'"
1354 (match-string-no-properties 1)))
1355 (unless (match-string 3)
1356 (wesnoth-check-process
1357 "Attribute has no value")))
1358 ((looking-at "[\t ]*#else")
1359 (unless (string-match "ifn?def" (car unmatched))
1360 (if (string= (car unmatched) "#define")
1361 (wesnoth-check-process "Expecting: '%s'"
1362 (car unmatched))
1363 (wesnoth-check-process "Expecting: '[/%s]'"
1364 (car unmatched)))))
1365 ((looking-at "[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]")
1366 (when (and unmatched
1367 (not (string= (match-string-no-properties 1)
1368 (car unmatched))))
1369 (wesnoth-check-process
1370 "Expecting '%s'"
1371 (or (cdr (assoc (car unmatched)
1372 '(("#define" . "#enddef")
1373 ("#ifdef" . "#endif")
1374 ("#ifndef" . "#endif"))))
1375 (concat "[/" (car unmatched) "]"))))
1376 (setq unmatched (cdr unmatched)
1377 last-match-pos (point))))))
1378 (when foreach
1379 (dolist (var foreach)
1380 (wesnoth-check-process "Unmatched FOREACH: '%s'" var)))
1381 (when unmatched
1382 (dolist (element unmatched)
1383 (wesnoth-check-process "Unmatched element: '%s'" element))))
1384 (save-excursion
1385 (setq wesnoth-define-blocks nil)
1386 (set-buffer outbuf)
1387 (toggle-read-only t)
1388 (let ((buffer (buffer-name))
1389 (buffer-read-only nil))
1390 (display-buffer outbuf t)
1391 (let ((warnings (- (wesnoth-line-number-at-pos
1392 (save-excursion (goto-char (point-max)))) 2)))
1393 (insert (format (concat "\nCheck complete. %d warning"
1394 (if (= warnings 1) "." "s.")) warnings)))
1395 (message (format "Checking %s...done" buffer))))))
1398 ;;; wesnoth-mode
1399 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
1400 "Major mode for editing WML."
1401 (kill-all-local-variables)
1402 (use-local-map wesnoth-mode-map)
1403 (setq major-mode 'wesnoth-mode)
1404 (setq mode-name "WML")
1405 (set-syntax-table wesnoth-syntax-table)
1406 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
1407 (set (make-local-variable 'comment-start) "#")
1408 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
1409 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
1410 (set (make-local-variable 'wesnoth-warning-markers) '())
1411 (set (make-local-variable 'font-lock-defaults)
1412 '(wesnoth-font-lock-keywords
1413 nil t nil nil
1414 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
1415 (setq indent-tabs-mode nil)
1416 (easy-menu-add wesnoth-menu wesnoth-mode-map)
1417 (wesnoth-create-wml-hash-table)
1418 (wesnoth-update-project-information)
1419 (run-hooks 'wesnoth-mode-hook))
1421 (provide 'wesnoth-mode)
1423 ;;; wesnoth-mode.el ends here