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