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