* wesnoth-update.el (wesnoth-handle-file): Ignore file if doesn't exist.
[wesnoth-mode.git] / wesnoth-mode.el
blob1690b71090619251dcdcddf0093b7714cda36aa3
1 ;;; wesnoth-mode.el --- A major mode for editing WML.
2 ;; Copyright (C) 2006, 2007, 2008 Chris Mann
4 ;; This file is part of wesnoth-mode.
6 ;; This program is free software; you can redistribute it and/or
7 ;; modify it under the terms of the GNU General Public License as
8 ;; published by the Free Software Foundation; either version 2 of the
9 ;; License, or (at your option) any later version.
11 ;; This program is distributed in the hope that it will be useful, but
12 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
13 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 ;; General Public License for more details.
16 ;; You should have received a copy of the GNU General Public License
17 ;; along with this program; see the file COPYING. If not, write to the
18 ;; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
19 ;; MA 02139, USA.
21 ;;; Description:
22 ;; wesnoth-mode is a major mode for Emacs which assists in the editing
23 ;; of Wesnoth Markup Language (WML) files. Currently, this mode
24 ;; features syntax highlighting support, automatic indentation,
25 ;; tag-completion and preliminary support for syntax 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.0
37 ;; * WML checking is now context sensitive; checks attributes and macros.
38 ;; * WML checks are now always performed on the entire buffer, with results
39 ;; displayed in a temporary buffer.
40 ;; * Context-sensitive completion for attributes and tags.
41 ;; * Completion for built-in and project-specific macros.
42 ;; * Changed the following bindings:
43 ;; `wesnoth-insert-tag' - C-c e -> C-c t
44 ;; `wesnoth-jump-to-matching' - C-c m -> C-c o
45 ;; `wesnoth-check-structure' -> `wesnoth-check-wml' - C-c c
46 ;; * Added the following bindings:
47 ;; `wesnoth-complete-attribute' - C-c a
48 ;; `wesnoth-complete-macro' - C-c m
49 ;; `wesnoth-complete-tag' - C-c t
50 ;; * Removed the following bindings:
51 ;; `wesnoth-check-tag-names' - C-c n
52 ;; * Removed `wesnoth-check-tag-names'. Replaced by `wesnoth-check-wml'.
53 ;; * Completion for an incomplete attribute, tag, or macro at point is
54 ;; attempted via TAB.
55 ;; 1.2.5
56 ;; * Fixed support for GNU Emacs 21.
57 ;; * Added several new tags to `wesnoth-tags-list'.
58 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
59 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
60 ;; how many blocks to wrap across instead of a region.
61 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
62 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
63 ;; causing tags not to be inserted in the correct position.
64 ;; * Fixed highlighting of array indexes as tags.
65 ;; 1.2.4
66 ;; * Improved syntax-highlighting for macro calls.
67 ;; * Underscore is now treated as whitespace.
68 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
69 ;; * Point is now placed at the first non-whitespace character of the line,
70 ;; instead of the last.
71 ;; * Corrected minor indentation bugs.
72 ;; * Indenting across large regions is now much more efficient.
73 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
74 ;; applied.
75 ;; 1.2.3
76 ;; * Now compatible with GNU Emacs 21.4.
77 ;; * Added support for several new tags.
78 ;; * Added menu entry for wesnoth-mode.
79 ;; * Significant speed increase to indentation.
80 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
81 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
82 ;; has been removed.
83 ;; * Trailing whitespace is no longer created when creating a second
84 ;; consecutive newline.
85 ;; * Spurious newlines are no longer created when inserting a tag elements
86 ;; around a region.
87 ;; 1.2.2
88 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
89 ;; `wesnoth-element', `wesnoth-element-opening',
90 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
91 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
92 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
93 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
94 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
95 ;; * Fixed a bug in indentation where content was needed between elements pairs
96 ;; for indentation to work.
97 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
98 ;; `wesnoth-auto-indent-flag'.
99 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
100 ;; * Added indentation styles: `wesnoth-indent-default',
101 ;; `wesnoth-indent-withtags' which implement a a similar indentation
102 ;; style to the existing styles, however all preprocessor statements are
103 ;; indented to the first column.
104 ;; * Added support for several new tags.
105 ;; * Modified `wesnoth-newline' to behave more consistently.
106 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
107 ;; now leaves point at the beginning (when moving backward) or end (when
108 ;; moving forward) of the match.
109 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
110 ;; will now work on preprocessor statements. Will now warn if jump
111 ;; destination may not be correct (due to errors in WML structure).
112 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
113 ;; * `wesnoth-check-structure' can now be applied over an active region and
114 ;; now checks preprocessor statements for correct nesting.
115 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
116 ;; perform indentation by providing a prefix argument.
117 ;; * Indentation styles now leave point at the first non-whitespace character
118 ;; of the line.
119 ;; * `wesnoth-check-tag-names' now reports on success.
120 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
121 ;; * `outline-minor-mode' now works on macro definitions.
122 ;; 1.2.1
123 ;; * Base indent now defaults to 4.
124 ;; * Added support for #ifndef.
126 ;;; Code:
127 (require 'cl)
128 (require 'wesnoth-wml-data)
129 (require 'wesnoth-update)
131 (defconst wesnoth-mode-version "1.3.0-git"
132 "The current version of `wesnoth-mode'.")
134 (defgroup wesnoth-mode nil "Wesnoth-mode access"
135 :group 'languages
136 :prefix "wesnoth-")
138 (defcustom wesnoth-auto-indent-flag t
139 "Non-nil means indent the current line upon creating a newline."
140 :type 'boolean
141 :group 'wesnoth-mode)
143 (defcustom wesnoth-indent-savefile t
144 "Non-nil means to use the current indentation conventions.
145 If nil, use the old convention for indentation.
146 The current convention is all attributes are indented a level deeper
147 than their parent; in the past attributes were indented to the same
148 level as their parent.")
150 (defcustom wesnoth-base-indent 4
151 "The number of columns to indent WML."
152 :type 'integer
153 :group 'wesnoth-mode)
155 (defconst wesnoth-preprocessor-regexp
156 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def\\)"
157 "Regular expression to match all preprocessor statements.")
159 (defconst wesnoth-preprocessor-opening-regexp
160 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
161 "Regular expression to match \"opening\" preprocessor statements.")
163 (defconst wesnoth-preprocessor-closing-regexp
164 "[\t ]*#\\(e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\)"
165 "Regular expression to match \"closing\" preprocessor statements.")
167 (defvar wesnoth-define-blocks '()
168 "Cache of all toplevel #define and #enddef pairs.")
170 (defvar wesnoth-mode-hook nil)
172 (defvar wesnoth-mode-map
173 (let ((map (make-sparse-keymap)))
174 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
175 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
176 (define-key map (kbd "C-m") 'wesnoth-newline)
177 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
178 (define-key map (kbd "C-c c") 'wesnoth-check-wml)
179 (define-key map (kbd "C-c C-c") 'wesnoth-check-wml)
180 (define-key map (kbd "C-c a") 'wesnoth-complete-attribute)
181 (define-key map (kbd "C-c C-a") 'wesnoth-complete-attribute)
182 (define-key map (kbd "C-c t") 'wesnoth-complete-tag)
183 (define-key map (kbd "C-c C-t") 'wesnoth-complete-tag)
184 (define-key map (kbd "M-TAB") 'wesnoth-insert-tag)
185 (define-key map (kbd "C-c m") 'wesnoth-complete-macro)
186 (define-key map (kbd "C-c C-m") 'wesnoth-complete-macro)
187 (define-key map (kbd "C-c o") 'wesnoth-jump-to-matching)
188 (define-key map (kbd "C-c C-o") 'wesnoth-jump-to-matching)
189 (define-key map (kbd "C-c /") 'wesnoth-insert-missing-closing)
190 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
191 (define-key map (kbd "TAB") 'wesnoth-indent-or-complete)
192 (define-key map [menu-bar wesnoth]
193 (cons "WML" (make-sparse-keymap "WML")))
194 (define-key map [menu-bar wesnoth check-structure]
195 '("Check WML" . wesnoth-check-wml))
196 (define-key map [menu-bar wesnoth insert-tag]
197 '("Insert Tag" . wesnoth-insert-tag))
198 (define-key map [menu-bar wesnoth complete-attribute]
199 '("Insert Attribute" . wesnoth-complete-attribute))
200 (define-key map [menu-bar wesnoth complete-macro]
201 '("Insert Macro" . wesnoth-complete-macro))
202 (define-key map [menu-bar wesnoth jump-to-matching]
203 '("Jump to Matching" . wesnoth-jump-to-matching))
204 (define-key map [menu-bar wesnoth insert-missing-closing]
205 '("Insert Missing Tag" . wesnoth-insert-missing-closing))
206 map)
207 "Keymap used in wesnoth mode.")
209 (defvar wesnoth-syntax-table
210 (let ((wesnoth-syntax-table (make-syntax-table)))
211 (modify-syntax-entry ?= "." wesnoth-syntax-table)
212 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
213 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
214 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
215 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
216 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
217 wesnoth-syntax-table)
218 "Syntax table for `wesnoth-mode'.")
220 ;; Prevents automatic syntax-highlighting of elements which might be
221 ;; pre-processor statements.
222 (defvar wesnoth-syntactic-keywords
223 (list
224 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
225 '("\\(#[\t ]*.*$\\)" 1 "<"))
226 "Highlighting syntactic keywords within `wesnoth-mode'.")
228 (defun wesnoth-preprocessor-best-face ()
229 "Use `font-lock-preprocessor-face' when available."
230 (when global-font-lock-mode
231 (if (boundp 'font-lock-preprocessor-face)
232 (copy-face 'font-lock-preprocessor-face 'wesnoth-preprocessor-face)
233 (copy-face 'font-lock-keyword-face 'wesnoth-preprocessor-face))))
235 (defvar wesnoth-font-lock-keywords
236 (list
237 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . 'wesnoth-preprocessor-face)
238 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
239 2 font-lock-function-name-face)
240 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
241 'wesnoth-preprocessor-face)
242 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)"
243 (1 font-lock-function-name-face))
244 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)"
245 (1 font-lock-function-name-face))
246 '("}" . font-lock-function-name-face)
247 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face)
248 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
249 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
250 1 font-lock-variable-name-face))
251 "Syntax highlighting for `wesnoth-mode'.")
253 (defconst wesnoth-element-closing "^[\t ]*\\(\\[/\\|#enddef\\)"
254 "String to use for a closing element.")
256 (defconst wesnoth-element-opening "^[\t ]*\\(\\[[^/]\\|#define\\)"
257 "String to use for an opening element.")
259 (defconst wesnoth-element "^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
260 "String to use for an opening or closing element.")
262 ;;; Insertion and completion
263 (defun wesnoth-parent-tag ()
264 "Return the name of the parent tag, nil otherwise."
265 (save-excursion
266 (let ((parent (when (and (wesnoth-wml-start-pos)
267 (> (point) (wesnoth-wml-start-pos)))
268 (wesnoth-check-structure (wesnoth-wml-start-pos)
269 (point)))))
270 (when parent
271 (if (string-match wesnoth-preprocessor-closing-regexp parent)
273 (subseq parent 2 (1- (length parent))))))))
275 (defun wesnoth-indent-or-complete ()
276 "Indent or complete the line at point, depending on context."
277 (interactive)
278 (let ((target nil))
279 (save-excursion
280 (back-to-indentation)
281 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
282 (wesnoth-complete-attribute t))
283 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
284 (wesnoth-complete-tag t))
285 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
286 (wesnoth-complete-macro t))
287 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
288 (delete-region (point) (progn (end-of-line) (point)))
289 (wesnoth-insert-missing-closing)
290 (end-of-line))
292 (wesnoth-indent)))
293 (setq target (point)))
294 (goto-char target)))
296 (defun wesnoth-complete-macro (&optional completep)
297 "Complete and insert the macro at point.
298 If COMPLETEP is non-nil, attempt to complete the macro at point."
299 (interactive)
300 (let* ((macro-information (append wesnoth-macro-data
301 wesnoth-local-macro-data))
302 (completions (wesnoth-emacs-completion-formats
303 (mapcar 'car macro-information)))
304 (partial (when completep
305 (save-excursion
306 (back-to-indentation)
307 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
308 (match-string 1)))))
309 (macro (or (wesnoth-element-completion completions "Macro: ")
310 partial))
311 (args (second (find macro macro-information
312 :key 'car :test 'string=))))
313 (when macro
314 (if partial
315 (progn
316 (delete-region (progn (back-to-indentation) (point))
317 (progn (end-of-line) (point)))
318 (insert "{" macro (if args " }" "}")))
319 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
320 (save-excursion
321 (wesnoth-indent))
322 (when args
323 (forward-char -1)))))
325 (defun wesnoth-complete-attribute (&optional completep)
326 "Insert the attribute at point.
327 If COMPLETEP is non-nil, attempt to complete the attribute at point."
328 (interactive)
329 (let* ((completions (wesnoth-build-completion 2))
330 (partial (when completep
331 (save-excursion
332 (back-to-indentation)
333 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
334 (match-string 1)))))
335 (attribute (or (wesnoth-element-completion completions "Attribute: ")
336 partial)))
337 (when attribute
338 (if (and partial completep)
339 (progn
340 (delete-region (progn (back-to-indentation) (point))
341 (progn (end-of-line) (point)))
342 (insert attribute "="))
343 (wesnoth-insert-element-separately attribute
344 (if (string-match "=" attribute)
346 "=")))
347 (save-excursion
348 (wesnoth-indent)))))
350 (defun wesnoth-complete-tag (&optional completep)
351 "Complete and insert the tag at point.
352 If COMPLETEP is non-nil, attempt to complete tag at point."
353 (interactive)
354 (let* ((completions (wesnoth-build-completion 1))
355 (partial (when completep
356 (save-excursion
357 (back-to-indentation)
358 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
359 (match-string 1)))))
360 (tag (or (wesnoth-element-completion completions "Tag: ")
361 partial)))
362 (let ((closed-p nil))
363 (save-excursion
364 (wesnoth-jump-to-matching)
365 (back-to-indentation)
366 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
367 (string= tag (match-string 1)))
368 (setq closed-p t)))
369 (when completep
370 (delete-region (progn (back-to-indentation) (point))
371 (progn (end-of-line) (point))))
372 (if (and closed-p completep)
373 (progn
374 (wesnoth-insert-and-indent "[" tag "]")
375 (end-of-line))
376 (wesnoth-insert-tag nil tag)))))
378 (defmacro wesnoth-element-completion (completions prompt)
379 "Process completion of COMPLETIONS, displaying PROMPT."
380 (let ((partial (gensym))
381 (element (gensym)))
382 `(let* ((,partial (match-string-no-properties 1))
383 (,element (when ,partial (try-completion ,partial ,completions))))
384 (cond ((eq ,element t)
385 (setq ,element nil))
386 ((null ,element)
387 (setq ,element
388 (completing-read ,prompt ,completions)))
389 ((not (member ,element ,completions))
390 (setq ,element
391 (completing-read ,prompt ,completions
392 nil nil ,partial))))
393 ,element)))
395 (defun wesnoth-build-completion (position)
396 "Create a new list for tag completion if necessary.
397 Rebuilding list is required for versions of GNU Emacs earlier
398 than 22. POSITION is the argument passed to `nth' for
399 `wesnoth-tag-data'."
400 (interactive "P")
401 (let* ((parent (wesnoth-parent-tag))
402 (candidates
403 (if (or (stringp parent) (null parent))
404 (nth position (find (wesnoth-parent-tag) wesnoth-tag-data
405 :key 'car :test 'string=))
406 (mapcar 'car wesnoth-tag-data))))
407 (wesnoth-emacs-completion-formats candidates)))
409 (defun wesnoth-emacs-completion-formats (candidates)
410 "Return the completions in the correct format for `emacs-major-version'.
411 CANDIDATES is a list of all possible completions."
412 (if (> emacs-major-version 21)
413 candidates
414 (let ((tags '())
415 (iter 0))
416 (dolist (tag candidates)
417 (setq iter (1+ iter))
418 (setq tags (append tags (list (cons tag iter)))))
419 tags)))
421 (defun wesnoth-insert-tag (&optional elements tagname)
422 "Insert the specified opening tag and it's matching closing tag.
423 Both the opening and closing tags will be placed on their own
424 lines with point positioned between them. Completion of tags at
425 the prompt uses `wesnoth-tags-list'.
427 ELEMENTS is specifies the number of following blocks which the
428 tag should wrap around.
430 TAGNAME is the name of the tag to be inserted."
431 (interactive "Ps")
432 (unless tagname
433 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 1))))
434 (or elements (setq elements 0))
435 (let ((depth 0)
436 (start (save-excursion (forward-line -1) (point)))
437 (end (unless (= elements 0)
438 (wesnoth-nth-pair-position elements))))
439 (wesnoth-insert-element-separately "[" tagname "]")
440 (save-excursion
441 (if end
442 (goto-char (marker-position end))
443 (newline 2))
444 (wesnoth-insert-element-separately "[/" tagname "]")
445 (indent-region start (point) nil))
446 (unless end
447 (forward-line 1)))
448 (wesnoth-indent))
450 (defun wesnoth-nth-pair-position (count)
451 "Return `point' after COUNT number of matching element pairs.
452 COUNT is a positive number representing the number of balanced
453 pairs to move across.
454 `point' is returned as a marker object."
455 (save-excursion
456 (while (> count 0)
457 ;; Currently looking-at target tag. Stop here to avoid
458 ;; incorrect nesting.
459 (unless (wesnoth-search-for-matching-tag
460 'search-forward-regexp wesnoth-element-closing 'point-max)
461 (setq count 0)
462 (search-backward-regexp wesnoth-element-closing (point-min) t))
463 (and (> (decf count) 0) (forward-line 1)))
464 (end-of-line)
465 (point-marker)))
467 (defun wesnoth-insert-element-separately (&rest strings)
468 "Concatenate STRINGS and insert them on a line of their own."
469 (let ((create-newline (save-excursion
470 (beginning-of-line)
471 (if (looking-at "^[\t ]*$") nil t))))
472 (when create-newline
473 (if (> (point) (save-excursion (back-to-indentation) (point)))
474 (progn
475 (end-of-line)
476 (newline))
477 (beginning-of-line)
478 (open-line 1)))
479 (insert (apply 'concat strings))))
481 (defun wesnoth-insert-missing-closing (&optional start end)
482 "Insert the next expected closing element at point.
484 START and END define the region to check for missing closing
485 elements. If function `transient-mark-mode' is enabled, the region
486 specified will be used as START and END. Otherwise, START and
487 END will be the minimum and maximum positions of the buffer,
488 respectively."
489 (interactive)
490 (if (and transient-mark-mode mark-active)
491 (setq start (region-beginning)
492 end (copy-marker (region-end)))
493 (setq start (point-min)
494 end (point-max)))
495 (let ((element (wesnoth-check-structure start end)))
496 (if (not element)
497 (error "%s" "Unable to find element to insert")
498 (when (string= element "Unexpected end of file")
499 (error "%s" element))
500 (wesnoth-insert-element-separately element)))
501 (wesnoth-indent)
502 (end-of-line))
504 (defun wesnoth-insert-and-indent (&rest args)
505 "Concatenate and insert the given string(s) before indenting.
507 ARGS is a list of strings to be inserted."
508 (insert (apply 'concat args))
509 (wesnoth-indent))
511 (defun wesnoth-newline (&optional indent)
512 "Indent both the current line and the newline created.
513 If `wesnoth-auto-indent-flag' is nil, indentation will not be
514 performed. Indentation can be forced by setting INDENT to
515 non-nil."
516 (interactive)
517 (save-excursion
518 (when (and (or wesnoth-auto-indent-flag indent)
519 (not (looking-at "^[\t ]*$")))
520 (wesnoth-indent)))
521 (newline))
523 ;;; Movement
524 (defmacro wesnoth-navigate-element (repeat search-function bound)
525 "Move point to the tag in the given direction REPEAT times.
527 SEARCH-FUNCTION is the symbol of the function for searching in
528 the required direction, with BOUND marking the furthest point to
529 search."
530 `(progn
531 (or ,repeat (setq ,repeat 1))
532 (while (> ,repeat 0)
533 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
534 (funcall ,search-function wesnoth-element-opening ,bound t)
535 (back-to-indentation)
536 (decf ,repeat))))
538 (defun wesnoth-forward-element (repeat)
539 "Move point to the end of the next tag.
540 REPEAT is an optional numeric argument. If REPEAT is non-nil,
541 jump forward the specified number of tags."
542 (interactive "p")
543 (if (< repeat 0)
544 (wesnoth-backward-element (abs repeat))
545 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
547 (defun wesnoth-backward-element (repeat)
548 "Move point to the beginning of the previous tag.
549 REPEAT is an optional numeric argument. If REPEAT is non-nil,
550 jump backward the specified number of tags."
551 (interactive "p")
552 (if (< repeat 0)
553 (wesnoth-forward-element (abs repeat))
554 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
556 (defmacro wesnoth-search-for-matching-tag (search-function search-string bound)
557 "Search for the matching tag for the current line.
559 SEARCH-FUNCTION is the name of the function used to perform the search.
560 SEARCH-STRING is a string representing the matching tag type.
561 BOUND is the bound to be passed to the search function."
562 `(let ((depth 1))
563 (unless (looking-at ,search-string)
564 (unless (> (point) (funcall ,bound)) (end-of-line))
565 (while (and (> depth 0)
566 (funcall ,search-function wesnoth-element
567 (funcall ,bound) t))
568 (if (string-match ,search-string (match-string 0))
569 (decf depth)
570 (incf depth)))
571 t)))
573 (defun wesnoth-jump-to-matching ()
574 "Jump point to the matching opening/closing tag."
575 (interactive)
576 (beginning-of-line)
577 (if (looking-at wesnoth-element-opening)
578 (wesnoth-search-for-matching-tag
579 'search-forward-regexp wesnoth-element-closing 'point-max)
580 (wesnoth-search-for-matching-tag
581 'search-backward-regexp wesnoth-element-opening 'wesnoth-wml-start-pos))
582 (back-to-indentation))
584 (defun wesnoth-wml-start-pos ()
585 "Determine the position of `point' relative to where the actual WML begins.
586 Return the likely starting position of the WML if it is found.
587 Otherwise return nil."
588 (save-excursion
589 (goto-char (point-min))
590 (when (search-forward-regexp wesnoth-element (point-max) t)
591 (beginning-of-line)
592 (point))))
594 (defun first-column-indent-p (point)
595 "Return non-nil if the current line should not be indented.
597 POINT is the position in the buffer to check.
598 CONTEXT represents the type of element which precedes the current element."
599 (or (not (wesnoth-wml-start-pos))
600 (<= (point) (wesnoth-wml-start-pos))
601 (nth 3 (parse-partial-sexp (point-min) point))
602 (looking-at wesnoth-preprocessor-regexp)))
604 (defun wesnoth-indent ()
605 "Indent the current line as WML."
606 (beginning-of-line)
607 (let ((cur-indent 0))
608 (unless (first-column-indent-p (point))
609 (multiple-value-bind (context ref-indent)
610 (wesnoth-determine-context (point))
611 (cond
612 ((eq context 'opening)
613 (if (or (and wesnoth-indent-savefile
614 (not (looking-at wesnoth-element-closing)))
615 (looking-at wesnoth-element-opening))
616 (setq cur-indent (+ ref-indent wesnoth-base-indent))
617 (setq cur-indent ref-indent)))
618 ((eq context 'closing)
619 (if (or (looking-at "^[\t ]*\\[/")
620 (and (not wesnoth-indent-savefile)
621 (not (looking-at wesnoth-element-opening))))
622 (setq cur-indent (- ref-indent wesnoth-base-indent))
623 (setq cur-indent ref-indent))))))
624 (indent-line-to (max cur-indent 0))))
626 (defun wesnoth-within-define (position)
627 "Determine whether point is currently inside a #define block.
628 POSITION is the initial cursor position."
629 (let ((depth 0))
630 (dolist (element (or wesnoth-define-blocks
631 (wesnoth-find-macro-definitions)))
632 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
633 (list position)) '>)) position)
634 (setq depth (max (car element) depth))))
635 depth))
637 (defun wesnoth-find-macro-definitions ()
638 "Return information regarding positioning of macro definitions."
639 (save-excursion
640 (goto-char (point-min))
641 (let ((depth 0)
642 openings cache)
643 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t)
644 (and (string= (match-string 1) "#define") (beginning-of-line))
645 (setq depth
646 (if (string= (match-string 1) "#define")
647 (progn
648 (add-to-list 'openings (point-marker))
649 (1+ depth))
650 (add-to-list 'cache
651 (list depth (list (car openings) (point-marker))))
652 (setq openings (cdr openings))
653 (1- depth)))
654 (end-of-line))
655 cache)))
657 (defun wesnoth-indent-region (start end)
658 "Indent the region from START to END.
660 Creates and destroys a cache of macro definition details as necessary."
661 (interactive "r")
662 (unwind-protect
663 (save-excursion
664 (goto-char end)
665 (setq end (point-marker))
666 (goto-char start)
667 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
668 (or (bolp) (forward-line 1))
669 (while (< (point) end)
670 (if (looking-at "^[\t ]*$")
671 (indent-line-to 0)
672 (funcall indent-line-function))
673 (forward-line 1)))
674 (setq wesnoth-define-blocks nil)))
676 (defun wesnoth-determine-context (position)
677 "Determine the type of the last relevant element.
679 POSITION is the buffer position of the element for which to
680 determine the context."
681 (save-excursion
682 (search-backward-regexp wesnoth-element (wesnoth-wml-start-pos) t)
683 (let ((match (or (match-string 1) ""))
684 (depth (wesnoth-within-define position)))
685 (while (and (> (wesnoth-within-define (point)) depth)
686 (not (= (point) (wesnoth-wml-start-pos))))
687 (search-backward-regexp wesnoth-element
688 (wesnoth-wml-start-pos) t)
689 (setq match (match-string 1)))
690 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth 0)
691 (string-match "#define" match))
692 ;; Found nothing of use; reset match and assume top-level tag.
693 (setq match ""))
694 (cond
695 ((string-match "\\[/\\|#enddef" match)
696 (values 'closing (current-indentation)))
697 ((string-match "\\[[^/]?\\|#define" match)
698 (values 'opening (current-indentation)))))))
700 (defun wesnoth-newline-and-indent (&optional indent)
701 "Indent both the current line and the newline created.
702 If `wesnoth-auto-indent-flag' is nil, indentation will not be
703 performed.
705 If the optional argument, INDENT is non-nil, force indentation to
706 be performed."
707 (interactive)
708 (wesnoth-newline)
709 (when (or wesnoth-auto-indent-flag indent)
710 (wesnoth-indent)))
712 ;;; WML checks
713 (defun wesnoth-check-element-type (position last-tag)
714 "Determine the context of the element.
715 POSITION is the position of the element in the list.
716 LAST-TAG is the parent element."
717 (if (or (string= last-tag "#define")
718 (string= last-tag "#ifndef")
719 (string= last-tag "#ifdef"))
720 (member (match-string-no-properties 1)
721 (mapcar 'car wesnoth-tag-data))
722 (member last-tag
723 (mapcar 'car
724 (remove-if-not
725 (lambda (list)
726 (member (match-string-no-properties 1)
727 list))
728 wesnoth-tag-data :key position)))))
730 (defun wesnoth-check-output (buffer format-string &rest args)
731 "Output the string as passed to `format'.
732 BUFFER is the buffer to output the result.
733 FORMAT-STRING is the string as the first argument of `format'.
734 ARGS is any additional data required by `format' to handle FORMAT-STRING."
735 (save-excursion
736 (let ((lnap (line-number-at-pos)))
737 (set-buffer buffer)
738 (insert (apply 'format (concat "%d: " format-string "\n")
739 lnap args)))))
741 (defun wesnoth-check-wml ()
742 "Perform context-sensitive analysis of WML-code."
743 (interactive)
744 (wesnoth-update-project-information)
745 (let ((unmatched-tag-list '())
746 (outbuf (get-buffer-create "*WML*")))
747 (save-excursion
748 (let ((buffer (buffer-name)))
749 (set-buffer outbuf)
750 (erase-buffer)
751 (message (format "Checking %s..." buffer))))
752 (save-excursion
753 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
754 (while (search-forward-regexp
755 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
756 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
757 wesnoth-preprocessor-regexp "\\)")
758 (point-max) t)
759 (beginning-of-line)
760 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
761 (unless (wesnoth-check-element-type 'second
762 (car unmatched-tag-list))
763 (wesnoth-check-output outbuf
764 "Tag not available in this context: %s"
765 (match-string-no-properties 1)))
766 (setq unmatched-tag-list (cons
767 (match-string-no-properties 1)
768 unmatched-tag-list)))
769 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
770 (setq unmatched-tag-list (cons (match-string-no-properties 1)
771 unmatched-tag-list)))
772 ((looking-at wesnoth-preprocessor-closing-regexp)
773 (unless (string= (car unmatched-tag-list)
774 (second (find (match-string-no-properties 1)
775 '(("enddef" "#define")
776 ("ifdef" "#endif")
777 ("ifndef" "#endif"))
778 :key 'car :test 'string=)))
779 (wesnoth-check-output outbuf
780 "Preprocessor statement does not nest correctly"))
781 (setq unmatched-tag-list (cdr unmatched-tag-list)))
782 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
783 (unless (wesnoth-check-element-type 'third
784 (car unmatched-tag-list))
785 (wesnoth-check-output
786 outbuf "Attribute not available in this context: %s"
787 (match-string-no-properties 1)))
788 (unless (match-string 3)
789 (wesnoth-check-output
790 outbuf "Attribute has no value")))
791 ((looking-at "^[\t ]*#else")
792 (unless (string-match "ifn?def" (car unmatched-tag-list))
793 (if (string= (car unmatched-tag-list) "#define")
794 (wesnoth-check-output outbuf "Expecting: %s"
795 (car unmatched-tag-list))
796 (wesnoth-check-output outbuf "Expecting: [/%s]"
797 (car unmatched-tag-list)))))
798 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
799 (unless (find (match-string-no-properties 1)
800 (append wesnoth-local-macro-data
801 wesnoth-macro-data)
802 :test 'string= :key 'car)
803 (wesnoth-check-output outbuf "Unknown macro definition: {%s}"
804 (match-string-no-properties 1))))
805 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
806 (unless (string= (match-string-no-properties 1)
807 (car unmatched-tag-list))
808 (if (string= "#" (subseq (car unmatched-tag-list) 0 1))
809 (wesnoth-check-output outbuf "Expecting: #%s"
810 (car
811 (find (car unmatched-tag-list)
812 '(("enddef" "#define")
813 ("ifdef" "#endif")
814 ("ifndef" "#endif"))
815 :key 'second :test 'string=)))
816 (wesnoth-check-output outbuf "Expecting: [/%s]"
817 (car unmatched-tag-list))))
818 (setq unmatched-tag-list (cdr unmatched-tag-list))))
819 (end-of-line))
820 (if unmatched-tag-list
821 (dolist (tag unmatched-tag-list)
822 (wesnoth-check-output outbuf "Unmatched tag: %s"
823 (car unmatched-tag-list)))))
824 (save-excursion
825 (let ((buffer (buffer-name)))
826 (set-buffer outbuf)
827 (display-buffer outbuf t)
828 (message (format "Checking %s... done" buffer))))))
830 (defmacro wesnoth-element-requires (element requirement &optional pop)
831 "Process requirements for corresponding preprocessor elements.
832 ELEMENT is the current element being tested.
833 REQUIREMENT is the element required to exist for correct nesting.
834 POP is an optional argument indicating the element should be
835 removed from the unmatched-tag-list."
836 `(when (string= ,element (match-string-no-properties 1))
838 (if (string-match ,requirement (car unmatched-tag-list))
839 (progn
840 (and ,pop (setq unmatched-tag-list (cdr unmatched-tag-list)))
842 (setq error-position (point)))))
844 (defmacro wesnoth-structure-result (position element)
845 "Process results of the structure check.
846 POSITION is the error position or nil, if no error was found.
847 ELEMENT is the last unmatched element, or nil if all opening
848 elements have been matched."
849 `(let ((expected nil))
850 (when ,element
851 (cond ((string= ,element "define ") (setq expected "#enddef"))
852 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
853 (if (interactive-p)
854 (if (or ,element ,position)
855 (progn
856 (and ,position (goto-char ,position))
857 (message "Error: Expecting %s" (or expected
858 (concat "[/" ,element "]"))))
859 (message "%s" "Structure appears consistent."))
860 (when (or expected ,element)
861 (or expected (concat "[/" ,element "]"))))))
863 (defun wesnoth-check-structure (&optional start end)
864 "Check the buffer for correct nesting of elements.
865 If a problem is found in the structure, point will be placed at
866 the location which an element was expected and the expected
867 element will be displayed in the mini-buffer.
869 START and END define the region to be checked. If
870 function `transient-mark-mode' is enabled, the region specified will be
871 checked. Otherwise START and END will be the minimum and maximum
872 positions of the buffer, respectively."
873 (interactive)
874 (unless (or start end)
875 (if (and transient-mark-mode mark-active)
876 (setq start (region-beginning)
877 end (copy-marker (region-end)))
878 (setq start (point-min)
879 end (point-max))))
880 (let ((unmatched-tag-list '())
881 (error-position nil))
882 (save-excursion
883 (and start (goto-char start))
884 (while (and (search-forward-regexp
885 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
886 wesnoth-preprocessor-regexp "\\)") end t)
887 (not error-position))
888 (beginning-of-line)
889 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
890 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
891 (setq unmatched-tag-list (cons (match-string-no-properties 1)
892 unmatched-tag-list))
893 (cond
894 ((wesnoth-element-requires "#else" "ifn?def "))
895 ((wesnoth-element-requires "#endif" "ifn?def " t))
896 ((wesnoth-element-requires "#enddef" "define " t))
897 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
898 wesnoth-preprocessor-closing-regexp))
899 (if (string= (match-string-no-properties 1)
900 (car unmatched-tag-list))
901 (setq unmatched-tag-list (cdr unmatched-tag-list))
902 (setq error-position (point))))))
903 (end-of-line)))
904 (wesnoth-structure-result error-position (car unmatched-tag-list))))
906 ;;; wesnoth-mode
907 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
908 "Major mode for editing WML."
909 (wesnoth-preprocessor-best-face)
910 (set-syntax-table wesnoth-syntax-table)
911 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
912 (set (make-local-variable 'comment-start) "#")
913 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
914 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
915 (set (make-local-variable 'font-lock-defaults)
916 '(wesnoth-font-lock-keywords
917 nil t nil nil
918 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
919 (setq indent-tabs-mode nil)
920 (setq mode-name "WML")
921 (run-hooks 'wesnoth-mode-hook))
923 (provide 'wesnoth-mode)
925 ;;; wesnoth-mode.el ends here