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