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