* wesnoth-mode.el: Make wesnoth-update, wesnoth-wml-data non-essential.
[wesnoth-mode.git] / wesnoth-mode.el
blobf7c8b51967a314eaa56cb5efebc9d0a4f43e821f
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 ;; The following provide completion data, but otherwise are not strictly
129 ;; necessary.
130 (require 'wesnoth-wml-data nil t)
131 (require 'wesnoth-update nil t)
133 (defconst wesnoth-mode-version "1.3.0-git"
134 "The current version of `wesnoth-mode'.")
136 (defgroup wesnoth-mode nil "Wesnoth-mode access"
137 :group 'languages
138 :prefix "wesnoth-")
140 (defcustom wesnoth-auto-indent-flag t
141 "Non-nil means indent the current line upon creating a newline."
142 :type 'boolean
143 :group 'wesnoth-mode)
145 (defcustom wesnoth-indent-savefile t
146 "Non-nil means to use the current indentation conventions.
147 If nil, use the old convention for indentation.
148 The current convention is all attributes are indented a level deeper
149 than their parent; in the past attributes were indented to the same
150 level as their parent.")
152 (defcustom wesnoth-base-indent 4
153 "The number of columns to indent WML."
154 :type 'integer
155 :group 'wesnoth-mode)
157 (defconst wesnoth-preprocessor-regexp
158 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def\\)"
159 "Regular expression to match all preprocessor statements.")
161 (defconst wesnoth-preprocessor-opening-regexp
162 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
163 "Regular expression to match \"opening\" preprocessor statements.")
165 (defconst wesnoth-preprocessor-closing-regexp
166 "[\t ]*#\\(e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\)"
167 "Regular expression to match \"closing\" preprocessor statements.")
169 (defvar wesnoth-define-blocks '()
170 "Cache of all toplevel #define and #enddef pairs.")
172 (defvar wesnoth-mode-hook nil)
174 (defvar wesnoth-mode-map
175 (let ((map (make-sparse-keymap)))
176 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
177 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
178 (define-key map (kbd "C-m") 'wesnoth-newline)
179 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
180 (define-key map (kbd "C-c c") 'wesnoth-check-wml)
181 (define-key map (kbd "C-c C-c") 'wesnoth-check-wml)
182 (define-key map (kbd "C-c a") 'wesnoth-complete-attribute)
183 (define-key map (kbd "C-c C-a") 'wesnoth-complete-attribute)
184 (define-key map (kbd "C-c t") 'wesnoth-complete-tag)
185 (define-key map (kbd "C-c C-t") 'wesnoth-complete-tag)
186 (define-key map (kbd "M-TAB") 'wesnoth-insert-tag)
187 (define-key map (kbd "C-c m") 'wesnoth-complete-macro)
188 (define-key map (kbd "C-c C-m") 'wesnoth-complete-macro)
189 (define-key map (kbd "C-c o") 'wesnoth-jump-to-matching)
190 (define-key map (kbd "C-c C-o") 'wesnoth-jump-to-matching)
191 (define-key map (kbd "C-c /") 'wesnoth-insert-missing-closing)
192 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
193 (define-key map (kbd "TAB") 'wesnoth-indent-or-complete)
194 (define-key map [menu-bar wesnoth]
195 (cons "WML" (make-sparse-keymap "WML")))
196 (define-key map [menu-bar wesnoth check-structure]
197 '("Check WML" . wesnoth-check-wml))
198 (define-key map [menu-bar wesnoth insert-tag]
199 '("Insert Tag" . wesnoth-insert-tag))
200 (define-key map [menu-bar wesnoth complete-attribute]
201 '("Insert Attribute" . wesnoth-complete-attribute))
202 (define-key map [menu-bar wesnoth complete-macro]
203 '("Insert Macro" . wesnoth-complete-macro))
204 (define-key map [menu-bar wesnoth jump-to-matching]
205 '("Jump to Matching" . wesnoth-jump-to-matching))
206 (define-key map [menu-bar wesnoth insert-missing-closing]
207 '("Insert Missing Tag" . wesnoth-insert-missing-closing))
208 map)
209 "Keymap used in wesnoth mode.")
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 (defun wesnoth-preprocessor-best-face ()
231 "Use `font-lock-preprocessor-face' when available."
232 (when global-font-lock-mode
233 (if (boundp 'font-lock-preprocessor-face)
234 (copy-face 'font-lock-preprocessor-face 'wesnoth-preprocessor-face)
235 (copy-face 'font-lock-keyword-face 'wesnoth-preprocessor-face))))
237 (defvar wesnoth-font-lock-keywords
238 (list
239 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . 'wesnoth-preprocessor-face)
240 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
241 2 font-lock-function-name-face)
242 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
243 'wesnoth-preprocessor-face)
244 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)"
245 (1 font-lock-function-name-face))
246 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)"
247 (1 font-lock-function-name-face))
248 '("}" . font-lock-function-name-face)
249 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face)
250 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
251 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
252 1 font-lock-variable-name-face))
253 "Syntax highlighting for `wesnoth-mode'.")
255 (defconst wesnoth-element-closing "^[\t ]*\\(\\[/\\|#enddef\\)"
256 "String to use for a closing element.")
258 (defconst wesnoth-element-opening "^[\t ]*\\(\\[[^/]\\|#define\\)"
259 "String to use for an opening element.")
261 (defconst wesnoth-element "^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
262 "String to use for an opening or closing element.")
264 ;;; Insertion and completion
265 (defmacro wesnoth-element-completion (completions prompt)
266 "Process completion of COMPLETIONS, displaying PROMPT."
267 (let ((partial (gensym))
268 (element (gensym)))
269 `(let* ((,partial (match-string-no-properties 1))
270 (,element (when ,partial (try-completion ,partial ,completions))))
271 (cond ((eq ,element t)
272 (setq ,element nil))
273 ((null ,element)
274 (setq ,element
275 (completing-read ,prompt ,completions)))
276 ((not (member ,element ,completions))
277 (setq ,element
278 (completing-read ,prompt ,completions
279 nil nil ,partial))))
280 ,element)))
282 (defun wesnoth-parent-tag ()
283 "Return the name of the parent tag, nil otherwise."
284 (save-excursion
285 (let ((parent (when (and (wesnoth-wml-start-pos)
286 (> (point) (wesnoth-wml-start-pos)))
287 (wesnoth-check-structure (wesnoth-wml-start-pos)
288 (point)))))
289 (when parent
290 (if (string-match wesnoth-preprocessor-closing-regexp parent)
292 (subseq parent 2 (1- (length parent))))))))
294 (defmacro wesnoth-completion-available (list)
295 "Return symbol value of LIST when bound.
296 Used to support lack of completion data."
297 `(when (boundp ,list)
298 (symbol-value ,list)))
300 (defun wesnoth-indent-or-complete ()
301 "Indent or complete the line at point, depending on context."
302 (interactive)
303 (let ((target nil))
304 (save-excursion
305 (back-to-indentation)
306 (cond ((looking-at "\\(\\(\\w\\|_\\)+\\)[\t ]*$")
307 (wesnoth-complete-attribute t))
308 ((looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$")
309 (wesnoth-complete-tag t))
310 ((looking-at "{\\(\\(\\w\\|_\\)*\\)[\t ]*$")
311 (wesnoth-complete-macro t))
312 ((looking-at "\\[/\\(\\(\\w\\|_\\)*\\)[\t ]*$")
313 (delete-region (point) (progn (end-of-line) (point)))
314 (wesnoth-insert-missing-closing)
315 (end-of-line))
317 (wesnoth-indent)))
318 (setq target (point)))
319 (goto-char target)))
321 (defun wesnoth-complete-macro (&optional completep)
322 "Complete and insert the macro at point.
323 If COMPLETEP is non-nil, attempt to complete the macro at point."
324 (interactive)
325 (let* ((macro-information (append (wesnoth-completion-available
326 'wesnoth-macro-data)
327 (wesnoth-completion-available
328 'wesnoth-local-macro-data)))
329 (completions (wesnoth-emacs-completion-formats
330 (mapcar 'car macro-information)))
331 (partial (when completep
332 (save-excursion
333 (back-to-indentation)
334 (when (looking-at "{\\(\\(\\w\\|_\\)*\\)")
335 (match-string 1)))))
336 (macro (or (wesnoth-element-completion completions "Macro: ")
337 partial))
338 (args (second (find macro macro-information
339 :key 'car :test 'string=))))
340 (when macro
341 (if partial
342 (progn
343 (delete-region (progn (back-to-indentation) (point))
344 (progn (end-of-line) (point)))
345 (insert "{" macro (if args " }" "}")))
346 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
347 (save-excursion
348 (wesnoth-indent))
349 (when args
350 (forward-char -1)))))
352 (defun wesnoth-complete-attribute (&optional completep)
353 "Insert the attribute at point.
354 If COMPLETEP is non-nil, attempt to complete the attribute at point."
355 (interactive)
356 (let* ((completions (wesnoth-build-completion 2))
357 (partial (when completep
358 (save-excursion
359 (back-to-indentation)
360 (when (looking-at "\\(\\(\\w\\|_\\)+\\)")
361 (match-string 1)))))
362 (attribute (or (wesnoth-element-completion completions "Attribute: ")
363 partial)))
364 (when attribute
365 (if (and partial completep)
366 (progn
367 (delete-region (progn (back-to-indentation) (point))
368 (progn (end-of-line) (point)))
369 (insert attribute "="))
370 (wesnoth-insert-element-separately attribute
371 (if (string-match "=" attribute)
373 "=")))
374 (save-excursion
375 (wesnoth-indent)))))
377 (defun wesnoth-complete-tag (&optional completep)
378 "Complete and insert the tag at point.
379 If COMPLETEP is non-nil, attempt to complete tag at point."
380 (interactive)
381 (let* ((completions (wesnoth-build-completion 1))
382 (partial (when completep
383 (save-excursion
384 (back-to-indentation)
385 (when (looking-at "\\[\\(\\(\\w\\|_\\)+\\)")
386 (match-string 1)))))
387 (tag (or (wesnoth-element-completion completions "Tag: ")
388 partial)))
389 (let ((closed-p nil))
390 (save-excursion
391 (wesnoth-jump-to-matching)
392 (back-to-indentation)
393 (when (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
394 (string= tag (match-string 1)))
395 (setq closed-p t)))
396 (when completep
397 (delete-region (progn (back-to-indentation) (point))
398 (progn (end-of-line) (point))))
399 (if (and closed-p completep)
400 (progn
401 (wesnoth-insert-and-indent "[" tag "]")
402 (end-of-line))
403 (wesnoth-insert-tag nil tag)))))
405 (defun wesnoth-build-completion (position)
406 "Create a new list for tag completion if necessary.
407 Rebuilding list is required for versions of GNU Emacs earlier
408 than 22. POSITION is the argument passed to `nth' for
409 `wesnoth-tag-data'."
410 (interactive "P")
411 (let* ((parent (wesnoth-parent-tag))
412 (candidates
413 (if (or (stringp parent) (null parent))
414 (nth position
415 (find (wesnoth-parent-tag)
416 (wesnoth-completion-available 'wesnoth-tag-data)
417 :key 'car :test 'string=))
418 (mapcar 'car (wesnoth-completion-available 'wesnoth-tag-data)))))
419 (wesnoth-emacs-completion-formats candidates)))
421 (defun wesnoth-emacs-completion-formats (candidates)
422 "Return the completions in the correct format for `emacs-major-version'.
423 CANDIDATES is a list of all possible completions."
424 (if (> emacs-major-version 21)
425 candidates
426 (let ((tags '())
427 (iter 0))
428 (dolist (tag candidates)
429 (setq iter (1+ iter))
430 (setq tags (append tags (list (cons tag iter)))))
431 tags)))
433 (defun wesnoth-insert-tag (&optional elements tagname)
434 "Insert the specified opening tag and it's matching closing tag.
435 Both the opening and closing tags will be placed on their own
436 lines with point positioned between them. Completion of tags at
437 the prompt uses `wesnoth-tags-list'.
439 ELEMENTS is specifies the number of following blocks which the
440 tag should wrap around.
442 TAGNAME is the name of the tag to be inserted."
443 (interactive "Ps")
444 (unless tagname
445 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 1))))
446 (or elements (setq elements 0))
447 (let ((depth 0)
448 (start (save-excursion (forward-line -1) (point)))
449 (end (unless (= elements 0)
450 (wesnoth-nth-pair-position elements))))
451 (wesnoth-insert-element-separately "[" tagname "]")
452 (save-excursion
453 (if end
454 (goto-char (marker-position end))
455 (newline 2))
456 (wesnoth-insert-element-separately "[/" tagname "]")
457 (indent-region start (point) nil))
458 (unless end
459 (forward-line 1)))
460 (wesnoth-indent))
462 (defun wesnoth-nth-pair-position (count)
463 "Return `point' after COUNT number of matching element pairs.
464 COUNT is a positive number representing the number of balanced
465 pairs to move across.
466 `point' is returned as a marker object."
467 (save-excursion
468 (while (> count 0)
469 ;; Currently looking-at target tag. Stop here to avoid
470 ;; incorrect nesting.
471 (unless (wesnoth-search-for-matching-tag
472 'search-forward-regexp wesnoth-element-closing 'point-max)
473 (setq count 0)
474 (search-backward-regexp wesnoth-element-closing (point-min) t))
475 (and (> (decf count) 0) (forward-line 1)))
476 (end-of-line)
477 (point-marker)))
479 (defun wesnoth-insert-element-separately (&rest strings)
480 "Concatenate STRINGS and insert them on a line of their own."
481 (let ((create-newline (save-excursion
482 (beginning-of-line)
483 (if (looking-at "^[\t ]*$") nil t))))
484 (when create-newline
485 (if (> (point) (save-excursion (back-to-indentation) (point)))
486 (progn
487 (end-of-line)
488 (newline))
489 (beginning-of-line)
490 (open-line 1)))
491 (insert (apply 'concat strings))))
493 (defun wesnoth-insert-missing-closing (&optional start end)
494 "Insert the next expected closing element at point.
496 START and END define the region to check for missing closing
497 elements. If function `transient-mark-mode' is enabled, the region
498 specified will be used as START and END. Otherwise, START and
499 END will be the minimum and maximum positions of the buffer,
500 respectively."
501 (interactive)
502 (if (and transient-mark-mode mark-active)
503 (setq start (region-beginning)
504 end (copy-marker (region-end)))
505 (setq start (point-min)
506 end (point-max)))
507 (let ((element (wesnoth-check-structure start end)))
508 (if (not element)
509 (error "%s" "Unable to find element to insert")
510 (when (string= element "Unexpected end of file")
511 (error "%s" element))
512 (wesnoth-insert-element-separately element)))
513 (wesnoth-indent)
514 (end-of-line))
516 (defun wesnoth-insert-and-indent (&rest args)
517 "Concatenate and insert the given string(s) before indenting.
519 ARGS is a list of strings to be inserted."
520 (insert (apply 'concat args))
521 (wesnoth-indent))
523 (defun wesnoth-newline (&optional indent)
524 "Indent both the current line and the newline created.
525 If `wesnoth-auto-indent-flag' is nil, indentation will not be
526 performed. Indentation can be forced by setting INDENT to
527 non-nil."
528 (interactive)
529 (save-excursion
530 (when (and (or wesnoth-auto-indent-flag indent)
531 (not (looking-at "^[\t ]*$")))
532 (wesnoth-indent)))
533 (newline))
535 ;;; Movement
536 (defmacro wesnoth-navigate-element (repeat search-function bound)
537 "Move point to the tag in the given direction REPEAT times.
539 SEARCH-FUNCTION is the symbol of the function for searching in
540 the required direction, with BOUND marking the furthest point to
541 search."
542 `(progn
543 (or ,repeat (setq ,repeat 1))
544 (while (> ,repeat 0)
545 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
546 (funcall ,search-function wesnoth-element-opening ,bound t)
547 (back-to-indentation)
548 (decf ,repeat))))
550 (defun wesnoth-forward-element (repeat)
551 "Move point to the end of the next tag.
552 REPEAT is an optional numeric argument. If REPEAT is non-nil,
553 jump forward the specified number of tags."
554 (interactive "p")
555 (if (< repeat 0)
556 (wesnoth-backward-element (abs repeat))
557 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
559 (defun wesnoth-backward-element (repeat)
560 "Move point to the beginning of the previous tag.
561 REPEAT is an optional numeric argument. If REPEAT is non-nil,
562 jump backward the specified number of tags."
563 (interactive "p")
564 (if (< repeat 0)
565 (wesnoth-forward-element (abs repeat))
566 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
568 (defmacro wesnoth-search-for-matching-tag (search-function search-string bound)
569 "Search for the matching tag for the current line.
571 SEARCH-FUNCTION is the name of the function used to perform the search.
572 SEARCH-STRING is a string representing the matching tag type.
573 BOUND is the bound to be passed to the search function."
574 `(let ((depth 1))
575 (unless (looking-at ,search-string)
576 (unless (> (point) (funcall ,bound)) (end-of-line))
577 (while (and (> depth 0)
578 (funcall ,search-function wesnoth-element
579 (funcall ,bound) t))
580 (if (string-match ,search-string (match-string 0))
581 (decf depth)
582 (incf depth)))
583 t)))
585 (defun wesnoth-jump-to-matching ()
586 "Jump point to the matching opening/closing tag."
587 (interactive)
588 (beginning-of-line)
589 (if (looking-at wesnoth-element-opening)
590 (wesnoth-search-for-matching-tag
591 'search-forward-regexp wesnoth-element-closing 'point-max)
592 (wesnoth-search-for-matching-tag
593 'search-backward-regexp wesnoth-element-opening 'wesnoth-wml-start-pos))
594 (back-to-indentation))
596 (defun wesnoth-wml-start-pos ()
597 "Determine the position of `point' relative to where the actual WML begins.
598 Return the likely starting position of the WML if it is found.
599 Otherwise return nil."
600 (save-excursion
601 (goto-char (point-min))
602 (when (search-forward-regexp wesnoth-element (point-max) t)
603 (beginning-of-line)
604 (point))))
606 (defun first-column-indent-p (point)
607 "Return non-nil if the current line should not be indented.
609 POINT is the position in the buffer to check.
610 CONTEXT represents the type of element which precedes the current element."
611 (or (not (wesnoth-wml-start-pos))
612 (<= (point) (wesnoth-wml-start-pos))
613 (nth 3 (parse-partial-sexp (point-min) point))
614 (looking-at wesnoth-preprocessor-regexp)))
616 (defun wesnoth-indent ()
617 "Indent the current line as WML."
618 (beginning-of-line)
619 (let ((cur-indent 0))
620 (unless (first-column-indent-p (point))
621 (multiple-value-bind (context ref-indent)
622 (wesnoth-determine-context (point))
623 (cond
624 ((eq context 'opening)
625 (if (or (and wesnoth-indent-savefile
626 (not (looking-at wesnoth-element-closing)))
627 (looking-at wesnoth-element-opening))
628 (setq cur-indent (+ ref-indent wesnoth-base-indent))
629 (setq cur-indent ref-indent)))
630 ((eq context 'closing)
631 (if (or (looking-at "^[\t ]*\\[/")
632 (and (not wesnoth-indent-savefile)
633 (not (looking-at wesnoth-element-opening))))
634 (setq cur-indent (- ref-indent wesnoth-base-indent))
635 (setq cur-indent ref-indent))))))
636 (indent-line-to (max cur-indent 0))))
638 (defun wesnoth-within-define (position)
639 "Determine whether point is currently inside a #define block.
640 POSITION is the initial cursor position."
641 (let ((depth 0))
642 (dolist (element (or wesnoth-define-blocks
643 (wesnoth-find-macro-definitions)))
644 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
645 (list position)) '>)) position)
646 (setq depth (max (car element) depth))))
647 depth))
649 (defun wesnoth-find-macro-definitions ()
650 "Return information regarding positioning of macro definitions."
651 (save-excursion
652 (goto-char (point-min))
653 (let ((depth 0)
654 openings cache)
655 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t)
656 (and (string= (match-string 1) "#define") (beginning-of-line))
657 (setq depth
658 (if (string= (match-string 1) "#define")
659 (progn
660 (add-to-list 'openings (point-marker))
661 (1+ depth))
662 (add-to-list 'cache
663 (list depth (list (car openings) (point-marker))))
664 (setq openings (cdr openings))
665 (1- depth)))
666 (end-of-line))
667 cache)))
669 (defun wesnoth-indent-region (start end)
670 "Indent the region from START to END.
672 Creates and destroys a cache of macro definition details as necessary."
673 (interactive "r")
674 (unwind-protect
675 (save-excursion
676 (goto-char end)
677 (setq end (point-marker))
678 (goto-char start)
679 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
680 (or (bolp) (forward-line 1))
681 (while (< (point) end)
682 (if (looking-at "^[\t ]*$")
683 (indent-line-to 0)
684 (funcall indent-line-function))
685 (forward-line 1)))
686 (setq wesnoth-define-blocks nil)))
688 (defun wesnoth-determine-context (position)
689 "Determine the type of the last relevant element.
691 POSITION is the buffer position of the element for which to
692 determine the context."
693 (save-excursion
694 (search-backward-regexp wesnoth-element (wesnoth-wml-start-pos) t)
695 (let ((match (or (match-string 1) ""))
696 (depth (wesnoth-within-define position)))
697 (while (and (> (wesnoth-within-define (point)) depth)
698 (not (= (point) (wesnoth-wml-start-pos))))
699 (search-backward-regexp wesnoth-element
700 (wesnoth-wml-start-pos) t)
701 (setq match (match-string 1)))
702 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth 0)
703 (string-match "#define" match))
704 ;; Found nothing of use; reset match and assume top-level tag.
705 (setq match ""))
706 (cond
707 ((string-match "\\[/\\|#enddef" match)
708 (values 'closing (current-indentation)))
709 ((string-match "\\[[^/]?\\|#define" match)
710 (values 'opening (current-indentation)))))))
712 (defun wesnoth-newline-and-indent (&optional indent)
713 "Indent both the current line and the newline created.
714 If `wesnoth-auto-indent-flag' is nil, indentation will not be
715 performed.
717 If the optional argument, INDENT is non-nil, force indentation to
718 be performed."
719 (interactive)
720 (wesnoth-newline)
721 (when (or wesnoth-auto-indent-flag indent)
722 (wesnoth-indent)))
724 ;;; WML checks
725 (defun wesnoth-check-element-type (position last-tag)
726 "Determine the context of the element.
727 POSITION is the position of the element in the list.
728 LAST-TAG is the parent element."
729 (if (or (string= last-tag "#define")
730 (string= last-tag "#ifndef")
731 (string= last-tag "#ifdef"))
732 (member (match-string-no-properties 1)
733 (mapcar 'car (wesnoth-completion-available 'wesnoth-tag-data)))
734 (member last-tag
735 (mapcar 'car
736 (remove-if-not
737 (lambda (list)
738 (member (match-string-no-properties 1)
739 list))
740 (wesnoth-completion-available 'wesnoth-tag-data)
741 :key position)))))
743 (defun wesnoth-check-output (buffer format-string &rest args)
744 "Output the string as passed to `format'.
745 BUFFER is the buffer to output the result.
746 FORMAT-STRING is the string as the first argument of `format'.
747 ARGS is any additional data required by `format' to handle FORMAT-STRING."
748 (save-excursion
749 (let ((lnap (line-number-at-pos)))
750 (set-buffer buffer)
751 (insert (apply 'format (concat "%d: " format-string "\n")
752 lnap args)))))
754 (defun wesnoth-check-wml ()
755 "Perform context-sensitive analysis of WML-code."
756 (interactive)
757 (when (fboundp 'wesnoth-update-project-information)
758 (funcall 'wesnoth-update-project-information))
759 (let ((unmatched-tag-list '())
760 (outbuf (get-buffer-create "*WML*")))
761 (save-excursion
762 (let ((buffer (buffer-name)))
763 (set-buffer outbuf)
764 (erase-buffer)
765 (message (format "Checking %s..." buffer))))
766 (save-excursion
767 (goto-char (or (wesnoth-wml-start-pos) (point-min)))
768 (while (search-forward-regexp
769 (concat "^[\t ]*\\(\\[[+/]?\\(\\(\\w\\|_\\)+\\)\\]\\|"
770 "\\(\\w\\|_\\)+=\\|{\\(\\(\\w\\|_\\)+\\).*}\\|"
771 wesnoth-preprocessor-regexp "\\)")
772 (point-max) t)
773 (beginning-of-line)
774 (cond ((looking-at "^[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
775 (unless (wesnoth-check-element-type 'second
776 (car unmatched-tag-list))
777 (wesnoth-check-output outbuf
778 "Tag not available in this context: '%s'"
779 (match-string-no-properties 1)))
780 (setq unmatched-tag-list (cons
781 (match-string-no-properties 1)
782 unmatched-tag-list)))
783 ((looking-at "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\) ")
784 (setq unmatched-tag-list (cons (match-string-no-properties 1)
785 unmatched-tag-list)))
786 ((looking-at wesnoth-preprocessor-closing-regexp)
787 (unless (string= (car unmatched-tag-list)
788 (second (find (match-string-no-properties 1)
789 '(("enddef" "#define")
790 ("ifdef" "#endif")
791 ("ifndef" "#endif"))
792 :key 'car :test 'string=)))
793 (wesnoth-check-output outbuf
794 "Preprocessor statement does not nest correctly"))
795 (setq unmatched-tag-list (cdr unmatched-tag-list)))
796 ((looking-at "^[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
797 (unless (wesnoth-check-element-type 'third
798 (car unmatched-tag-list))
799 (wesnoth-check-output
800 outbuf "Attribute not available in this context: '%s'"
801 (match-string-no-properties 1)))
802 (unless (match-string 3)
803 (wesnoth-check-output
804 outbuf "Attribute has no value")))
805 ((looking-at "^[\t ]*#else")
806 (unless (string-match "ifn?def" (car unmatched-tag-list))
807 (if (string= (car unmatched-tag-list) "#define")
808 (wesnoth-check-output outbuf "Expecting: '%s'"
809 (car unmatched-tag-list))
810 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
811 (car unmatched-tag-list)))))
812 ((looking-at "^[\t ]*{\\(\\(\\w\\|_\\)+\\).*}")
813 (unless (find (match-string-no-properties 1)
814 (append (wesnoth-completion-available
815 'wesnoth-local-macro-data)
816 (wesnoth-completion-available
817 'wesnoth-macro-data))
818 :test 'string= :key 'car)
819 (wesnoth-check-output outbuf "Unknown macro definition: '{%s}'"
820 (match-string-no-properties 1))))
821 ((or (looking-at "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]"))
822 (unless (string= (match-string-no-properties 1)
823 (car unmatched-tag-list))
824 (if (string= "#" (subseq (car unmatched-tag-list) 0 1))
825 (wesnoth-check-output outbuf "Expecting: '#%s'"
826 (car
827 (find (car unmatched-tag-list)
828 '(("enddef" "#define")
829 ("ifdef" "#endif")
830 ("ifndef" "#endif"))
831 :key 'second :test 'string=)))
832 (wesnoth-check-output outbuf "Expecting: '[/%s]'"
833 (car unmatched-tag-list))))
834 (setq unmatched-tag-list (cdr unmatched-tag-list))))
835 (end-of-line))
836 (if unmatched-tag-list
837 (dolist (tag unmatched-tag-list)
838 (wesnoth-check-output outbuf "Unmatched tag: '%s'"
839 (car unmatched-tag-list)))))
840 (save-excursion
841 (let ((buffer (buffer-name)))
842 (set-buffer outbuf)
843 (display-buffer outbuf t)
844 (message (format "Checking %s... done" buffer))))))
846 (defmacro wesnoth-element-requires (element requirement &optional pop)
847 "Process requirements for corresponding preprocessor elements.
848 ELEMENT is the current element being tested.
849 REQUIREMENT is the element required to exist for correct nesting.
850 POP is an optional argument indicating the element should be
851 removed from the unmatched-tag-list."
852 `(when (string= ,element (match-string-no-properties 1))
854 (if (string-match ,requirement (car unmatched-tag-list))
855 (progn
856 (and ,pop (setq unmatched-tag-list (cdr unmatched-tag-list)))
858 (setq error-position (point)))))
860 (defmacro wesnoth-structure-result (position element)
861 "Process results of the structure check.
862 POSITION is the error position or nil, if no error was found.
863 ELEMENT is the last unmatched element, or nil if all opening
864 elements have been matched."
865 `(let ((expected nil))
866 (when ,element
867 (cond ((string= ,element "define ") (setq expected "#enddef"))
868 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
869 (if (interactive-p)
870 (if (or ,element ,position)
871 (progn
872 (and ,position (goto-char ,position))
873 (message "Error: Expecting %s" (or expected
874 (concat "[/" ,element "]"))))
875 (message "%s" "Structure appears consistent."))
876 (when (or expected ,element)
877 (or expected (concat "[/" ,element "]"))))))
879 (defun wesnoth-check-structure (&optional start end)
880 "Check the buffer for correct nesting of elements.
881 If a problem is found in the structure, point will be placed at
882 the location which an element was expected and the expected
883 element will be displayed in the mini-buffer.
885 START and END define the region to be checked. If
886 function `transient-mark-mode' is enabled, the region specified will be
887 checked. Otherwise START and END will be the minimum and maximum
888 positions of the buffer, respectively."
889 (interactive)
890 (unless (or start end)
891 (if (and transient-mark-mode mark-active)
892 (setq start (region-beginning)
893 end (copy-marker (region-end)))
894 (setq start (point-min)
895 end (point-max))))
896 (let ((unmatched-tag-list '())
897 (error-position nil))
898 (save-excursion
899 (and start (goto-char start))
900 (while (and (search-forward-regexp
901 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
902 wesnoth-preprocessor-regexp "\\)") end t)
903 (not error-position))
904 (beginning-of-line)
905 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
906 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
907 (setq unmatched-tag-list (cons (match-string-no-properties 1)
908 unmatched-tag-list))
909 (cond
910 ((wesnoth-element-requires "#else" "ifn?def "))
911 ((wesnoth-element-requires "#endif" "ifn?def " t))
912 ((wesnoth-element-requires "#enddef" "define " t))
913 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
914 wesnoth-preprocessor-closing-regexp))
915 (if (string= (match-string-no-properties 1)
916 (car unmatched-tag-list))
917 (setq unmatched-tag-list (cdr unmatched-tag-list))
918 (setq error-position (point))))))
919 (end-of-line)))
920 (wesnoth-structure-result error-position (car unmatched-tag-list))))
922 ;;; wesnoth-mode
923 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
924 "Major mode for editing WML."
925 (wesnoth-preprocessor-best-face)
926 (set-syntax-table wesnoth-syntax-table)
927 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
928 (set (make-local-variable 'comment-start) "#")
929 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
930 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
931 (set (make-local-variable 'font-lock-defaults)
932 '(wesnoth-font-lock-keywords
933 nil t nil nil
934 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
935 (setq indent-tabs-mode nil)
936 (setq mode-name "WML")
937 (run-hooks 'wesnoth-mode-hook))
939 (provide 'wesnoth-mode)
941 ;;; wesnoth-mode.el ends here