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