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