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