* wesnoth-mode.el: Require cl for decf, incf, multiple-value-bind and values
[wesnoth-mode.git] / wesnoth-mode.el
blob1aa43c63fe3ac3e13863cf52cdc57607dcb3dd3e
1 ;;; wesnoth-mode.el --- A major mode for editing WML.
2 ;; Copyright (C) 2006, 2007, 2008 Chris Mann
4 ;; This program is free software; you can redistribute it and/or
5 ;; modify it under the terms of the GNU General Public License as
6 ;; published by the Free Software Foundation; either version 2 of the
7 ;; License, or (at your option) any later version.
9 ;; This program is distributed in the hope that it will be useful, but
10 ;; WITHOUT ANY WARRANTY; without even the implied warranty of
11 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
12 ;; General Public License for more details.
14 ;; You should have received a copy of the GNU General Public License
15 ;; along with this program; see the file COPYING. If not, write to the
16 ;; Free Software Foundation, 51 Franklin Street, Fifth Floor, Boston,
17 ;; MA 02139, USA.
19 ;;; Description:
20 ;; wesnoth-mode is a major mode for Emacs which assists in the editing
21 ;; of Wesnoth Markup Language (WML) files. Currently, this mode
22 ;; features syntax highlighting support, automatic indentation,
23 ;; tag-completion and preliminary support for syntax checking.
25 ;;; Commentary:
26 ;; Add the following to your .emacs:
27 ;; (add-to-list 'load-path "path/to/wesnoth-mode")
28 ;; (autoload 'wesnoth-mode "wesnoth-mode" "Major mode for editing WML." t)
29 ;; Optionally adding:
30 ;; (add-to-list 'auto-mode-alist '("\\.cfg\\'" . wesnoth-mode))
31 ;; to automatically load wesnoth-mode for all files ending in '.cfg'.
33 ;;; History:
34 ;; 1.2.5
35 ;; * Fixed support for GNU Emacs 21.
36 ;; * Added several new tags to `wesnoth-tags-list'.
37 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
38 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
39 ;; how many blocks to wrap across instead of a region.
40 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
41 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
42 ;; causing tags not to be inserted in the correct position.
43 ;; * Fixed highlighting of array indexes as tags.
44 ;; 1.2.4
45 ;; * Improved syntax-highlighting for macro calls.
46 ;; * Underscore is now treated as whitespace.
47 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
48 ;; * Point is now placed at the first non-whitespace character of the line,
49 ;; instead of the last.
50 ;; * Corrected minor indentation bugs.
51 ;; * Indenting across large regions is now much more efficient.
52 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
53 ;; applied.
54 ;; 1.2.3
55 ;; * Now compatible with GNU Emacs 21.4.
56 ;; * Added support for several new tags.
57 ;; * Added menu entry for wesnoth-mode.
58 ;; * Significant speed increase to indentation.
59 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
60 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
61 ;; has been removed.
62 ;; * Trailing whitespace is no longer created when creating a second
63 ;; consecutive newline.
64 ;; * Spurious newlines are no longer created when inserting a tag elements
65 ;; around a region.
66 ;; 1.2.2
67 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
68 ;; `wesnoth-element', `wesnoth-element-opening',
69 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
70 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
71 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
72 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
73 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
74 ;; * Fixed a bug in indentation where content was needed between elements pairs
75 ;; for indentation to work.
76 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
77 ;; `wesnoth-auto-indent-flag'.
78 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
79 ;; * Added indentation styles: `wesnoth-indent-default',
80 ;; `wesnoth-indent-withtags' which implement a a similar indentation
81 ;; style to the existing styles, however all preprocessor statements are
82 ;; indented to the first column.
83 ;; * Added support for several new tags.
84 ;; * Modified `wesnoth-newline' to behave more consistently.
85 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
86 ;; now leaves point at the beginning (when moving backward) or end (when
87 ;; moving forward) of the match.
88 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
89 ;; will now work on preprocessor statements. Will now warn if jump
90 ;; destination may not be correct (due to errors in WML structure).
91 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
92 ;; * `wesnoth-check-structure' can now be applied over an active region and
93 ;; now checks preprocessor statements for correct nesting.
94 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
95 ;; perform indentation by providing a prefix argument.
96 ;; * Indentation styles now leave point at the first non-whitespace character
97 ;; of the line.
98 ;; * `wesnoth-check-tag-names' now reports on success.
99 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
100 ;; * `outline-minor-mode' now works on macro definitions.
101 ;; 1.2.1
102 ;; * Base indent now defaults to 4.
103 ;; * Added support for #ifndef.
105 ;;; Code:
106 (require 'cl)
108 (defconst wesnoth-mode-version "1.2.5a"
109 "The current version of `wesnoth-mode'.")
111 (defgroup wesnoth-mode nil "Wesnoth-mode access"
112 :group 'languages
113 :prefix "wesnoth-")
115 (defcustom wesnoth-auto-indent-flag t
116 "Non-nil means indent the current line upon creating a newline."
117 :type 'boolean
118 :group 'wesnoth-mode)
120 (defcustom wesnoth-indent-savefile t
121 "Non-nil means to use the current indentation conventions.
122 If nil, use the old convention for indentation.
123 The current convention is all attributes are indented a level deeper
124 than their parent; in the past attributes were indented to the same
125 level as their parent.")
127 (defcustom wesnoth-base-indent 4
128 "The number of columns to indent WML."
129 :type 'integer
130 :group 'wesnoth-mode)
132 (defconst wesnoth-preprocessor-regexp
133 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def\\)"
134 "Regular expression to match all preprocessor statements.")
136 (defconst wesnoth-preprocessor-opening-regexp
137 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
138 "Regular expression to match \"opening\" preprocessor statements.")
140 (defconst wesnoth-preprocessor-closing-regexp
141 "[\t ]*#e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)"
142 "Regular expression to match \"closing\" preprocessor statements.")
144 (defvar wesnoth-define-blocks '()
145 "Cache of all toplevel #define and #enddef pairs.")
147 (defvar wesnoth-mode-hook nil)
149 (defvar wesnoth-mode-map
150 (let ((map (make-sparse-keymap)))
151 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
152 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
153 (define-key map (kbd "C-m") 'wesnoth-newline)
154 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
155 (define-key map (kbd "C-c c") 'wesnoth-check-structure)
156 (define-key map (kbd "C-c C-c") 'wesnoth-check-structure)
157 (define-key map (kbd "C-c e") 'wesnoth-insert-tag)
158 (define-key map (kbd "C-c C-e") 'wesnoth-insert-tag)
159 (define-key map (kbd "M-TAB") 'wesnoth-insert-tag)
160 (define-key map (kbd "C-c m") 'wesnoth-jump-to-matching)
161 (define-key map (kbd "C-c C-m") 'wesnoth-jump-to-matching)
162 (define-key map (kbd "C-c n") 'wesnoth-check-tag-names)
163 (define-key map (kbd "C-c C-n") 'wesnoth-check-tag-names)
164 (define-key map (kbd "C-c /") 'wesnoth-insert-missing-closing)
165 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
166 (define-key map [menu-bar wesnoth]
167 (cons "WML" (make-sparse-keymap "WML")))
168 (define-key map [menu-bar wesnoth insert-tag]
169 '("Insert Tag" . wesnoth-insert-tag))
170 (define-key map [menu-bar wesnoth check-names]
171 '("Check Tag Names" . wesnoth-check-tag-names))
172 (define-key map [menu-bar wesnoth check-structure]
173 '("Check Structure" . wesnoth-check-structure))
174 (define-key map [menu-bar wesnoth jump-to-matching]
175 '("Jump to Matching" . wesnoth-jump-to-matching))
176 (define-key map [menu-bar wesnoth insert-missing-closing]
177 '("Insert Missing Tag" . wesnoth-insert-missing-closing))
178 map)
179 "Keymap used in wesnoth mode.")
181 (defvar wesnoth-syntax-table
182 (let ((wesnoth-syntax-table (make-syntax-table)))
183 (modify-syntax-entry ?= "." wesnoth-syntax-table)
184 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
185 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
186 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
187 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
188 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
189 wesnoth-syntax-table)
190 "Syntax table for `wesnoth-mode'.")
192 ;; Prevents automatic syntax-highlighting of elements which might be
193 ;; pre-processor statements.
194 (defvar wesnoth-syntactic-keywords
195 (list
196 '("\\(^[\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\|#enddef\\)" 1 "w")
197 '("\\(#[\t ]*.*$\\)" 1 "<"))
198 "Highlighting syntactic keywords within `wesnoth-mode'.")
200 (defun wesnoth-preprocessor-best-face ()
201 "Use `font-lock-preprocessor-face' when available."
202 (when global-font-lock-mode
203 (if (boundp 'font-lock-preprocessor-face)
204 (copy-face 'font-lock-preprocessor-face 'wesnoth-preprocessor-face)
205 (copy-face 'font-lock-keyword-face 'wesnoth-preprocessor-face))))
207 (defvar wesnoth-font-lock-keywords
208 (list
209 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . 'wesnoth-preprocessor-face)
210 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
211 2 font-lock-function-name-face)
212 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
213 'wesnoth-preprocessor-face)
214 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)"
215 (1 font-lock-function-name-face))
216 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)"
217 (1 font-lock-function-name-face))
218 '("}" . font-lock-function-name-face)
219 '("^[\t ]*\\(\\[[^]]+\\]\\)" 1 font-lock-type-face)
220 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
221 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
222 1 font-lock-variable-name-face))
223 "Syntax highlighting for `wesnoth-mode'.")
225 (defconst wesnoth-element-closing "^[\t ]*\\(\\[/\\|#enddef\\)"
226 "String to use for a closing element.")
228 (defconst wesnoth-element-opening "^[\t ]*\\(\\[[^/]\\|#define\\)"
229 "String to use for an opening element.")
231 (defconst wesnoth-element "^[\t ]*\\(\\[[^]]?\\|#define\\|#enddef\\)"
232 "String to use for an opening or closing element.")
234 ;;; Insertion
235 (defvar wesnoth-tags-list
236 (list
237 "abilities" "about" "advances" "advancefrom" "ai" "allow_recruit" "and"
238 "animation" "array" "attack" "attack_anim" "attacks" "avoid" "binary_path"
239 "bold" "campaign" "capture_village" "choose""clear_variable"
240 "colour_adjust" "command" "deaths" "debug_message" "defend" "defends"
241 "defense" "delay" "destination" "disallow_recruit" "do" "effect" "else"
242 "end_turn" "endlevel" "entry" "era" "event" "expenses" "filter"
243 "filter_attack" "filter_adjacent_location" "filter_location"
244 "filter_radius" "filter_second" "filter_vision" "format" "frame"
245 "game_config" "generator" "gold" "have_unit" "header" "hide_unit" "if"
246 "illuminated_time" "image" "img" "income" "italic" "item" "jump" "kill"
247 "killed" "label" "language" "leader_goal" "main_map" "menu" "message"
248 "mini_map" "missile_frame" "modifications" "modify_side" "modify_turns"
249 "move" "move_unit_fake" "movement_costs" "movetype" "multiplayer"
250 "multiplayer_side" "music" "not" "num_units" "object" "objectives"
251 "objective" "observers" "option" "or" "panel" "part" "place_shroud"
252 "position" "print" "protect_location" "protect_unit" "race" "random"
253 "recall" "recalls" "recruit" "recruits" "redraw" "ref" "remove_shroud"
254 "remove_unit_overlay" "removeitem" "replay" "replay_start" "resistance"
255 "resolution" "results" "role" "save" "scenario" "scroll" "scroll_to"
256 "scroll_to_unit" "section" "set_menu_item" "set_recruit" "set_specials"
257 "set_variable" "show_if" "side" "side_playing" "snapshot" "sound" "source"
258 "specials" "statistics" "status" "stone" "store_gold" "store_locations"
259 "store_starting_location" "store_side" "store_unit" "story" "target" "team"
260 "teleport" "teleport_anim" "terrain" "terrain_graphics" "terrain_mask"
261 "test" "text_input" "textdomain" "theme" "then" "tile" "time" "time_area"
262 "time_of_day" "topic" "toplevel" "trait" "turn" "tutorial" "unhide_unit"
263 "unit" "unit_abilities" "unit_alignment" "unit_description" "unit_hp"
264 "unit_image" "unit_level" "unit_moves" "unit_overlay" "unit_profile"
265 "unit_status" "unit_traits" "unit_type" "unit_weapons" "unit_xp" "units"
266 "unstone" "unstore_unit" "upkeep" "variable" "variables" "village"
267 "villages" "while" "wml_filter")
268 "A list containing all tags which are available in WML.")
270 (defvar wesnoth-completion-cache '()
271 "List of tags which have been generated by `wesnoth-build-completion'.")
273 (defun wesnoth-build-completion (&optional rebuild)
274 "Create a new list for tag completion if necessary.
275 Rebuilding list is required for versions of GNU Emacs earlier
276 than 22. If REBUILD is non-nil, regenerate `wesnoth-completion-cache'."
277 (interactive "P")
278 (if (> emacs-major-version 21)
279 wesnoth-tags-list
280 (if (and wesnoth-completion-cache (not rebuild))
281 wesnoth-completion-cache
282 (let ((tags '())
283 (iter 0))
284 (dolist (tag wesnoth-tags-list)
285 (setq iter (1+ iter))
286 (setq tags (append tags (list (cons tag iter)))))
287 (setq wesnoth-completion-cache tags)))))
289 (defun wesnoth-insert-tag (&optional elements tagname)
290 "Insert the specified opening tag and it's matching closing tag.
291 Both the opening and closing tags will be placed on their own
292 lines with point positioned between them. Completion of tags at
293 the prompt uses `wesnoth-tags-list'.
295 ELEMENTS is specifies the number of following blocks which the
296 tag should wrap around.
298 TAGNAME is the name of the tag to be inserted."
299 (interactive "Ps")
300 (unless tagname
301 (setq tagname (completing-read "Tag: " (wesnoth-build-completion))))
302 (or elements (setq elements 0))
303 (let ((depth 0)
304 (start (save-excursion (forward-line -1) (point)))
305 (end (unless (= elements 0)
306 (wesnoth-nth-pair-position elements))))
307 (wesnoth-insert-element-separately "[" tagname "]")
308 (save-excursion
309 (if end
310 (goto-char (marker-position end))
311 (newline 2))
312 (wesnoth-insert-element-separately "[/" tagname "]")
313 (indent-region start (point) nil))
314 (unless end
315 (forward-line 1)))
316 (wesnoth-indent))
318 (defun wesnoth-nth-pair-position (count)
319 "Return `point' after COUNT number of matching element pairs.
320 COUNT is a positive number representing the number of balanced
321 pairs to move across.
322 `point' is returned as a marker object."
323 (save-excursion
324 (while (> count 0)
325 ;; Currently looking-at target tag. Stop here to avoid
326 ;; incorrect nesting.
327 (unless (wesnoth-search-for-matching-tag
328 'search-forward-regexp wesnoth-element-closing 'point-max)
329 (setq count 0)
330 (search-backward-regexp wesnoth-element-closing (point-min) t))
331 (and (> (decf count) 0) (forward-line 1)))
332 (end-of-line)
333 (point-marker)))
335 (defun wesnoth-insert-element-separately (&rest strings)
336 "Concatenate STRINGS and insert them on a line of their own."
337 (let ((create-newline (save-excursion
338 (beginning-of-line)
339 (if (looking-at "^[\t ]*$") nil t))))
340 (when create-newline
341 (if (> (point) (save-excursion (back-to-indentation) (point)))
342 (progn
343 (end-of-line)
344 (newline))
345 (beginning-of-line)
346 (open-line 1)))
347 (insert (apply 'concat strings))))
349 (defun wesnoth-insert-missing-closing (&optional start end)
350 "Insert the next expected closing element at point.
352 START and END define the region to check for missing closing
353 elements. If function `transient-mark-mode' is enabled, the region
354 specified will be used as START and END. Otherwise, START and
355 END will be the minimum and maximum positions of the buffer,
356 respectively."
357 (interactive)
358 (if (and transient-mark-mode mark-active)
359 (setq start (region-beginning)
360 end (copy-marker (region-end)))
361 (setq start (point-min)
362 end (point-max)))
363 (let ((element (wesnoth-check-structure start end)))
364 (if (not element)
365 (error "%s" "Unable to find element to insert")
366 (when (string= element "Unexpected end of file")
367 (error "%s" element))
368 (wesnoth-insert-element-separately element)))
369 (wesnoth-indent))
371 (defun wesnoth-insert-and-indent (&rest args)
372 "Concatenate and insert the given string(s) before indenting.
374 ARGS is a list of strings to be inserted."
375 (insert (apply 'concat args))
376 (wesnoth-indent))
378 (defun wesnoth-newline (&optional indent)
379 "Indent both the current line and the newline created.
380 If `wesnoth-auto-indent-flag' is nil, indentation will not be
381 performed. Indentation can be forced by setting INDENT to
382 non-nil."
383 (interactive)
384 (save-excursion
385 (when (and (or wesnoth-auto-indent-flag indent)
386 (not (looking-at "^[\t ]*$")))
387 (wesnoth-indent)))
388 (newline))
390 ;;; Movement
391 (defmacro wesnoth-navigate-element (repeat search-function bound)
392 "Move point to the tag in the given direction REPEAT times.
394 SEARCH-FUNCTION is the symbol of the function for searching in
395 the required direction, with BOUND marking the furthest point to
396 search."
397 `(progn
398 (or ,repeat (setq ,repeat 1))
399 (while (> ,repeat 0)
400 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
401 (funcall ,search-function wesnoth-element-opening ,bound t)
402 (back-to-indentation)
403 (decf ,repeat))))
405 (defun wesnoth-forward-element (repeat)
406 "Move point to the end of the next tag.
407 REPEAT is an optional numeric argument. If REPEAT is non-nil,
408 jump forward the specified number of tags."
409 (interactive "p")
410 (if (< repeat 0)
411 (wesnoth-backward-element (abs repeat))
412 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
414 (defun wesnoth-backward-element (repeat)
415 "Move point to the beginning of the previous tag.
416 REPEAT is an optional numeric argument. If REPEAT is non-nil,
417 jump backward the specified number of tags."
418 (interactive "p")
419 (if (< repeat 0)
420 (wesnoth-forward-element (abs repeat))
421 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
423 (defmacro wesnoth-search-for-matching-tag (search-function search-string bound)
424 "Search for the matching tag for the current line.
426 SEARCH-FUNCTION is the name of the function used to perform the search.
427 SEARCH-STRING is a string representing the matching tag type.
428 BOUND is the bound to be passed to the search function."
429 `(let ((depth 1))
430 (unless (looking-at ,search-string)
431 (unless (> (point) (funcall ,bound)) (end-of-line))
432 (while (and (> depth 0)
433 (funcall ,search-function wesnoth-element
434 (funcall ,bound) t))
435 (if (string-match ,search-string (match-string 0))
436 (decf depth)
437 (incf depth)))
438 t)))
440 (defun wesnoth-jump-to-matching ()
441 "Jump point to the matching opening/closing tag."
442 (interactive)
443 (beginning-of-line)
444 (if (looking-at wesnoth-element-opening)
445 (wesnoth-search-for-matching-tag
446 'search-forward-regexp wesnoth-element-closing 'point-max)
447 (wesnoth-search-for-matching-tag
448 'search-backward-regexp wesnoth-element-opening 'wesnoth-wml-start-pos))
449 (back-to-indentation))
451 (defun wesnoth-wml-start-pos ()
452 "Determine the position of `point' relative to where the actual WML begins.
453 Return the likely starting position of the WML if it is found.
454 Otherwise return nil."
455 (save-excursion
456 (goto-char (point-min))
457 (when (search-forward-regexp wesnoth-element (point-max) t)
458 (beginning-of-line)
459 (point))))
461 (defun first-column-indent-p (point)
462 "Return non-nil if the current line should not be indented.
464 POINT is the position in the buffer to check.
465 CONTEXT represents the type of element which precedes the current element."
466 (or (not (wesnoth-wml-start-pos))
467 (<= (point) (wesnoth-wml-start-pos))
468 (nth 3 (parse-partial-sexp (point-min) point))
469 (looking-at wesnoth-preprocessor-regexp)))
471 (defun wesnoth-indent ()
472 "Indent the current line as WML."
473 (beginning-of-line)
474 (let ((cur-indent 0))
475 (unless (first-column-indent-p (point))
476 (multiple-value-bind (context ref-indent)
477 (wesnoth-determine-context (point))
478 (cond
479 ((eq context 'opening)
480 (if (or (and wesnoth-indent-savefile
481 (not (looking-at wesnoth-element-closing)))
482 (looking-at wesnoth-element-opening))
483 (setq cur-indent (+ ref-indent wesnoth-base-indent))
484 (setq cur-indent ref-indent)))
485 ((eq context 'closing)
486 (if (or (looking-at "^[\t ]*\\[/")
487 (and (not wesnoth-indent-savefile)
488 (not (looking-at wesnoth-element-opening))))
489 (setq cur-indent (- ref-indent wesnoth-base-indent))
490 (setq cur-indent ref-indent))))))
491 (indent-line-to (max cur-indent 0))))
493 (defun wesnoth-within-define (position)
494 "Determine whether point is currently inside a #define block.
495 POSITION is the initial cursor position."
496 (let ((depth 0))
497 (dolist (element (or wesnoth-define-blocks
498 (wesnoth-find-macro-definitions)))
499 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
500 (list position)) '>)) position)
501 (setq depth (max (car element) depth))))
502 depth))
504 (defun wesnoth-find-macro-definitions ()
505 "Return information regarding positioning of macro definitions."
506 (save-excursion
507 (goto-char (point-min))
508 (let ((depth 0)
509 openings cache)
510 (while (search-forward-regexp "^[\t ]*\\(#define\\|#enddef\\)" (point-max) t)
511 (and (string= (match-string 1) "#define") (beginning-of-line))
512 (setq depth
513 (if (string= (match-string 1) "#define")
514 (progn
515 (add-to-list 'openings (point-marker))
516 (1+ depth))
517 (add-to-list 'cache
518 (list depth (list (car openings) (point-marker))))
519 (setq openings (cdr openings))
520 (1- depth)))
521 (end-of-line))
522 cache)))
524 (defun wesnoth-indent-region (start end)
525 "Indent the region from START to END.
527 Creates and destroys a cache of macro definition details as necessary."
528 (interactive "r")
529 (unwind-protect
530 (save-excursion
531 (goto-char end)
532 (setq end (point-marker))
533 (goto-char start)
534 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
535 (or (bolp) (forward-line 1))
536 (while (< (point) end)
537 (if (looking-at "^[\t ]*$")
538 (indent-line-to 0)
539 (funcall indent-line-function))
540 (forward-line 1)))
541 (setq wesnoth-define-blocks nil)))
543 (defun wesnoth-determine-context (position)
544 "Determine the type of the last relevant element.
546 POSITION is the buffer position of the element for which to
547 determine the context."
548 (save-excursion
549 (search-backward-regexp wesnoth-element (wesnoth-wml-start-pos) t)
550 (let ((match (or (match-string 1) ""))
551 (depth (wesnoth-within-define position)))
552 (while (and (> (wesnoth-within-define (point)) depth)
553 (not (= (point) (wesnoth-wml-start-pos))))
554 (search-backward-regexp wesnoth-element
555 (wesnoth-wml-start-pos) t)
556 (setq match (match-string 1)))
557 (when (and (= (point) (wesnoth-wml-start-pos)) (= depth 0)
558 (string-match "#define" match))
559 ;; Found nothing of use; reset match and assume top-level tag.
560 (setq match ""))
561 (cond
562 ((string-match "\\[/\\|#enddef" match)
563 (values 'closing (current-indentation)))
564 ((string-match "\\[[^/]?\\|#define" match)
565 (values 'opening (current-indentation)))))))
567 (defun wesnoth-newline-and-indent (&optional indent)
568 "Indent both the current line and the newline created.
569 If `wesnoth-auto-indent-flag' is nil, indentation will not be
570 performed.
572 If the optional argument, INDENT is non-nil, force indentation to
573 be performed."
574 (interactive)
575 (wesnoth-newline)
576 (when (or wesnoth-auto-indent-flag indent)
577 (wesnoth-indent)))
579 ;;; WML checks
580 (defun wesnoth-check-tag-names ()
581 "Check the names of all tags in the buffer for correctness.
582 If a tag is found which is not present in the list an error will
583 be signalled and point will be moved to the corresponding
584 position."
585 (interactive)
586 (let ((tag-position nil)
587 (missing-tag-name nil))
588 (save-excursion
589 (goto-char (point-min))
590 (while (and (search-forward-regexp "^[\t ]*\\[" (point-max) t)
591 (not tag-position))
592 (beginning-of-line)
593 (when (looking-at "^[\t ]*\\[/?\\(\\(\\w\\|_\\)+\\|_\\)\\]")
594 (unless (member (match-string-no-properties 1) wesnoth-tags-list)
595 (setq tag-position (point))
596 (setq missing-tag-name (match-string-no-properties 1))))
597 (end-of-line)))
598 (if (not tag-position)
599 (message "%s" "No unknown tag names found.")
600 (goto-char tag-position)
601 (back-to-indentation)
602 (message "'%s' is not known to exist"
603 missing-tag-name))))
605 (defmacro wesnoth-element-requires (element requirement &optional pop)
606 "Process requirements for corresponding preprocessor elements.
607 ELEMENT is the current element being tested.
608 REQUIREMENT is the element required to exist for correct nesting.
609 POP is an optional argument indicating the element should be
610 removed from the unmatched-tag-list."
611 `(when (string= ,element (match-string-no-properties 1))
613 (if (string-match ,requirement (car unmatched-tag-list))
614 (progn
615 (and ,pop (setq unmatched-tag-list (cdr unmatched-tag-list)))
617 (setq error-position (point)))))
619 (defmacro wesnoth-structure-result (position element)
620 "Process results of the structure check.
621 POSITION is the error position or nil, if no error was found.
622 ELEMENT is the last unmatched element, or nil if all opening
623 elements have been matched."
624 `(let ((expected nil))
625 (when ,element
626 (cond ((string= ,element "define ") (setq expected "#enddef"))
627 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
628 (if (interactive-p)
629 (if (or ,element ,position)
630 (progn
631 (and ,position (goto-char ,position))
632 (message "Error: Expecting %s" (or expected
633 (concat "[/" ,element "]"))))
634 (message "%s" "Structure appears consistent."))
635 (when (or expected ,element)
636 (or expected (concat "[/" ,element "]"))))))
638 (defun wesnoth-check-structure (&optional start end)
639 "Check the buffer for correct nesting of elements.
640 If a problem is found in the structure, point will be placed at
641 the location which an element was expected and the expected
642 element will be displayed in the mini-buffer.
644 START and END define the region to be checked. If
645 function `transient-mark-mode' is enabled, the region specified will be
646 checked. Otherwise START and END will be the minimum and maximum
647 positions of the buffer, respectively."
648 (interactive)
649 (unless (or start end)
650 (if (and transient-mark-mode mark-active)
651 (setq start (region-beginning)
652 end (copy-marker (region-end)))
653 (setq start (point-min)
654 end (point-max))))
655 (let ((unmatched-tag-list '())
656 (error-position nil))
657 (save-excursion
658 (and start (goto-char start))
659 (while (and (search-forward-regexp
660 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
661 wesnoth-preprocessor-regexp "\\)") end t)
662 (not error-position))
663 (beginning-of-line)
664 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
665 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
666 (setq unmatched-tag-list (cons (match-string-no-properties 1)
667 unmatched-tag-list))
668 (cond
669 ((wesnoth-element-requires "#else" "ifn?def "))
670 ((wesnoth-element-requires "#endif" "ifn?def " t))
671 ((wesnoth-element-requires "#enddef" "define " t))
672 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
673 wesnoth-preprocessor-closing-regexp))
674 (if (string= (match-string-no-properties 1)
675 (car unmatched-tag-list))
676 (setq unmatched-tag-list (cdr unmatched-tag-list))
677 (setq error-position (point))))))
678 (end-of-line)))
679 (wesnoth-structure-result error-position (car unmatched-tag-list))))
681 ;;; wesnoth-mode
682 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
683 "Major mode for editing WML."
684 (wesnoth-preprocessor-best-face)
685 (set-syntax-table wesnoth-syntax-table)
686 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
687 (set (make-local-variable 'comment-start) "#")
688 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
689 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
690 (set (make-local-variable 'font-lock-defaults)
691 '(wesnoth-font-lock-keywords
692 nil t nil nil
693 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
694 (setq indent-tabs-mode nil)
695 (setq mode-name "WML")
696 (run-hooks 'wesnoth-mode-hook))
698 (provide 'wesnoth-mode)
700 ;;; wesnoth-mode.el ends here