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