d987eda487c25286cce784dc0450fbfb4899d3f3
[wesnoth-mode.git] / wesnoth-mode.el
blobd987eda487c25286cce784dc0450fbfb4899d3f3
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 1 (1- (length parent))) position))))))))
541 (defun wesnoth-partial-macro-p ()
542 "Return non-nil if point is in a partial macro."
543 (save-excursion
544 (let ((opened 0))
545 (search-backward-regexp "{" (point-min) t)
546 (while (search-forward-regexp "[{}]" (point-max) t)
547 (if (string= (match-string 0) "{")
548 (setq opened (1+ opened))
549 (setq opened (1- opened))))
550 (> opened 0))))
552 (defun wesnoth-indent-or-complete (&optional elements)
553 "Indent or complete the line at point, depending on context.
554 ELEMENTS is the number of elements to wrap around if inserting
555 matching tags."
556 (interactive "P")
557 (or elements (setq elements 0))
558 (let ((details (wesnoth-guess-element-type (point))))
559 (cond
560 ((eq (car details) 'tag-opening)
561 (wesnoth-complete-tag elements t))
562 ((and (eq (car details) 'macro)
563 (wesnoth-partial-macro-p))
564 (wesnoth-complete-macro t))
565 ((eq (car details) 'preprocessor)
566 (wesnoth-complete-preprocessor elements t))
567 ((eq (car details) 'tag-closing)
568 ;; FIXME: Solve incorrect behaviour when partial closing is "[/"
569 (insert "a")
570 (and (wesnoth-insert-missing-closing t)
571 (delete-region (nth 1 details)
572 (save-excursion (beginning-of-line) (point))))
573 (end-of-line)
574 (wesnoth-indent))
575 ((eq (car details) 'attribute)
576 (wesnoth-complete-attribute t))
578 (wesnoth-indent)))))
580 (defun wesnoth-preprocessor-closed-p (preprocessor)
581 "Determine whether PREPROCESSOR has been closed.
582 PREPROCESSOR is a string matching the preprocessor statement to
583 be inserted."
584 (save-excursion
585 (back-to-indentation)
586 (wesnoth-jump-to-matching preprocessor)
587 (looking-at
588 (if (string= preprocessor "#define ")
589 "#enddef"
590 "#endif"))))
592 (defun wesnoth-complete-preprocessor (&optional elements completep)
593 "Complete and insert the preprocessor at point.
594 ELEMENTS is the number of elements to wrap around.
595 If COMPLETEP is non-nil, attempt to complete preprocessor at point."
596 (interactive "P")
597 (or elements (setq elements 0))
598 (let* ((completions (wesnoth-emacs-completion-formats
599 '("define" "else" "ifdef" "ifndef"
600 "enddef" "endif" "undef")))
601 (partial (when completep
602 (save-excursion
603 (back-to-indentation)
604 (when (looking-at "#\\(\\w*\\)$")
605 (match-string-no-properties 1)))))
606 (preprocessor (wesnoth-element-completion
607 completions "Preprocessor: " partial completep))
608 (details (wesnoth-guess-element-type (point)))
609 (closedp
610 (save-excursion
611 (when preprocessor
612 (unless (string= "#" (substring preprocessor 0 1))
613 (setq preprocessor (concat "#" preprocessor)))
614 (when (string-match "#\\(define\\|ifn?def\\|undef\\)"
615 preprocessor)
616 (setq preprocessor (concat preprocessor " ")))
617 (when partial
618 (delete-region (nth 1 details) (nth 2 details)))
619 (wesnoth-preprocessor-closed-p preprocessor)))))
620 (when preprocessor
621 (when partial
622 (delete-region
623 (save-excursion
624 (progn (search-backward
625 "#" (save-excursion (back-to-indentation)
626 (point))
628 (point)))
629 (point)))
630 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor)
631 (not closedp))
632 (progn
633 (wesnoth-insert-tag elements preprocessor)
634 (forward-line -1)
635 (end-of-line))
636 (wesnoth-insert-element-separately preprocessor)))))
638 (defun wesnoth-macro-arguments ()
639 "Find any current macro arguments."
640 (let ((results '())
641 (depth (wesnoth-within-define (point))))
642 (save-excursion
643 (while (> depth 0)
644 (save-match-data
645 (search-backward-regexp
646 "[\t ]*#define \\(?:\\w+\\|_\\)*\\(\\([\t ]*\\(\\w\\|_\\)+\\)*\\)"
647 (point-min) t)
648 (when (<= (wesnoth-within-define (point)) depth)
649 (and (> depth 0)
650 (setq results
651 (append (mapcar (lambda (macro)
652 (list macro nil))
653 (split-string
654 (match-string-no-properties 1)))
655 results)))
656 (setq depth (1- depth)))))
657 results)))
659 (defun wesnoth-complete-macro (&optional completep)
660 "Complete and insert the macro at point.
661 If COMPLETEP is non-nil, attempt to complete the macro at point."
662 (interactive)
663 (wesnoth-update-project-information)
664 (let* ((macro-information (wesnoth-merge-macro-data
665 wesnoth-macro-data
666 (wesnoth-macro-additions)
667 wesnoth-local-macro-data
668 (wesnoth-macro-arguments)))
669 (completions (wesnoth-emacs-completion-formats
670 (mapcar 'car macro-information)))
671 (details (wesnoth-guess-element-type (point)))
672 (partial (when
673 (save-excursion
674 (and completep
675 (eq (car details) 'macro)
676 (goto-char (cadr details))
677 (looking-at "{\\(\\(\\w\\|_\\)*\\)")))
678 (match-string-no-properties 1)))
679 (macro (wesnoth-element-completion completions "Macro: " partial
680 completep))
681 (args (cadr (assoc macro macro-information))))
682 (when macro
683 (if partial
684 (progn
685 ;; Delete the region corresponding to the current macro.
686 (delete-region (nth 1 details) (nth 2 details))
687 (insert "{" macro (if args " }" "}")))
688 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
689 (save-excursion
690 (wesnoth-indent))
691 (forward-char -1)
692 (when args
693 (let ((input (read-string (concat (car args) ": "))))
694 (insert input (if (and (cdr args)
695 (not (string= input "")))
696 " " ""))
697 (while (and (setq args (cdr args)) (not (string= input "")))
698 (insert (setq input (read-string (concat (car args) ": ")))
699 (if (and (not (string= input ""))
700 (cdr args))
701 " " "")))))
702 (when (null args) (forward-char 1)))))
704 (defun wesnoth-complete-attribute (&optional completep)
705 "Insert the attribute at point.
706 If COMPLETEP is non-nil, attempt to complete the attribute at point."
707 (interactive)
708 (wesnoth-refresh-wml-data)
709 (let* ((details (save-excursion
710 (back-to-indentation)
711 (wesnoth-guess-element-type (point))))
712 (completions (save-excursion (when (nth 1 details)
713 (goto-char (nth 1 details)))
714 (wesnoth-build-completion 1)))
715 (partial (when completep
716 (when (save-excursion
717 (back-to-indentation)
718 (looking-at "\\(\\(\\w\\|_\\)+\\)"))
719 (match-string-no-properties 1))))
720 (attribute (wesnoth-element-completion completions "Attribute: "
721 partial completep)))
722 (when attribute
723 (if partial
724 (progn
725 (delete-region (nth 1 details) (nth 2 details))
726 (insert attribute "="))
727 (wesnoth-insert-element-separately attribute
728 (if (string-match "=" attribute)
730 "=")))
731 (save-excursion
732 (wesnoth-indent)))))
734 (defun wesnoth-complete-tag (&optional elements completep)
735 "Complete and insert the tag at point.
736 ELEMENTS is the number of elements to wrap around.
737 If COMPLETEP is non-nil, attempt to complete tag at point."
738 (interactive "P")
739 (or elements (setq elements 0))
740 (let* ((details (wesnoth-guess-element-type (point)))
741 (completions (save-excursion (and (nth 1 details)
742 (goto-char (nth 1 details)))
743 (wesnoth-build-completion 0)))
744 (partial (save-excursion
745 (when (and completep
746 (eq (car details) 'tag-opening)
747 (goto-char (cadr details))
748 (looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$"))
749 (match-string-no-properties 1))))
750 (tag (wesnoth-element-completion completions "Tag: " partial
751 completep))
752 (closedp
753 (save-excursion
754 (wesnoth-jump-to-matching (concat "[" tag "]"))
755 (back-to-indentation)
756 (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
757 (string= tag (match-string 1))))))
758 (if tag
759 (progn
760 (if completep
761 (progn
762 (delete-region (nth 1 details) (nth 2 details))
763 (if closedp
764 (progn
765 (wesnoth-insert-and-indent "[" tag "]")
766 (end-of-line))
767 (wesnoth-insert-tag elements tag)))
768 (wesnoth-insert-tag elements tag)))
769 (or completep (wesnoth-insert-tag elements)))))
771 (defun wesnoth-build-completion (position)
772 "Create a new list for tag completion if necessary.
773 Rebuilding list is required for versions of GNU Emacs earlier
774 than 22. POSITION is the argument passed to `nth' for
775 `wesnoth-tag-data'."
776 (interactive "P")
777 (let ((parent (wesnoth-active-parent-tag))
778 (tag-data (wesnoth-refresh-wml-data)))
779 (wesnoth-emacs-completion-formats
780 (if (or (stringp parent) (null parent))
781 (nth position (gethash parent wesnoth-tag-hash-table))
782 (mapcar 'car tag-data)))))
784 (defun wesnoth-emacs-completion-formats (candidates)
785 "Return the completions in the correct format for `emacs-major-version'.
786 CANDIDATES is a list of all possible completions."
787 (if (> emacs-major-version 21)
788 candidates
789 (let ((tags '())
790 (iter 0))
791 (dolist (tag candidates)
792 (setq iter (1+ iter))
793 (setq tags (append tags (list (cons tag iter)))))
794 tags)))
796 (defun wesnoth-insert-tag (&optional elements tagname)
797 "Insert the specified opening tag and it's matching closing tag.
798 Both the opening and closing tags will be placed on their own
799 lines with point positioned between them. Completion of tags at
800 the prompt uses `wesnoth-tags-list'.
802 ELEMENTS is specifies the number of following blocks which the
803 tag should wrap around.
805 TAGNAME is the name of the tag to be inserted."
806 (interactive "Ps")
807 (unless tagname
808 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 0)
809 nil nil nil 'wesnoth-history-list)))
810 (when (or (not elements)
811 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
812 wesnoth-preprocessor-regexp "\\)")))
813 (setq elements 0))
814 (let ((start (save-excursion (forward-line -1) (point)))
815 (end (unless (= elements 0)
816 ;; Work around some strange behaviour when the target is at the
817 ;; end of the buffer.
818 (save-excursion
819 (goto-char (point-max))
820 (beginning-of-line)
821 (unless (looking-at "^[\t ]*$")
822 (end-of-line)
823 (newline)))
824 (wesnoth-nth-pair-position elements))))
825 (if (string-match wesnoth-preprocessor-regexp tagname)
826 (wesnoth-insert-element-separately tagname)
827 (wesnoth-insert-element-separately "[" tagname "]"))
828 (save-excursion
829 (if end
830 (goto-char (marker-position end))
831 (newline (if (string-match wesnoth-preprocessor-regexp tagname) 1 2)))
832 (if (string-match wesnoth-preprocessor-opening-regexp tagname)
833 (wesnoth-insert-element-separately
834 (if (string= tagname "#define ")
835 "#enddef"
836 "#endif"))
837 (wesnoth-insert-element-separately "[/" (if (string-match "^+"
838 tagname)
839 (substring tagname 1)
840 tagname)
841 "]"))
842 (indent-region start (point) nil))
843 (unless end
844 (forward-line 1)))
845 (wesnoth-indent))
847 (defun wesnoth-insert-element-separately (&rest strings)
848 "Concatenate STRINGS and insert them on a line of their own."
849 (if (save-excursion (and (> (point) (progn (back-to-indentation) (point)))))
850 (if (save-excursion (forward-line 1) (looking-at "^[\t ]*$"))
851 (progn
852 (forward-line 1)
853 (end-of-line))
854 (end-of-line)
855 (newline))
856 (beginning-of-line)
857 (if (looking-at "^[\t ]*$")
858 (end-of-line)
859 (open-line 1)))
860 (insert (apply 'concat strings)))
862 (defun wesnoth-insert-missing-closing (&optional completep)
863 "Insert the next expected closing element at point.
864 If COMPLETEP is non-nil, do not move forward a line when scanning
865 for the matching tag."
866 (interactive)
867 (let ((match nil)
868 (skip t))
869 (save-excursion
870 (when (and (null completep)
871 (<= (point) (save-excursion (back-to-indentation) (point))))
872 (if (save-excursion (beginning-of-line)
873 (looking-at (wesnoth-element-opening)))
874 (forward-line -1)
875 (when
876 (save-excursion (beginning-of-line)
877 (looking-at (wesnoth-element-closing)))
878 (setq skip nil))))
879 (when (wesnoth-search-for-matching-tag
880 'search-backward-regexp (wesnoth-element-opening) 'point-min
881 (and skip (if completep nil 1)))
882 (setq match (and (looking-at (wesnoth-element-opening))
883 (match-string-no-properties 1)))))
884 (when match
885 (if (string= (substring match 0 1) "[")
886 (wesnoth-insert-element-separately
887 "[/"
888 (let ((tagname (substring match 1 (1- (length match)))))
889 (if (string-match "^+" tagname)
890 (substring tagname 1)
891 tagname))
892 "]")
893 (wesnoth-insert-element-separately
894 (cdr (assoc match '(("#define " . "#enddef")
895 ("#ifndef " . "#endif")
896 ("#ifdef " . "#endif")))))))
897 (wesnoth-indent)
898 (end-of-line)
899 match))
901 (defun wesnoth-insert-and-indent (&rest args)
902 "Concatenate and insert the given string(s) before indenting.
904 ARGS is a list of strings to be inserted."
905 (insert (apply 'concat args))
906 (wesnoth-indent))
908 (defun wesnoth-newline (&optional indent)
909 "Indent the current line and create a newline.
910 If `wesnoth-auto-indent-flag' is nil, indentation will not be
911 performed. Indentation can be forced by setting INDENT to
912 non-nil."
913 (interactive "P")
914 (newline)
915 (save-excursion
916 (forward-line -1)
917 (when (and (or wesnoth-auto-indent-flag indent)
918 (not (looking-at "^[\t ]*$")))
919 (wesnoth-indent))))
921 ;;; Movement
922 (defun wesnoth-navigate-element (repeat search-function bound)
923 "Move point to the tag in the given direction REPEAT times.
925 SEARCH-FUNCTION is the symbol of the function for searching in
926 the required direction, with BOUND marking the furthest point to
927 search."
928 (or repeat (setq repeat 1))
929 (while (> repeat 0)
930 (and (eq search-function 'search-forward-regexp) (end-of-line))
931 (funcall search-function (wesnoth-element-opening) bound t)
932 (back-to-indentation)
933 (setq repeat (1- repeat))))
935 (defun wesnoth-nth-pair-position (count)
936 "Return `point' after COUNT number of matching element pairs.
937 COUNT is a positive number representing the number of balanced
938 pairs to move across.
939 `point' is returned as a marker object."
940 (save-excursion
941 (let ((failed nil))
942 (if (> (point) (save-excursion (back-to-indentation) (point)))
943 (end-of-line)
944 (beginning-of-line))
945 (while (> count 0)
946 ;; Currently looking-at target tag. Stop here to avoid
947 ;; incorrect nesting.
948 (unless (wesnoth-search-for-matching-tag
949 'search-forward-regexp (wesnoth-element-closing) 'point-max)
950 (setq count 0)
951 (setq failed t))
952 (and (> (setq count (1- count)) 0) (forward-line 1)))
953 (if failed
954 (beginning-of-line)
955 (end-of-line))
956 (point-marker))))
958 (defun wesnoth-forward-element (repeat)
959 "Move point to the end of the next tag.
960 REPEAT is an optional numeric argument. If REPEAT is non-nil,
961 jump forward the specified number of tags."
962 (interactive "p")
963 (if (< repeat 0)
964 (wesnoth-backward-element (abs repeat))
965 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
967 (defun wesnoth-backward-element (repeat)
968 "Move point to the beginning of the previous tag.
969 REPEAT is an optional numeric argument. If REPEAT is non-nil,
970 jump backward the specified number of tags."
971 (interactive "p")
972 (if (< repeat 0)
973 (wesnoth-forward-element (abs repeat))
974 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
976 (defun wesnoth-search-for-matching-tag (search-function
977 search-string bound &optional skip)
978 "Search for the matching tag for the current line.
979 SEARCH-FUNCTION is the name of the function used to perform the search.
980 SEARCH-STRING is a string representing the matching tag type.
981 BOUND is the bound to be passed to the search function.
982 If SKIP is non-nil, skip the first element and continue from there."
983 (let ((depth 1))
984 (when (and (or (and (numberp skip) (forward-line skip))
985 (funcall search-function (wesnoth-element)
986 (funcall bound) t))
987 (or skip (not (string-match search-string (match-string 0)))))
988 (while (and (> depth 0)
989 (funcall search-function (wesnoth-element)
990 (funcall bound) t))
991 (if (string-match search-string (match-string 0))
992 (setq depth (1- depth))
993 (setq depth (1+ depth))))
994 (= depth 0))))
996 (defun wesnoth-jump-to-matching (&optional element)
997 "Jump point to the matching opening/closing tag.
998 ELEMENT is an element to find a match for."
999 (interactive)
1000 (beginning-of-line)
1001 (let ((target nil)
1002 (first-element nil))
1003 (save-excursion
1004 (cond
1005 ((or (and (stringp element)
1006 (string-match (wesnoth-element-opening) element))
1007 (looking-at (wesnoth-element-opening)))
1008 (setq first-element (match-string-no-properties 0 element))
1009 (when (wesnoth-search-for-matching-tag
1010 'search-forward-regexp (wesnoth-element-closing) 'point-max
1011 (and (stringp element) 1))
1012 (beginning-of-line)
1013 (if (and (string-match wesnoth-preprocessor-opening-regexp
1014 first-element)
1015 (looking-at (wesnoth-element-closing)))
1016 (when (string= (match-string-no-properties 0)
1017 (cdr (assoc first-element
1018 '(("#define " . "#enddef")
1019 ("#ifndef " . "#endif")
1020 ("#ifdef " . "#endif")))))
1021 (setq target (point)))
1022 (setq target (point)))))
1023 ((or (and (stringp element)
1024 (string-match (wesnoth-element-closing) element))
1025 (looking-at (wesnoth-element-closing)))
1026 (end-of-line)
1027 (setq first-element (match-string-no-properties 0 element))
1028 (when (wesnoth-search-for-matching-tag
1029 'search-backward-regexp (wesnoth-element-opening)
1030 'wesnoth-wml-start-pos (and (stringp element) -1))
1031 (if (and (string-match wesnoth-preprocessor-closing-regexp
1032 first-element)
1033 (looking-at (wesnoth-element-opening)))
1034 (progn
1035 (when (or (and (string= "#enddef" first-element)
1036 (string= "#define "
1037 (match-string-no-properties
1038 0)))
1039 (and (string= "#endif" first-element)
1040 (string-match
1041 "#ifn?def "
1042 (match-string-no-properties
1043 0))))
1044 (setq target (point))))
1045 (setq target (point)))))
1047 (search-backward-regexp (wesnoth-element-opening) (point-min) t)
1048 (setq target (point)))))
1049 (if target
1050 (progn
1051 (goto-char target)
1052 (back-to-indentation))
1053 (when (interactive-p)
1054 (message "%s" "Tag does not appear to be matched")))))
1056 ;;; Indentation
1057 (defun wesnoth-wml-start-pos ()
1058 "Determine the position of `point' relative to where the actual WML begins.
1059 Return the likely starting position of the WML if it is found.
1060 Otherwise return nil."
1061 (save-excursion
1062 (goto-char (point-min))
1063 (when (search-forward-regexp (wesnoth-element) (point-max) t)
1064 (beginning-of-line)
1065 (point))))
1067 (defun wesnoth-first-column-indent-p (point)
1068 "Return non-nil if the current line should not be indented.
1070 POINT is the position in the buffer to check.
1071 CONTEXT represents the type of element which precedes the current element."
1072 (or (not (wesnoth-wml-start-pos))
1073 (<= (point) (wesnoth-wml-start-pos))
1074 (nth 3 (parse-partial-sexp
1075 (save-excursion (search-backward-regexp
1076 (wesnoth-element t) (point-min) t)
1077 (point))
1078 point))
1079 (and (looking-at wesnoth-preprocessor-regexp)
1080 wesnoth-indent-preprocessor-bol)))
1082 (defun wesnoth-indent ()
1083 "Indent the current line as WML."
1084 (save-excursion
1085 (beginning-of-line)
1086 (let* ((cur-indent 0)
1087 (context-data (wesnoth-determine-context (point)))
1088 (context (car context-data))
1089 (ref-indent (cdr context-data)))
1090 (unless (wesnoth-first-column-indent-p (point))
1091 (cond
1092 ((eq context 'opening)
1093 (if (and (looking-at "^[\t ]*#else")
1094 (not wesnoth-indent-preprocessor-bol))
1095 (setq cur-indent ref-indent)
1096 (if (or (and wesnoth-indent-savefile
1097 (or (looking-at "[\t ]*{NEXT ")
1098 (and (not
1099 (looking-at (wesnoth-element-closing t)))
1100 (not (looking-at "[\t ]*{NEXT ")))))
1101 (looking-at (wesnoth-element-opening t))
1102 (looking-at "[\t ]*{FOREACH "))
1103 (setq cur-indent (+ ref-indent wesnoth-base-indent))
1104 (setq cur-indent ref-indent))))
1105 ((eq context 'closing)
1106 (if (and (looking-at "^[\t ]*#else")
1107 (not wesnoth-indent-preprocessor-bol))
1108 (setq cur-indent (- ref-indent wesnoth-base-indent))
1109 (if (or (looking-at
1110 (concat "^[\t ]*\\(\\[/\\|\\#enddef"
1111 (if (not wesnoth-indent-preprocessor-bol)
1112 "\\|#endif"
1114 "\\)"))
1115 (and (not wesnoth-indent-savefile)
1116 (not (looking-at (wesnoth-element-opening t)))
1117 (not (looking-at "[\t ]*{FOREACH "))))
1118 (setq cur-indent (- ref-indent wesnoth-base-indent))
1119 (setq cur-indent ref-indent))))))
1120 (indent-line-to (max cur-indent 0))))
1121 (when (> (save-excursion (back-to-indentation) (point))
1122 (point))
1123 (back-to-indentation)))
1125 (defun wesnoth-within-define (position)
1126 "Determine whether point is currently inside a #define block.
1127 POSITION is the initial cursor position."
1128 (save-match-data
1129 (let ((depth 0)
1130 (defblocks (or wesnoth-define-blocks
1131 (wesnoth-find-macro-definitions))))
1132 (unless (equal (car defblocks) 'none)
1133 (dolist (element defblocks)
1134 (when (= (cadr (sort (append (mapcar 'marker-position
1135 (cadr element))
1136 (list position)) '>)) position)
1137 (setq depth (max (car element) depth)))))
1138 depth)))
1140 (defun wesnoth-find-macro-definitions ()
1141 "Return information regarding positioning of macro definitions."
1142 (save-excursion
1143 (goto-char (point-min))
1144 (let ((depth 0)
1145 openings cache)
1146 (while (search-forward-regexp "#define\\|#enddef" (point-max) t)
1147 (and (string= (match-string 0) "#define") (beginning-of-line))
1148 (setq depth
1149 (if (string= (match-string 0) "#define")
1150 (progn
1151 (add-to-list 'openings (point-marker))
1152 (1+ depth))
1153 (if openings
1154 (progn
1155 (add-to-list 'cache
1156 (list depth (list (car openings)
1157 (point-marker))))
1158 (setq openings (cdr openings))
1159 (1- depth))
1160 depth)))
1161 (end-of-line))
1162 (or cache (list 'none)))))
1164 (defun wesnoth-indent-region (start end)
1165 "Indent the region from START to END.
1166 Creates and destroys a cache of macro definition details as necessary."
1167 (interactive "r")
1168 (unwind-protect
1169 (save-excursion
1170 (goto-char end)
1171 (setq end (point-marker))
1172 (goto-char start)
1173 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1174 (or (bolp) (forward-line 1))
1175 (while (< (point) end)
1176 (if (looking-at "^[\t ]*$")
1177 (indent-line-to 0)
1178 (funcall indent-line-function))
1179 (forward-line 1)))
1180 (setq wesnoth-define-blocks nil)))
1182 (defun wesnoth-determine-context (position)
1183 "Determine the type of the last relevant element.
1184 POSITION is the buffer position of the element for which to
1185 determine the context."
1186 (save-excursion
1187 (let* ((elements (concat (substring (wesnoth-element t)
1188 0 (- (length (wesnoth-element t)) 2))
1189 "\\|{FOREACH .+}\\|{NEXT .+}\\)"))
1190 (match (or
1191 (and (search-backward-regexp
1192 elements (point-min) t)
1193 (progn
1194 (while
1195 (save-match-data
1196 (looking-at "^[\t ]*\\[[^/].+\\]\\[/.+\\]"))
1197 (search-backward-regexp elements
1198 (point-min) t))
1200 (match-string 1))
1201 ""))
1202 (depth (wesnoth-within-define position)))
1203 (while (and (wesnoth-wml-start-pos)
1204 (> (wesnoth-within-define (point)) depth)
1205 (not (= (point) (wesnoth-wml-start-pos))))
1206 (search-backward-regexp elements
1207 (wesnoth-wml-start-pos) t)
1208 (setq match (match-string 1)))
1209 (when (and (wesnoth-wml-start-pos)
1210 (= (point) (wesnoth-wml-start-pos))
1211 (= depth 0)
1212 (string-match "#define" match))
1213 ;; Found nothing of use; reset match and assume top-level tag.
1214 (setq match ""))
1215 (cond
1216 ((string-match (concat "\\[/\\|#enddef"
1217 (if (not wesnoth-indent-preprocessor-bol)
1218 "\\|#endif"
1219 ""))
1220 match)
1221 (cons 'closing (current-indentation)))
1222 ((string-match "{NEXT " match)
1223 (cons 'closing (if wesnoth-indent-savefile
1224 (- (current-indentation) wesnoth-base-indent)
1225 (current-indentation))))
1226 ((string-match (concat "\\[[^/]?\\|#define\\|{FOREACH "
1227 (if (not wesnoth-indent-preprocessor-bol)
1228 "\\|#ifn?def \\|#else"
1229 "")) match)
1230 (cons 'opening (current-indentation)))))))
1232 (defun wesnoth-newline-and-indent (&optional indent)
1233 "Indent both the current line and the newline created.
1234 If `wesnoth-auto-indent-flag' is nil, indentation will not be
1235 performed.
1237 If the optional argument, INDENT is non-nil, force indentation to
1238 be performed."
1239 (interactive)
1240 (wesnoth-newline)
1241 (when (or wesnoth-auto-indent-flag indent)
1242 (wesnoth-indent)))
1244 ;;; WML checks
1245 (defun wesnoth-check-element-type (position)
1246 "Determine the context of the element.
1247 POSITION is the position of the element in the list."
1248 (let ((parent (save-match-data (car (wesnoth-parent-tag)))))
1249 (if (or (stringp parent) (null parent))
1250 (member (match-string-no-properties 1)
1251 (nth position (gethash parent wesnoth-tag-hash-table)))
1252 (member (match-string-no-properties 1)
1253 (let ((result '()))
1254 (mapc
1255 '(lambda (x)
1256 (let ((value (nth position (cdr x))))
1257 (and value (mapc '(lambda (y)
1258 (setq result (cons y result)))
1259 value))))
1260 (or wesnoth-tmp-tag-data (wesnoth-refresh-wml-data)))
1261 result)))))
1263 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
1264 (defun wesnoth-line-number-at-pos (&optional pos)
1265 "Return (narrowed) buffer line number at position POS.
1266 If POS is nil, use current buffer location.
1267 Counting starts at (point-min), so the value refers
1268 to the contents of the accessible portion of the buffer."
1269 (let ((opoint (or pos (point))) start)
1270 (save-excursion
1271 (goto-char (point-min))
1272 (setq start (point))
1273 (goto-char opoint)
1274 (forward-line 0)
1275 (1+ (count-lines start (point))))))
1277 (defun wesnoth-check-output (buffer format-string &rest args)
1278 "Output the string as passed to `format'.
1279 BUFFER is the buffer to output the result.
1280 FORMAT-STRING is the string as the first argument of `format'.
1281 ARGS is any additional data required by `format' to handle FORMAT-STRING."
1282 (save-excursion
1283 (let ((lnap (wesnoth-line-number-at-pos)))
1284 (set-buffer buffer)
1285 (let ((buffer-read-only nil))
1286 (insert (apply 'format (concat "Line %d: " format-string "\n")
1287 lnap args))))))
1289 (defun wesnoth-extract-macro-details (macro-arguments)
1290 "Return a list of all macros in MACRO-ARGUMENTS."
1291 (when macro-arguments
1292 (let ((results '()))
1293 (dolist (macro (split-string macro-arguments "[{}][\t ]*"))
1294 (when (string-match "^\\(\\(?:\\w\\|_\\)+\\)"
1295 macro)
1296 (add-to-list 'results (match-string-no-properties 1 macro))))
1297 results)))
1299 (defmacro wesnoth-check-process (format-string &rest args)
1300 "Output to buffer where requested and position overlays as required.
1301 FORMAT-STRING is the string to pass as the first argument to
1302 `format' for the error. ARGS is a list of arguments required by
1303 FORMAT-STRING."
1304 `(progn
1305 (wesnoth-check-output outbuf ,format-string ,@args)
1306 (wesnoth-place-overlay (match-beginning 0) (match-end 0))))
1308 (defmacro wesnoth-overlay-at-pos-p (position)
1309 "Return non-nil when there is an overlay at POSITION."
1310 `(and (overlays-at (goto-char ,position))
1311 (overlay-get (car (overlays-at (point))) 'wesnoth-error)
1312 (overlay-start (car (overlays-at (point))))))
1314 (defmacro wesnoth-locate-warning (string start end)
1315 "Search for STRING and move to the warning in the given direction.
1316 Searching starts from `point' and will wrap from START if no
1317 match was found. STRING is a form to locate the warning in the
1318 required direction. START is the start of the region searched.
1319 END is the end of the region searched."
1320 `(let ((target nil))
1321 (save-excursion
1322 (cond
1323 ((setq target (wesnoth-overlay-at-pos-p ,string)))
1324 ((setq target (wesnoth-overlay-at-pos-p ,start)))
1325 ((and (not (= (goto-char ,string) ,end))
1326 (setq target (wesnoth-overlay-at-pos-p (point)))))))
1327 target))
1329 (defun wesnoth-forward-warning ()
1330 "Move to the next warning."
1331 (interactive)
1332 (let ((target
1333 (if (fboundp 'next-overlay-change)
1334 (save-excursion
1335 (end-of-line)
1336 (wesnoth-locate-warning (next-overlay-change (point))
1337 (point-min)
1338 (point-max)))
1339 (wesnoth-target-position '< '>))))
1340 (if target
1341 (goto-char target)
1342 (message "%s" "No warnings found"))))
1344 (defun wesnoth-backward-warning ()
1345 "Move to the previous warning."
1346 (interactive)
1347 (let ((target
1348 (if (fboundp 'previous-overlay-change)
1349 (save-excursion
1350 (beginning-of-line)
1351 (wesnoth-locate-warning (1- (previous-overlay-change (point)))
1352 (point-max)
1353 (point-min)))
1354 (wesnoth-target-position '> '< t))))
1355 (if target
1356 (goto-char target)
1357 (message "%s" "No warnings found"))))
1359 (defun wesnoth-target-position (predicate search &optional lastp)
1360 "Return the target marker position.
1361 PREDICATE is the function to use to sort
1362 `wesnoth-warning-markers'. SEARCH must be a function which
1363 returns non-nil when the match is correct. If LASTP is non-nil,
1364 swap the order of the sorted positions when attempting to
1365 fallback."
1366 (let ((positions (sort (mapcar 'marker-position wesnoth-warning-markers)
1367 predicate)))
1368 (or (catch 'pos
1369 (dolist (position positions)
1370 (when (funcall search position (point))
1371 (throw 'pos position))))
1372 (car positions))))
1374 (defun wesnoth-place-overlay (start end)
1375 "Place overlay in the region and apply necessary properties.
1376 START is the start of the region to place the overlay. END is
1377 the end of the region to place the overlay."
1378 (if (fboundp 'overlay-put)
1379 (let ((overlay (make-overlay start end)))
1380 (overlay-put overlay 'wesnoth-error t)
1381 (overlay-put overlay 'face 'wesnoth-warning-face))
1382 (add-to-list 'wesnoth-warning-markers (save-excursion
1383 (goto-char start)
1384 (point-marker)))))
1386 (defun wesnoth-kill-block ()
1387 "Kill the block at point."
1388 (interactive)
1389 (save-excursion
1390 (let ((kill-whole-line t))
1391 (if (looking-at "[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|\
1392 #ifn?def\\)")
1393 (kill-region (point)
1394 (save-excursion
1395 (wesnoth-jump-to-matching)
1396 (forward-line 1)
1397 (point)))
1398 (kill-line))
1399 (wesnoth-indent))))
1401 (defun wesnoth-mark-block ()
1402 "Mark the block at point."
1403 (interactive)
1404 (when (looking-at "[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|\
1405 #ifn?def\\)")
1406 (push-mark (save-excursion
1407 (wesnoth-jump-to-matching)
1408 (end-of-line)
1409 (point)))))
1411 (defun wesnoth-down-list (&optional arg)
1412 "Move forward down ARG levels of elements.
1413 If ARG is not specified, move forward down one level."
1414 (interactive "p")
1415 (unless arg
1416 (setq arg 1))
1417 (when (looking-at "\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|\
1418 #ifn?def\\|\\(\\w\\|_\\)+=\\)")
1419 (forward-char 1))
1420 (let ((target nil))
1421 (save-excursion
1422 (when (looking-at "\\(\\w\\|_\\)+=")
1423 (if (and (search-forward-regexp (wesnoth-element) (point-max) t)
1424 (progn (beginning-of-line)
1425 (looking-at (wesnoth-element-opening t))))
1426 (setq target (point))
1427 (message "%s" "Innermost level"))))
1428 (when target (goto-char target)))
1429 (while (> arg 0)
1430 (when (> (save-excursion (wesnoth-jump-to-matching) (point)) (point))
1431 (search-forward-regexp
1432 "\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define\\|#ifn?def\\|\\(\\w\\|_\\)+=\\)"
1433 (save-excursion
1434 (wesnoth-jump-to-matching)
1435 (point))
1437 (setq arg (1- arg)))
1438 (back-to-indentation))
1440 (defun wesnoth-backward-up-list (&optional arg)
1441 "Move backward up ARG levels of elements.
1442 If ARG is not specified, move backward up one level."
1443 (interactive "p")
1444 (unless arg
1445 (setq arg 1))
1446 (let ((parent nil))
1447 (while (> arg 0)
1448 (setq parent (cdr (wesnoth-parent-tag)))
1449 (if (numberp parent)
1450 (progn
1451 (goto-char parent)
1452 (setq arg (1- arg)))
1453 (message "%s" "Outermost level")
1454 (setq arg 0))
1455 (when (numberp parent)
1456 (back-to-indentation)))))
1458 (defun wesnoth-forward-list (&optional arg)
1459 "Move to forward ARG elements at the current depth.
1460 If ARG is not specifed, move forward one element."
1461 (interactive "p")
1462 (unless arg
1463 (setq arg 1))
1464 (when (save-excursion (beginning-of-line)
1465 (looking-at (wesnoth-element-opening)))
1466 (wesnoth-jump-to-matching)
1467 (setq arg (1- arg)))
1468 (let ((revert-target (point)))
1469 (while (> arg 0)
1470 (beginning-of-line)
1471 (unless (looking-at (wesnoth-element-closing))
1472 (wesnoth-jump-to-matching))
1473 (end-of-line)
1474 (if (and (search-forward-regexp (wesnoth-element) (point-max) t)
1475 (save-excursion (beginning-of-line)
1476 (looking-at (wesnoth-element-opening))))
1477 (setq revert-target (point))
1478 (goto-char revert-target)
1479 (message "%s" "End of block"))
1480 (setq arg (1- arg))))
1481 (when (save-excursion (beginning-of-line)
1482 (looking-at (wesnoth-element-opening)))
1483 (wesnoth-jump-to-matching))
1484 (end-of-line))
1486 (defun wesnoth-backward-list (&optional arg)
1487 "Move to backward ARG elements at the current depth.
1488 If ARG is not specifed, move backward one element."
1489 (interactive "p")
1490 (unless arg
1491 (setq arg 1))
1492 (when (save-excursion (beginning-of-line)
1493 (looking-at (wesnoth-element-closing)))
1494 (wesnoth-jump-to-matching)
1495 (setq arg (1- arg)))
1496 (let ((revert-target (point)))
1497 (while (> arg 0)
1498 (beginning-of-line)
1499 (unless (looking-at (wesnoth-element-opening))
1500 (wesnoth-jump-to-matching))
1501 (if (and (search-backward-regexp (wesnoth-element) (point-min) t)
1502 (save-excursion (beginning-of-line)
1503 (looking-at (wesnoth-element-closing))))
1504 (setq revert-target (point))
1505 (goto-char revert-target)
1506 (message "%s" "Beginning of block"))
1507 (setq arg (1- arg))))
1508 (when (looking-at (wesnoth-element-closing))
1509 (wesnoth-jump-to-matching)))
1511 (defun wesnoth-check-wml ()
1512 "Perform context-sensitive analysis of WML-code."
1513 (interactive)
1514 ;; Temporarily cache all tag-data.
1515 (setq wesnoth-tmp-tag-data (wesnoth-refresh-wml-data))
1516 (wesnoth-update-project-information)
1517 (if (fboundp 'delete-overlay)
1518 (dolist (overlay (overlays-in (point-min) (point-max)))
1519 (if (eq 'wesnoth-warning-face (overlay-get overlay 'face))
1520 (delete-overlay overlay)))
1521 (setq wesnoth-warning-markers nil))
1522 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
1523 (error "WML data not available; unable to generate report"))
1524 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1525 (let ((unmatched '())
1526 (outbuf (and (interactive-p) (get-buffer-create "*WML*")))
1527 (last-match-pos 1)
1528 (details nil)
1529 (foreach '()))
1530 (save-excursion
1531 (set-buffer outbuf)
1532 (let ((buffer (buffer-name))
1533 (buffer-read-only nil))
1534 (erase-buffer)
1535 (insert (format "Checking %s...\n" buffer))
1536 (message (format "Checking %s..." buffer))))
1537 (save-excursion
1538 (goto-char (point-min))
1539 (while (setq details (wesnoth-find-next
1540 '(tag-opening tag-closing preprocessor attribute
1541 macro)))
1542 (save-excursion
1543 (goto-char (match-beginning 0))
1544 (cond ((nth 3 (parse-partial-sexp last-match-pos (point)))
1545 nil)
1546 ((eq (car details) 'macro)
1547 (dolist (macro (save-match-data
1548 (wesnoth-extract-macro-details
1549 (match-string-no-properties 0))))
1550 (unless (assoc macro
1551 (wesnoth-merge-macro-data
1552 wesnoth-macro-data
1553 (wesnoth-macro-additions)
1554 wesnoth-local-macro-data
1555 (wesnoth-macro-arguments)))
1556 (wesnoth-check-process "Unknown macro: '%s'"
1557 macro)))
1558 (save-match-data
1559 (when
1560 (looking-at
1561 "{\\(FOREACH\\|NEXT\\).*[\t ]+\
1562 \\(\\(?:\\w\\|_\\)+\\)}")
1563 (if (string= (match-string-no-properties 1) "FOREACH")
1564 (setq foreach
1565 (cons (match-string-no-properties 2) foreach))
1566 (if (string= (match-string-no-properties 1) "NEXT")
1567 (progn
1568 (unless (string= (car foreach)
1569 (match-string-no-properties 2))
1570 (wesnoth-check-process
1571 (concat "NEXT does not match corresponding "
1572 "FOREACH: '%s' found; '%s' expected.")
1573 (match-string-no-properties 2)
1574 (car foreach)))
1575 (setq foreach (cdr foreach))))))))
1576 ((looking-at "[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
1577 (unless (wesnoth-check-element-type 0)
1578 (wesnoth-check-process
1579 "Tag not available in this context: '%s'"
1580 (match-string-no-properties 1)))
1581 (setq unmatched (cons (match-string-no-properties 1)
1582 unmatched)))
1583 ((looking-at
1584 (concat "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\|#undef\\)"
1585 "\\( \\(\\w\\|_\\)+\\)*"))
1586 (unless (match-string-no-properties 2)
1587 (wesnoth-check-process
1588 (concat "Preprocessor statement has no argument: "
1589 (match-string-no-properties 1))))
1590 (unless (string= (match-string-no-properties 1) "#undef")
1591 (setq unmatched (cons (match-string-no-properties 1)
1592 unmatched))))
1593 ((looking-at wesnoth-preprocessor-closing-regexp)
1594 (when (and unmatched
1595 (not (string-match
1596 (cdr (assoc (match-string-no-properties 1)
1597 '(("enddef" . "#define")
1598 ("endif" . "#ifn?def"))))
1599 (car unmatched))))
1600 (wesnoth-check-process
1601 "Preprocessor statement does not nest correctly"))
1602 (setq unmatched (cdr unmatched)))
1603 ((looking-at "[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
1604 (unless (wesnoth-check-element-type 1)
1605 (wesnoth-check-process
1606 "Attribute not available in this context: '%s'"
1607 (match-string-no-properties 1)))
1608 (unless (match-string 3)
1609 (wesnoth-check-process
1610 "Attribute has no value")))
1611 ((looking-at "[\t ]*#else")
1612 (unless (string-match "ifn?def" (car unmatched))
1613 (if (string= (car unmatched) "#define")
1614 (wesnoth-check-process "Expecting: '%s'"
1615 (car unmatched))
1616 (wesnoth-check-process "Expecting: '[/%s]'"
1617 (car unmatched)))))
1618 ((looking-at "[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]")
1619 (when (and unmatched
1620 (not (string= (match-string-no-properties 1)
1621 (car unmatched))))
1622 (wesnoth-check-process
1623 "Expecting '%s'"
1624 (or (cdr (assoc (car unmatched)
1625 '(("#define" . "#enddef")
1626 ("#ifdef" . "#endif")
1627 ("#ifndef" . "#endif"))))
1628 (concat "[/" (car unmatched) "]"))))
1629 (setq unmatched (cdr unmatched)
1630 last-match-pos (point))))))
1631 (when foreach
1632 (dolist (var foreach)
1633 (wesnoth-check-process "Unmatched FOREACH: '%s'" var)))
1634 (when unmatched
1635 (dolist (element unmatched)
1636 (wesnoth-check-process "Unmatched element: '%s'" element))))
1637 (save-excursion
1638 (setq wesnoth-define-blocks nil
1639 wesnoth-tmp-tag-data nil)
1640 (set-buffer outbuf)
1641 (toggle-read-only t)
1642 (let ((buffer (buffer-name))
1643 (buffer-read-only nil))
1644 (display-buffer outbuf t)
1645 (let ((warnings (- (wesnoth-line-number-at-pos
1646 (save-excursion (goto-char (point-max)))) 2)))
1647 (insert (format (concat "\nCheck complete. %d warning"
1648 (if (= warnings 1) "." "s.")) warnings)))
1649 (message (format "Checking %s...done" buffer))))))
1652 ;;; wesnoth-mode
1653 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
1654 "Major mode for editing WML."
1655 (kill-all-local-variables)
1656 (use-local-map wesnoth-mode-map)
1657 (setq major-mode 'wesnoth-mode)
1658 (setq mode-name "WML")
1659 (set-syntax-table wesnoth-syntax-table)
1660 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
1661 (set (make-local-variable 'comment-start) "#")
1662 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
1663 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
1664 (set (make-local-variable 'wesnoth-warning-markers) '())
1665 (set (make-local-variable 'font-lock-defaults)
1666 '(wesnoth-font-lock-keywords
1667 nil t nil nil
1668 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
1669 (setq indent-tabs-mode nil)
1670 (easy-menu-add wesnoth-menu wesnoth-mode-map)
1671 (wesnoth-refresh-wml-data)
1672 (wesnoth-update-project-information)
1673 (run-hooks 'wesnoth-mode-hook))
1675 (provide 'wesnoth-mode)
1677 ;;; wesnoth-mode.el ends here