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