* wesnoth-mode.el (wesnoth-find-next, wesnoth-partial-macro-p,
[wesnoth-mode.git] / wesnoth-mode.el
blob80b78d5d3f87f4e91a7a0215c880606b1f2d4b12
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.3
37 ;; * All warnings found when checking WML are now underlined in the buffer.
38 ;; * Next and previous warning can be jumped to using C-c C-f (or C-x `) and
39 ;; C-c C-b, respectively.
40 ;; * Any macro arguments are now prompted for and inserted when performing
41 ;; completing, as suggested by fabi.
42 ;; * Improved handling of completion; no longer prompt when no completion
43 ;; found, as suggested by uzytkownik.
44 ;; * Added indentation for FOREACH, as suggested by fabi.
45 ;; * Several bugs and inconsistencies corrected.
46 ;; 1.3.2
47 ;; * Major performance improvements to indentation and WML checking.
48 ;; * Fixed a bug where nesting could break when inserting multiple elements
49 ;; near the last element in a buffer.
50 ;; * Fixed a bug where attributes immediately within #ifn?def were always
51 ;; reported to be illegal.
52 ;; * Fixed a bug where tags immediately within #ifn?def were always legal.
53 ;; * Fixed a bug where when inserting missing tags, scanning would only be
54 ;; performed up to point.
55 ;; * Fixed a bug when jumping between preprocessor statements.
56 ;; 1.3.1
57 ;; * Completion history available is now specific to wesnoth-mode.
58 ;; * Added binding to explicitly update macro information from the current
59 ;; buffer (C-c C-u).
60 ;; * Significantly improved performance of completion and WML checking.
61 ;; * Improved performance for inserting missing tags.
62 ;; * Fixed a bug where #ifdef was never matched when checking WML.
63 ;; * Added completion for preprocessor statements.
64 ;; * Improved macro completion and checking.
65 ;; 1.3.0
66 ;; * Added support for Xemacs.
67 ;; * WML checking is now context sensitive; checks attributes and macros.
68 ;; * WML checks are now always performed on the entire buffer, with results
69 ;; displayed in a temporary buffer.
70 ;; * Context-sensitive completion for attributes and tags.
71 ;; * Completion for built-in and project-specific macros.
72 ;; * Changed the following bindings:
73 ;; `wesnoth-insert-tag' - C-c e -> C-c t
74 ;; `wesnoth-jump-to-matching' - C-c m -> C-c o
75 ;; `wesnoth-check-structure' -> `wesnoth-check-wml' - C-c c
76 ;; * Added the following bindings:
77 ;; `wesnoth-complete-attribute' - C-c a
78 ;; `wesnoth-complete-macro' - C-c m
79 ;; `wesnoth-complete-tag' - C-c t
80 ;; * Removed the following bindings:
81 ;; `wesnoth-check-tag-names' - C-c n
82 ;; * Removed `wesnoth-check-tag-names'. Replaced by `wesnoth-check-wml'.
83 ;; * Completion for an incomplete attribute, tag, or macro at point is
84 ;; attempted via TAB.
85 ;; 1.2.5
86 ;; * Fixed support for GNU Emacs 21.
87 ;; * Added several new tags to `wesnoth-tags-list'.
88 ;; * Added M-TAB binding for `wesnoth-insert-tag'.
89 ;; * `wesnoth-insert-tag' now takes an optional numeric argument indicating
90 ;; how many blocks to wrap across instead of a region.
91 ;; * Support for `wesnoth-indent-preprocessor-bol' removed.
92 ;; * Fixed a bug in `wesnoth-insert-tag' and `wesnoth-insert-missing-closing'
93 ;; causing tags not to be inserted in the correct position.
94 ;; * Fixed highlighting of array indexes as tags.
95 ;; 1.2.4
96 ;; * Improved syntax-highlighting for macro calls.
97 ;; * Underscore is now treated as whitespace.
98 ;; * Fixed incorrect indentation when preprocessor preceeded by whitespace.
99 ;; * Point is now placed at the first non-whitespace character of the line,
100 ;; instead of the last.
101 ;; * Corrected minor indentation bugs.
102 ;; * Indenting across large regions is now much more efficient.
103 ;; * Fix hooks modifying wesnoth-mode-map causing default bindings not being
104 ;; applied.
105 ;; 1.2.3
106 ;; * Now compatible with GNU Emacs 21.4.
107 ;; * Added support for several new tags.
108 ;; * Added menu entry for wesnoth-mode.
109 ;; * Significant speed increase to indentation.
110 ;; * Indentation can now be customised using `wesnoth-indent-preprocessor-bol'
111 ;; and `wesnoth-indent-savefile'; support for `wesnoth-indentation-function'
112 ;; has been removed.
113 ;; * Trailing whitespace is no longer created when creating a second
114 ;; consecutive newline.
115 ;; * Spurious newlines are no longer created when inserting a tag elements
116 ;; around a region.
117 ;; 1.2.2
118 ;; * Added functions: `wesnoth-indent', `wesnoth-element-closing',
119 ;; `wesnoth-element', `wesnoth-element-opening',
120 ;; `wesnoth-insert-and-indent', `wesnoth-insert-missing-closing'.
121 ;; * Renamed `wesnoth-indent-line-default', `wesnoth-indent-line-savefile' and
122 ;; `wesnoth-jump-backward', `wesnoth-jump-forward' to
123 ;; `wesnoth-indent-withtags-inline', `wesnoth-indent-default-inline' and
124 ;; `wesnoth-backward-tag', `wesnoth-forward-tag', respectively.
125 ;; * Fixed a bug in indentation where content was needed between elements pairs
126 ;; for indentation to work.
127 ;; * Fixed `wesnoth-newline-and-indent' ignoring the state of
128 ;; `wesnoth-auto-indent-flag'.
129 ;; * Fixed `{...}' and `#endif' not font-locking correctly.
130 ;; * Added indentation styles: `wesnoth-indent-default',
131 ;; `wesnoth-indent-withtags' which implement a a similar indentation
132 ;; style to the existing styles, however all preprocessor statements are
133 ;; indented to the first column.
134 ;; * Added support for several new tags.
135 ;; * Modified `wesnoth-newline' to behave more consistently.
136 ;; * `wesnoth-jump-to-matching', `wesnoth-forward-tag', `wesnoth-backward-tag'
137 ;; now leaves point at the beginning (when moving backward) or end (when
138 ;; moving forward) of the match.
139 ;; * `wesnoth-jump-to-matching' now attempts to find a target if necessary and
140 ;; will now work on preprocessor statements. Will now warn if jump
141 ;; destination may not be correct (due to errors in WML structure).
142 ;; * Indentation style is now determined by `wesnoth-indentation-function'.
143 ;; * `wesnoth-check-structure' can now be applied over an active region and
144 ;; now checks preprocessor statements for correct nesting.
145 ;; * `wesnoth-newline' and `wesnoth-newline-and-indent' can now be forced to
146 ;; perform indentation by providing a prefix argument.
147 ;; * Indentation styles now leave point at the first non-whitespace character
148 ;; of the line.
149 ;; * `wesnoth-check-tag-names' now reports on success.
150 ;; * `wesnoth-insert-tag' is now able to insert tags around a region.
151 ;; * `outline-minor-mode' now works on macro definitions.
152 ;; 1.2.1
153 ;; * Base indent now defaults to 4.
154 ;; * Added support for #ifndef.
156 ;;; Code:
157 (require 'easymenu)
158 (require 'wesnoth-update)
159 (require 'wesnoth-wml-data)
161 (defconst wesnoth-mode-version "1.3.2"
162 "The current version of `wesnoth-mode'.")
164 (defgroup wesnoth-mode nil "Wesnoth-mode access"
165 :group 'languages
166 :prefix "wesnoth-")
168 (defcustom wesnoth-auto-indent-flag t
169 "Non-nil means indent the current line upon creating a newline."
170 :type 'boolean
171 :group 'wesnoth-mode)
173 (defcustom wesnoth-indent-savefile t
174 "Non-nil means to use the current indentation conventions.
175 If nil, use the old convention for indentation.
176 The current convention is all attributes are indented a level deeper
177 than their parent; in the past attributes were indented to the same
178 level as their parent.")
180 (defcustom wesnoth-base-indent 4
181 "The number of columns to indent WML."
182 :type 'integer
183 :group 'wesnoth-mode)
185 (defconst wesnoth-preprocessor-regexp
186 "[\t ]*#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def \\)"
187 "Regular expression to match all preprocessor statements.")
189 (defconst wesnoth-preprocessor-opening-regexp
190 "[\t ]*#\\(define \\|else\\|ifdef \\|ifndef \\)"
191 "Regular expression to match \"opening\" preprocessor statements.")
193 (defconst wesnoth-preprocessor-closing-regexp
194 "[\t ]*#\\(end\\(\\(de\\|i\\)f\\)\\)"
195 "Regular expression to match \"closing\" preprocessor statements.")
197 (defvar wesnoth-define-blocks '()
198 "Cache of all toplevel #define and #enddef pairs.")
200 (defvar wesnoth-history-list '()
201 "History of inserted WML elements.")
203 (defvar wesnoth-mode-hook nil)
205 (defface wesnoth-warning-face
206 '((t (:underline "tomato1")))
207 "Face to use for warnings in wesnoth-mode"
208 :group 'wesnoth-mode)
210 (defvar wesnoth-mode-map
211 (let ((map (make-sparse-keymap)))
212 (define-key map (kbd "C-M-a") 'wesnoth-backward-element)
213 (define-key map (kbd "C-M-e") 'wesnoth-forward-element)
214 (define-key map (kbd "C-m") 'wesnoth-newline)
215 (define-key map (kbd "C-j") 'wesnoth-newline-and-indent)
216 (define-key map (kbd "C-c C-c") 'wesnoth-check-wml)
217 (define-key map (kbd "C-c C-a") 'wesnoth-complete-attribute)
218 (define-key map (kbd "C-c C-t") 'wesnoth-complete-tag)
219 (define-key map (kbd "C-c C-p") 'wesnoth-complete-preprocessor)
220 (define-key map (kbd "C-c C-u") 'wesnoth-update-project-information)
221 (define-key map (kbd "M-TAB") 'wesnoth-complete-tag)
222 (define-key map (kbd "C-c C-m") 'wesnoth-complete-macro)
223 (define-key map (kbd "C-c C-o") 'wesnoth-jump-to-matching)
224 (define-key map (kbd "C-c C-f") 'wesnoth-forward-warning)
225 (define-key map (kbd "C-x `") 'wesnoth-forward-warning)
226 (define-key map (kbd "C-c C-b") 'wesnoth-backward-warning)
227 (define-key map (kbd "C-c C-/") 'wesnoth-insert-missing-closing)
228 (define-key map (kbd "TAB") 'wesnoth-indent-or-complete)
229 map)
230 "Keymap used in `wesnoth-mode'.")
232 (easy-menu-define wesnoth-menu wesnoth-mode-map "Menu for wesnoth-mode"
233 '("WML"
234 ["Check WML" wesnoth-check-wml t]
235 ["Indent or Complete" wesnoth-indent-or-complete t]
236 ["Indent buffer" (lambda ()
237 (interactive)
238 (wesnoth-indent-region (point-min) (point-max))) t]
239 ["Insert Tag" wesnoth-complete-tag t]
240 ["Insert Attribute" wesnoth-complete-attribute t]
241 ["Insert Macro" wesnoth-complete-macro t]
242 ["Insert Preprocessor" wesnoth-complete-preprocessor t]
243 ["Insert Missing Tag" wesnoth-insert-missing-closing t]
244 ["Jump to Matching" wesnoth-jump-to-matching t]
245 ["Update Macros" wesnoth-update-project-information t]))
247 (defvar wesnoth-syntax-table
248 (let ((wesnoth-syntax-table (make-syntax-table)))
249 (modify-syntax-entry ?= "." wesnoth-syntax-table)
250 (modify-syntax-entry ?_ "_" wesnoth-syntax-table)
251 (modify-syntax-entry ?- "_" wesnoth-syntax-table)
252 (modify-syntax-entry ?. "_" wesnoth-syntax-table)
253 (modify-syntax-entry ?\n ">" wesnoth-syntax-table)
254 (modify-syntax-entry ?\r ">" wesnoth-syntax-table)
255 wesnoth-syntax-table)
256 "Syntax table for `wesnoth-mode'.")
258 ;; Prevents automatic syntax-highlighting of elements which might be
259 ;; pre-processor statements.
260 (defvar wesnoth-syntactic-keywords
261 (list
262 '("\\([\t ]*\\(#\\(?:define \\|e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\|\\(?:ifn?\\|un\\)def \\)\\)\\)" 1 "w")
263 '("\\(#[\t ]*.*$\\)" 1 "<"))
264 "Highlighting syntactic keywords within `wesnoth-mode'.")
266 (defvar wesnoth-font-lock-keywords
267 (list
268 '("#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)" . font-lock-keyword-face)
269 '("\\(#e\\(?:lse\\|nd\\(?:\\(?:de\\|i\\)f\\)\\)\\)" .
270 font-lock-keyword-face)
271 '("\\(#\\(?:define\\|\\(?:ifn?\\|un\\)def\\)\\)[\t ]+\\(\\(\\w\\|_\\)+\\)"
272 2 font-lock-function-name-face)
273 '("\\({[@~]?\\(\\w\\|\\.\\|/\\|-\\)+}\\)" (1 font-lock-function-name-face))
274 '("\\({\\(\\w\\|:\\|_\\)+\\|{[~@]?\\)" (1 font-lock-function-name-face))
275 '("}" . font-lock-function-name-face)
276 '("[\t ]*\\(\\[/?[^$]\\(\\w\\|_\\)+\\]\\)" 1 font-lock-type-face)
277 '("\\$\\(\\w\\|_\\)+" . font-lock-variable-name-face)
278 '("\\(\\(\\w\\|_\\)+\\(\\,[\t ]*\\(\\w\\|_\\)+\\)*\\)="
279 1 font-lock-variable-name-face))
280 "Syntax highlighting for `wesnoth-mode'.")
282 (defun wesnoth-element-closing (&optional limited)
283 "Return the regexp to match a closing element.
284 If LIMITED is non-nil, return a regexp which matches only the
285 #enddef preprocessor."
286 (concat "^[\t ]*\\(\\[/\\(\\w\\|_\\)+\\|"
287 (if limited
288 "#enddef"
289 "#end\\(?:def\\|if\\)")
290 "\\)"))
292 (defun wesnoth-element-opening (&optional limited)
293 "Return the regexp to match a closing element.
294 If LIMITED is non-nil, return a regexp which matches only the
295 #define preprocessor."
296 (concat "^[\t ]*\\(\\[\\+?\\(\\w\\|_\\)+\\]\\|#define "
297 (if limited
298 "{FOREACH .+}"
299 "\\|#ifn?def ")
300 "\\)"))
302 (defun wesnoth-find-next (type)
303 "Find the next element of TYPE.
304 TYPE is a symbol representing an element type, or a list of
305 element types to find."
306 (let ((element (wesnoth-next-element)))
307 (while (and element (if (listp type)
308 (not (member (car element) type))
309 (not (eq (car element) type))))
310 (setq element (wesnoth-next-element)))
311 (when (if (listp type)
312 (member (car element) type)
313 (eq (car element) type))
314 element)))
316 (defun wesnoth-element (&optional limited)
317 "Return the regexp to match a closing element.
318 If LIMITED is non-nil, return a regexp which matches only the
319 #define and #enddef preprocessors."
320 (concat "^[\t ]*\\(\\[[/+]?\\(\\w\\|_\\)+\\]?\\|"
321 (if limited
322 "#define \\|#enddef"
323 (substring wesnoth-preprocessor-regexp 5))
324 "\\)"))
326 (defun wesnoth-next-element ()
327 "Move to the next element in the buffer.
328 Return non-nil when an element is found. Otherwise, return nil."
329 (interactive)
330 (save-match-data
331 (and (or (eolp) (looking-at "[}\t ]"))
332 (search-forward-regexp "[^}
333 \t ]" (point-max) t)
334 (forward-char -1)))
335 (let ((details (wesnoth-element-type (point))))
336 (save-match-data
337 (when (nth 2 details)
338 (goto-char (nth 2 details))
339 (while (nth 3 (parse-partial-sexp
340 (save-excursion (search-backward-regexp
341 (wesnoth-element t) (point-min) t)
342 (point))
343 (point)))
344 (search-forward "\"" (point-max) t))))
345 details))
347 (defun wesnoth-element-type (point)
348 "Return details regarding the element at POINT.
349 A list is returned, the elements of the list represent the
350 following, respectively: A symbol representing the type of
351 element; the position of the start of the element and the
352 position of the end of the element. POINT must be at the start
353 of the element."
354 (let ((element-matches
355 '(("{\\(.*?[/\]\\)+}" . nil) ;; pathnames
356 ("{\\(\\w\\|_\\)+" . macro)
357 ("\\[\\+?[^/]+?\\]" . tag-opening)
358 ("\\[/.+?\\]" . tag-closing)
359 ("\\(\\w\\|_\\)+[\t ]*=" . attribute)
360 ("#\\(enddef\\|define \\|e\\(lse\\|nd\\(\\(de\\|i\\)f\\)\\)\\|\\(ifn?\\|un\\)def \\)" . preprocessor)
361 ("#.*$" . comment)
362 ("[^\t\n |]+") . nil)))
363 (catch 'result
364 (dolist (pair element-matches)
365 (when (looking-at (car pair))
366 (throw 'result (list (cdr pair)
367 (match-beginning 0)
368 (match-end 0))))))))
370 (defun wesnoth-estimate-element-type (point)
371 "Return match data for a partial element at POINT."
372 (save-excursion
373 (goto-char (point))
374 (let ((element-matches
375 '(("{\\(.*?[/\]\\)+$" . nil) ;; pathnames
376 ("{\\(\\w\\|_\\)*$" . macro)
377 ("\\[/\\(\\w\\|_\\)*$" . tag-closing)
378 ("\\[\\+?\\(\\w\\|_\\)*$" . tag-opening)
379 ("^[\t ]*\\(\\w\\|_\\)+$" . attribute)
380 ("^[\t ]*#\\w*$" . preprocessor))))
381 (catch 'result
382 (dolist (pair element-matches)
383 (when (looking-at (car pair))
384 (throw 'result (list (cdr pair)
385 (match-beginning 0)
386 (match-end 0)))))))))
388 (defun wesnoth-guess-element-type (point &optional bound)
389 "Return details for the the element near POINT.
390 Locate the start of the element before determining details.
391 BOUND is the limit to search backwards."
392 (save-excursion
393 (unless bound (setq bound (save-excursion
394 (beginning-of-line)
395 (point))))
396 (let ((details (wesnoth-estimate-element-type (point))))
397 (unless (< (point) bound)
398 (if (null (car details))
399 (progn
400 (forward-char -1)
401 (wesnoth-guess-element-type point bound))
402 (when (and (nth 1 details)
403 (>= point (nth 1 details))
404 (nth 2 details)
405 (<= point (nth 2 details)))
406 details))))))
409 ;;; Insertion and completion
410 (defmacro wesnoth-element-completion (completions prompt partial
411 &optional completep)
412 "Process completion of COMPLETIONS, displaying PROMPT.
413 PARTIAL is the partial string on which to attempt completion.
414 If COMPLETEP is non-nil, do not prompt if no completion is found."
415 `(let* ((element (when ,partial (try-completion ,partial ,completions))))
416 (cond ((eq element t)
417 ,partial)
418 ((and completep (null element))
419 nil)
420 ((and element (eq (try-completion element ,completions) t))
421 element)
422 ((> (length (all-completions (or element "") ,completions)) 1)
423 (completing-read ,prompt ,completions
424 nil nil element
425 'wesnoth-history-list))
427 element))))
429 (defun wesnoth-parent-tag ()
430 "Return the name of the parent tag.
431 If the parent is a preprocessor statement, return non-nil.
432 If the element does not have a parent, return nil.
433 Otherwise, return a string containing the name of the parent tag."
434 (save-excursion
435 (let ((start-point (point))
436 (depth 1))
437 (when (save-excursion (> (point) (progn (back-to-indentation)
438 (point))))
439 (end-of-line))
440 (while (and (> depth 0)
441 (search-backward-regexp (wesnoth-element t)
442 (point-min) t))
443 (if (string-match "[\t ]*\\[/" (match-string 0))
444 (setq depth (1+ depth))
445 (setq depth (1- depth))))
446 (beginning-of-line)
447 (if (> depth 0)
449 (when (looking-at (wesnoth-element-opening))
450 (let ((parent (match-string-no-properties 1)))
451 (if (or (string-match wesnoth-preprocessor-opening-regexp parent)
452 ;; Check if we're immediately within a macro
453 (and (goto-char start-point)
454 (search-backward-regexp "[}{]" (point-min) t)
455 (string= (match-string 0) "{")
456 (goto-char start-point)
457 (not (and (search-backward parent (point-min) t)
458 (search-backward-regexp "[}{]" (point-min) t)
459 (string= (match-string 0) "{")))))
461 (substring parent 1 (1- (length parent))))))))))
463 (defun wesnoth-partial-macro-p ()
464 "Return non-nil if point is in a partial macro."
465 (save-excursion
466 (let ((opened 0))
467 (search-backward-regexp "{" (point-min) t)
468 (while (search-forward-regexp "[{}]" (point-max) t)
469 (if (string= (match-string 0) "{")
470 (setq opened (1+ opened))
471 (setq opened (1- opened))))
472 (> opened 0))))
474 (defun wesnoth-indent-or-complete (&optional elements)
475 "Indent or complete the line at point, depending on context.
476 ELEMENTS is the number of elements to wrap around if inserting
477 matching tags."
478 (interactive "P")
479 (or elements (setq elements 0))
480 (let ((details (wesnoth-guess-element-type (point))))
481 (cond
482 ((eq (car details) 'tag-opening)
483 (wesnoth-complete-tag elements t))
484 ((and (eq (car details) 'macro)
485 (wesnoth-partial-macro-p))
486 (wesnoth-complete-macro t))
487 ((eq (car details) 'preprocessor)
488 (wesnoth-complete-preprocessor elements t))
489 ((eq (car details) 'tag-closing)
490 (and (wesnoth-insert-missing-closing)
491 (delete-region (nth 1 details) (save-excursion
492 (beginning-of-line)
493 (point))))
494 (end-of-line))
495 ((eq (car details) 'attribute)
496 (wesnoth-complete-attribute t))
498 (wesnoth-indent)))))
500 (defun wesnoth-preprocessor-closed-p (preprocessor)
501 "Determine whether PREPROCESSOR has been closed.
502 PREPROCESSOR is a string matching the preprocessor statement to
503 be inserted."
504 (save-excursion
505 (back-to-indentation)
506 (wesnoth-jump-to-matching preprocessor)
507 (looking-at
508 (if (string= preprocessor "#define ")
509 "#enddef"
510 "#endif"))))
512 (defun wesnoth-complete-preprocessor (&optional elements completep)
513 "Complete and insert the preprocessor at point.
514 ELEMENTS is the number of elements to wrap around.
515 If COMPLETEP is non-nil, attempt to complete preprocessor at point."
516 (interactive "P")
517 (or elements (setq elements 0))
518 (let* ((completions (wesnoth-emacs-completion-formats
519 '("define" "else" "ifdef" "ifndef"
520 "enddef" "endif" "undef")))
521 (partial (when completep
522 (save-excursion
523 (back-to-indentation)
524 (when (looking-at "#\\(\\w*\\)$")
525 (match-string-no-properties 1)))))
526 (preprocessor (wesnoth-element-completion
527 completions "Preprocessor: " partial completep))
528 (closedp
529 (save-excursion
530 (when preprocessor
531 (unless (string= "#" (substring preprocessor 0 1))
532 (setq preprocessor (concat "#" preprocessor)))
533 (when (string-match "#\\(define\\|ifn?def\\|undef\\)" preprocessor)
534 (setq preprocessor (concat preprocessor " ")))
535 (when partial
536 (delete-region
537 (save-excursion
538 (progn (search-backward
540 (save-excursion (back-to-indentation)
541 (point))
543 (point)))
544 (point)))
545 (wesnoth-preprocessor-closed-p preprocessor)))))
546 (when preprocessor
547 (when partial
548 (delete-region
549 (save-excursion
550 (progn (search-backward
551 "#" (save-excursion (back-to-indentation)
552 (point))
554 (point)))
555 (point)))
556 (if (and (string-match "#\\(define \\|ifn?def\\)" preprocessor)
557 (not closedp))
558 (progn
559 (wesnoth-insert-tag elements preprocessor)
560 (forward-line -1)
561 (end-of-line))
562 (wesnoth-insert-element-separately preprocessor)))))
564 (defun wesnoth-macro-arguments ()
565 "Find any current macro arguments."
566 (let ((results '())
567 (depth (wesnoth-within-define (point))))
568 (save-excursion
569 (while (> depth 0)
570 (save-match-data
571 (search-backward-regexp
572 "[\t ]*#define \\(?:\\w+\\|_\\)*\\(\\([\t ]*\\(\\w\\|_\\)+\\)*\\)"
573 (point-min) t)
574 (when (<= (wesnoth-within-define (point)) depth)
575 (and (> depth 0)
576 (setq results
577 (append (mapcar (lambda (macro)
578 (list macro nil))
579 (split-string
580 (match-string-no-properties 1)))
581 results)))
582 (setq depth (1- depth)))))
583 results)))
585 (defun wesnoth-complete-macro (&optional completep)
586 "Complete and insert the macro at point.
587 If COMPLETEP is non-nil, attempt to complete the macro at point."
588 (interactive)
589 (wesnoth-update-project-information)
590 (let* ((macro-information (append (wesnoth-macro-arguments)
591 wesnoth-macro-data
592 wesnoth-local-macro-data))
593 (completions (wesnoth-emacs-completion-formats
594 (mapcar 'car macro-information)))
595 (details (wesnoth-guess-element-type (point)))
596 (partial (when
597 (save-excursion
598 (and completep
599 (eq (car details) 'macro)
600 (goto-char (cadr details))
601 (looking-at "{\\(\\(\\w\\|_\\)*\\)")))
602 (match-string-no-properties 1)))
603 (macro (wesnoth-element-completion completions "Macro: " partial
604 completep))
605 (args (cadr (assoc macro macro-information))))
606 (when macro
607 (if partial
608 (progn
609 ;; Delete the region corresponding to the current macro.
610 (delete-region (nth 1 details) (nth 2 details))
611 (insert "{" macro (if args " }" "}")))
612 (wesnoth-insert-element-separately "{" macro (if args " }" "}")))
613 (save-excursion
614 (wesnoth-indent))
615 (forward-char -1)
616 (when args
617 (let ((input (read-string (concat (car args) ": "))))
618 (insert input (if (string= input "") "" " "))
619 (while (and (setq args (cdr args)) (not (string= input "")))
620 (insert (setq input (read-string (concat (car args) ": ")))
621 (if (and (not (string= input ""))
622 (cdr args)) " " "")))))
623 (when (null args) (forward-char 1)))))
625 (defun wesnoth-complete-attribute (&optional completep)
626 "Insert the attribute at point.
627 If COMPLETEP is non-nil, attempt to complete the attribute at point."
628 (interactive)
629 (let* ((completions (wesnoth-build-completion 1))
630 (details (save-excursion
631 (back-to-indentation)
632 (wesnoth-guess-element-type (point))))
633 (partial (when completep
634 (when (save-excursion
635 (back-to-indentation)
636 (looking-at "\\(\\(\\w\\|_\\)+\\)"))
637 (match-string-no-properties 1))))
638 (attribute (wesnoth-element-completion completions "Attribute: "
639 partial completep)))
640 (when attribute
641 (if partial
642 (progn
643 (delete-region (nth 1 details) (nth 2 details))
644 (insert attribute "="))
645 (wesnoth-insert-element-separately attribute
646 (if (string-match "=" attribute)
648 "=")))
649 (save-excursion
650 (wesnoth-indent)))))
652 (defun wesnoth-complete-tag (&optional elements completep)
653 "Complete and insert the tag at point.
654 ELEMENTS is the number of elements to wrap around.
655 If COMPLETEP is non-nil, attempt to complete tag at point."
656 (interactive "P")
657 (or elements (setq elements 0))
658 (let* ((completions (wesnoth-build-completion 0))
659 (details (wesnoth-guess-element-type (point)))
660 (partial (save-excursion
661 (when (and completep
662 (eq (car details) 'tag-opening)
663 (goto-char (cadr details))
664 (looking-at "\\[\\(\\(\\w\\|_\\)*\\)[\t ]*$"))
665 (match-string-no-properties 1))))
666 (tag (wesnoth-element-completion completions "Tag: " partial
667 completep))
668 (closedp
669 (save-excursion
670 (wesnoth-jump-to-matching (concat "[" tag "]"))
671 (back-to-indentation)
672 (and (looking-at "\\[/\\(\\(\\w\\|_\\)+\\)")
673 (string= tag (match-string 1))))))
674 (if tag
675 (progn
676 (if completep
677 (progn
678 (delete-region (nth 1 details) (nth 2 details))
679 (if closedp
680 (progn
681 (wesnoth-insert-and-indent "[" tag "]")
682 (end-of-line))
683 (wesnoth-insert-tag elements tag)))
684 (wesnoth-insert-tag elements tag)))
685 (or completep (wesnoth-insert-tag elements)))))
687 (defun wesnoth-build-completion (position)
688 "Create a new list for tag completion if necessary.
689 Rebuilding list is required for versions of GNU Emacs earlier
690 than 22. POSITION is the argument passed to `nth' for
691 `wesnoth-tag-data'."
692 (interactive "P")
693 (let ((parent (wesnoth-parent-tag)))
694 (wesnoth-emacs-completion-formats
695 (if (or (stringp parent) (null parent))
696 (nth position (gethash parent wesnoth-tag-hash-table))
697 (mapcar 'car wesnoth-tag-data)))))
699 (defun wesnoth-emacs-completion-formats (candidates)
700 "Return the completions in the correct format for `emacs-major-version'.
701 CANDIDATES is a list of all possible completions."
702 (if (> emacs-major-version 21)
703 candidates
704 (let ((tags '())
705 (iter 0))
706 (dolist (tag candidates)
707 (setq iter (1+ iter))
708 (setq tags (append tags (list (cons tag iter)))))
709 tags)))
711 (defun wesnoth-insert-tag (&optional elements tagname)
712 "Insert the specified opening tag and it's matching closing tag.
713 Both the opening and closing tags will be placed on their own
714 lines with point positioned between them. Completion of tags at
715 the prompt uses `wesnoth-tags-list'.
717 ELEMENTS is specifies the number of following blocks which the
718 tag should wrap around.
720 TAGNAME is the name of the tag to be inserted."
721 (interactive "Ps")
722 (unless tagname
723 (setq tagname (completing-read "Tag: " (wesnoth-build-completion 1)
724 nil nil nil 'wesnoth-history-list)))
725 (when (or (not elements)
726 (looking-at (concat "[\t ]*\\(:?\\[/\\|"
727 wesnoth-preprocessor-regexp "\\)")))
728 (setq elements 0))
729 (let ((start (save-excursion (forward-line -1) (point)))
730 (end (unless (= elements 0)
731 ;; Work around some strange behaviour when the target is at the
732 ;; end of the buffer.
733 (save-excursion
734 (goto-char (point-max))
735 (beginning-of-line)
736 (unless (looking-at "^[\t ]*$")
737 (end-of-line)
738 (newline)))
739 (wesnoth-nth-pair-position elements))))
740 (if (string-match wesnoth-preprocessor-regexp tagname)
741 (wesnoth-insert-element-separately tagname)
742 (wesnoth-insert-element-separately "[" tagname "]"))
743 (save-excursion
744 (if end
745 (goto-char (marker-position end))
746 (newline (if (string-match wesnoth-preprocessor-regexp tagname) 1 2)))
747 (if (string-match wesnoth-preprocessor-opening-regexp tagname)
748 (wesnoth-insert-element-separately
749 (if (string= tagname "#define ")
750 "#enddef"
751 "#endif"))
752 (wesnoth-insert-element-separately "[/" tagname "]"))
753 (indent-region start (point) nil))
754 (unless end
755 (forward-line 1)))
756 (wesnoth-indent))
758 (defun wesnoth-insert-element-separately (&rest strings)
759 "Concatenate STRINGS and insert them on a line of their own."
760 (if (save-excursion (and (> (point) (progn (back-to-indentation) (point)))))
761 (if (save-excursion (forward-line 1) (looking-at "^[\t ]*$"))
762 (progn
763 (forward-line 1)
764 (end-of-line))
765 (end-of-line)
766 (newline))
767 (beginning-of-line)
768 (if (looking-at "^[\t ]*$")
769 (end-of-line)
770 (open-line 1)))
771 (insert (apply 'concat strings)))
773 (defun wesnoth-insert-missing-closing (&optional start end)
774 "Insert the next expected closing element at point.
776 START and END define the region to check for missing closing
777 elements. If function `transient-mark-mode' is enabled, the region
778 specified will be used as START and END. Otherwise, START and
779 END will be the minimum and current positions of the buffer,
780 respectively."
781 (interactive)
782 (if (and (boundp 'transient-mark-mode)
783 (symbol-value 'transient-mark-mode)
784 (symbol-value 'mark-active))
785 (setq start (region-beginning)
786 end (copy-marker (region-end)))
787 (setq start (point-min)
788 end (point-max)))
789 (let ((element (wesnoth-check-structure start end)))
790 (cond ((not element)
791 (message "%s" "Unable to find element to insert")
792 nil)
793 ((string= element "Unexpected end of file")
794 (message "%s" element)
795 nil)
797 (wesnoth-insert-element-separately element)
798 (wesnoth-indent)
799 (end-of-line)
800 t))))
802 (defun wesnoth-insert-and-indent (&rest args)
803 "Concatenate and insert the given string(s) before indenting.
805 ARGS is a list of strings to be inserted."
806 (insert (apply 'concat args))
807 (wesnoth-indent))
809 (defun wesnoth-newline (&optional indent)
810 "Indent both the current line and the newline created.
811 If `wesnoth-auto-indent-flag' is nil, indentation will not be
812 performed. Indentation can be forced by setting INDENT to
813 non-nil."
814 (interactive "P")
815 (newline)
816 (save-excursion
817 (forward-line -1)
818 (when (and (or wesnoth-auto-indent-flag indent)
819 (not (looking-at "^[\t ]*$")))
820 (wesnoth-indent))))
822 ;;; Movement
823 (defmacro wesnoth-navigate-element (repeat search-function bound)
824 "Move point to the tag in the given direction REPEAT times.
826 SEARCH-FUNCTION is the symbol of the function for searching in
827 the required direction, with BOUND marking the furthest point to
828 search."
829 `(progn
830 (or ,repeat (setq ,repeat 1))
831 (while (> ,repeat 0)
832 (and (eq ,search-function 'search-forward-regexp) (end-of-line))
833 (funcall ,search-function (wesnoth-element-opening) ,bound t)
834 (back-to-indentation)
835 (setq repeat (1- ,repeat)))))
837 (defun wesnoth-nth-pair-position (count)
838 "Return `point' after COUNT number of matching element pairs.
839 COUNT is a positive number representing the number of balanced
840 pairs to move across.
841 `point' is returned as a marker object."
842 (save-excursion
843 (let ((failed nil))
844 (if (> (point) (save-excursion (back-to-indentation) (point)))
845 (end-of-line)
846 (beginning-of-line))
847 (while (> count 0)
848 ;; Currently looking-at target tag. Stop here to avoid
849 ;; incorrect nesting.
850 (unless (wesnoth-search-for-matching-tag
851 'search-forward-regexp (wesnoth-element-closing) 'point-max)
852 (setq count 0)
853 (setq failed t))
854 (and (> (setq count (1- count)) 0) (forward-line 1)))
855 (if failed
856 (beginning-of-line)
857 (end-of-line))
858 (point-marker))))
860 (defun wesnoth-forward-element (repeat)
861 "Move point to the end of the next tag.
862 REPEAT is an optional numeric argument. If REPEAT is non-nil,
863 jump forward the specified number of tags."
864 (interactive "p")
865 (if (< repeat 0)
866 (wesnoth-backward-element (abs repeat))
867 (wesnoth-navigate-element repeat 'search-forward-regexp (point-max))))
869 (defun wesnoth-backward-element (repeat)
870 "Move point to the beginning of the previous tag.
871 REPEAT is an optional numeric argument. If REPEAT is non-nil,
872 jump backward the specified number of tags."
873 (interactive "p")
874 (if (< repeat 0)
875 (wesnoth-forward-element (abs repeat))
876 (wesnoth-navigate-element repeat 'search-backward-regexp (point-min))))
878 (defmacro wesnoth-search-for-matching-tag (search-function
879 search-string bound &optional skip)
880 "Search for the matching tag for the current line.
881 SEARCH-FUNCTION is the name of the function used to perform the search.
882 SEARCH-STRING is a string representing the matching tag type.
883 BOUND is the bound to be passed to the search function.
884 If SKIP is non-nil, skip the first element and continue from there."
885 `(let ((depth 1))
886 (when (and (or (and ,skip (forward-line 1))
887 (funcall ,search-function (wesnoth-element) (funcall ,bound) t))
888 (or ,skip (not (string-match ,search-string (match-string 0)))))
889 (while (and (> depth 0)
890 (funcall ,search-function (wesnoth-element)
891 (funcall ,bound) t))
892 (if (string-match ,search-string (match-string 0))
893 (setq depth (1- depth))
894 (setq depth (1+ depth))))
895 (= depth 0))))
897 (defun wesnoth-jump-to-matching (&optional opening)
898 "Jump point to the matching opening/closing tag.
899 OPENING is an opening preprocessor statement to attempt to find a match for."
900 (interactive)
901 (beginning-of-line)
902 (let ((target nil)
903 (first-element nil))
904 (save-excursion
905 (cond
906 ((or (and (stringp opening)
907 (string-match (wesnoth-element-opening) opening))
908 (looking-at (wesnoth-element-opening)))
909 (progn
910 (setq first-element (match-string-no-properties 0 opening))
911 (when (wesnoth-search-for-matching-tag
912 'search-forward-regexp (wesnoth-element-closing) 'point-max
913 (stringp opening))
914 (beginning-of-line)
915 (if (and (string-match wesnoth-preprocessor-opening-regexp
916 first-element)
917 (looking-at (wesnoth-element-closing)))
918 (when (string= (match-string-no-properties 0)
919 (cdr (assoc first-element
920 '(("#define " . "#enddef")
921 ("#ifndef " . "#endif")
922 ("#ifdef " . "#endif")))))
923 (setq target (point)))
924 (setq target (point))))))
925 ((looking-at (wesnoth-element-closing))
926 (end-of-line)
927 (setq first-element (match-string-no-properties 0))
928 (when (wesnoth-search-for-matching-tag
929 'search-backward-regexp (wesnoth-element-opening)
930 'wesnoth-wml-start-pos)
931 (if (and (string-match wesnoth-preprocessor-closing-regexp
932 first-element)
933 (looking-at (wesnoth-element-opening)))
934 (progn
935 (when (or (and (string= "#enddef" first-element)
936 (string= "#define "
937 (match-string-no-properties
938 0)))
939 (and (string= "#endif" first-element)
940 (string-match
941 "#ifn?def "
942 (match-string-no-properties
943 0))))
944 (setq target (point))))
945 (setq target (point)))))
947 (search-backward-regexp (wesnoth-element-opening) (point-min) t)
948 (setq target (point)))))
949 (if target
950 (progn
951 (goto-char target)
952 (back-to-indentation))
953 (when (interactive-p)
954 (message "%s" "Tag does not appear to be matched")))))
956 ;;; Indentation
957 (defun wesnoth-wml-start-pos ()
958 "Determine the position of `point' relative to where the actual WML begins.
959 Return the likely starting position of the WML if it is found.
960 Otherwise return nil."
961 (save-excursion
962 (goto-char (point-min))
963 (when (search-forward-regexp (wesnoth-element) (point-max) t)
964 (beginning-of-line)
965 (point))))
967 (defun wesnoth-first-column-indent-p (point)
968 "Return non-nil if the current line should not be indented.
970 POINT is the position in the buffer to check.
971 CONTEXT represents the type of element which precedes the current element."
972 (or (not (wesnoth-wml-start-pos))
973 (<= (point) (wesnoth-wml-start-pos))
974 (nth 3 (parse-partial-sexp
975 (save-excursion (search-backward-regexp
976 (wesnoth-element t) (point-min) t)
977 (point))
978 point))
979 (looking-at wesnoth-preprocessor-regexp)))
981 (defun wesnoth-indent ()
982 "Indent the current line as WML."
983 (save-excursion
984 (beginning-of-line)
985 (let* ((cur-indent 0)
986 (context-data (wesnoth-determine-context (point)))
987 (context (car context-data))
988 (ref-indent (cdr context-data)))
989 (unless (wesnoth-first-column-indent-p (point))
990 (cond
991 ((eq context 'opening)
992 (if (or (and wesnoth-indent-savefile
993 (not (looking-at (wesnoth-element-closing t))))
994 (looking-at (wesnoth-element-opening t)))
995 (setq cur-indent (+ ref-indent wesnoth-base-indent))
996 (setq cur-indent ref-indent)))
997 ((eq context 'closing)
998 (if (or (looking-at "^[\t ]*\\(\\[/\\)")
999 (and (not wesnoth-indent-savefile)
1000 (not (looking-at (wesnoth-element-opening t)))))
1001 (setq cur-indent (- ref-indent wesnoth-base-indent))
1002 (setq cur-indent ref-indent)))))
1003 (indent-line-to (max cur-indent 0))))
1004 (when (> (save-excursion (back-to-indentation) (point))
1005 (point))
1006 (back-to-indentation)))
1008 (defun wesnoth-within-define (position)
1009 "Determine whether point is currently inside a #define block.
1010 POSITION is the initial cursor position."
1011 (save-match-data
1012 (let ((depth 0)
1013 (defblocks (or wesnoth-define-blocks
1014 (wesnoth-find-macro-definitions))))
1015 (unless (equal (car defblocks) 'none)
1016 (dolist (element defblocks)
1017 (when (= (cadr (sort (append (mapcar 'marker-position (cadr element))
1018 (list position)) '>)) position)
1019 (setq depth (max (car element) depth)))))
1020 depth)))
1022 (defun wesnoth-find-macro-definitions ()
1023 "Return information regarding positioning of macro definitions."
1024 (save-excursion
1025 (goto-char (point-min))
1026 (let ((depth 0)
1027 openings cache)
1028 (while (search-forward-regexp "#define\\|#enddef" (point-max) t)
1029 (and (string= (match-string 0) "#define") (beginning-of-line))
1030 (setq depth
1031 (if (string= (match-string 0) "#define")
1032 (progn
1033 (add-to-list 'openings (point-marker))
1034 (1+ depth))
1035 (if openings
1036 (progn
1037 (add-to-list 'cache
1038 (list depth (list (car openings)
1039 (point-marker))))
1040 (setq openings (cdr openings))
1041 (1- depth))
1042 depth)))
1043 (end-of-line))
1044 (or cache (list 'none)))))
1046 (defun wesnoth-indent-region (start end)
1047 "Indent the region from START to END.
1048 Creates and destroys a cache of macro definition details as necessary."
1049 (interactive "r")
1050 (unwind-protect
1051 (save-excursion
1052 (goto-char end)
1053 (setq end (point-marker))
1054 (goto-char start)
1055 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1056 (or (bolp) (forward-line 1))
1057 (while (< (point) end)
1058 (if (looking-at "^[\t ]*$")
1059 (indent-line-to 0)
1060 (funcall indent-line-function))
1061 (forward-line 1)))
1062 (setq wesnoth-define-blocks nil)))
1064 (defun wesnoth-determine-context (position)
1065 "Determine the type of the last relevant element.
1066 POSITION is the buffer position of the element for which to
1067 determine the context."
1068 (save-excursion
1069 (let* ((elements (concat (substring (wesnoth-element t)
1070 0 (- (length (wesnoth-element t)) 3))
1071 "\\|{FOREACH .+}\\|{NEXT .+}\\)"))
1072 (match (or
1073 (and (search-backward-regexp
1074 elements (point-min) t)
1075 (progn
1076 (while (save-match-data
1077 (looking-at "^[\t ]*\\[[^/].+\\]\\[/.+\\]"))
1078 (search-backward-regexp elements
1079 (point-min) t))
1081 (match-string 1))
1082 ""))
1083 (depth (wesnoth-within-define position)))
1084 (while (and (wesnoth-wml-start-pos)
1085 (> (wesnoth-within-define (point)) depth)
1086 (not (= (point) (wesnoth-wml-start-pos))))
1087 (search-backward-regexp elements
1088 (wesnoth-wml-start-pos) t)
1089 (setq match (match-string 1)))
1090 (when (and (wesnoth-wml-start-pos)
1091 (= (point) (wesnoth-wml-start-pos))
1092 (= depth 0)
1093 (string-match "#define" match))
1094 ;; Found nothing of use; reset match and assume top-level tag.
1095 (setq match ""))
1096 (cond
1097 ((string-match "\\[/\\|#enddef" match)
1098 (cons 'closing (current-indentation)))
1099 ((string-match "{NEXT " match)
1100 (cons 'closing (- (current-indentation) wesnoth-base-indent)))
1101 ((string-match "\\[[^/]?\\|#define\\|{FOREACH " match)
1102 (cons 'opening (current-indentation)))))))
1104 (defun wesnoth-newline-and-indent (&optional indent)
1105 "Indent both the current line and the newline created.
1106 If `wesnoth-auto-indent-flag' is nil, indentation will not be
1107 performed.
1109 If the optional argument, INDENT is non-nil, force indentation to
1110 be performed."
1111 (interactive)
1112 (wesnoth-newline)
1113 (when (or wesnoth-auto-indent-flag indent)
1114 (wesnoth-indent)))
1116 ;;; WML checks
1117 (defun wesnoth-check-element-type (position)
1118 "Determine the context of the element.
1119 POSITION is the position of the element in the list."
1120 (let ((parent (save-match-data (wesnoth-parent-tag))))
1121 (if (or (stringp parent) (null parent))
1122 (member (match-string-no-properties 1)
1123 (nth position (gethash parent wesnoth-tag-hash-table)))
1124 (member (match-string-no-properties 1)
1125 (mapcar 'car wesnoth-tag-data)))))
1127 ;; Provide `line-number-at-pos' implementation (not available in Emacs 21).
1128 (defun wesnoth-line-number-at-pos (&optional pos)
1129 "Return (narrowed) buffer line number at position POS.
1130 If POS is nil, use current buffer location.
1131 Counting starts at (point-min), so the value refers
1132 to the contents of the accessible portion of the buffer."
1133 (let ((opoint (or pos (point))) start)
1134 (save-excursion
1135 (goto-char (point-min))
1136 (setq start (point))
1137 (goto-char opoint)
1138 (forward-line 0)
1139 (1+ (count-lines start (point))))))
1141 (defun wesnoth-check-output (buffer format-string &rest args)
1142 "Output the string as passed to `format'.
1143 BUFFER is the buffer to output the result.
1144 FORMAT-STRING is the string as the first argument of `format'.
1145 ARGS is any additional data required by `format' to handle FORMAT-STRING."
1146 (save-excursion
1147 (let ((lnap (wesnoth-line-number-at-pos)))
1148 (set-buffer buffer)
1149 (let ((buffer-read-only nil))
1150 (insert (apply 'format (concat "Line %d: " format-string "\n")
1151 lnap args))))))
1153 (defun wesnoth-extract-macro-details (macro-arguments)
1154 "Return a list of all macros in MACRO-ARGUMENTS."
1155 (when macro-arguments
1156 (let ((results '()))
1157 (dolist (macro (split-string macro-arguments "[{}][\t ]*"))
1158 (when (string-match "^\\(\\(?:\\w\\|_\\)+\\)"
1159 macro)
1160 (add-to-list 'results (match-string-no-properties 1 macro))))
1161 results)))
1163 (defmacro wesnoth-check-process (format-string &rest args)
1164 "Output to buffer where requested and position overlays as required.
1165 FORMAT-STRING is the string to pass as the first argument to
1166 `format' for the error. ARGS is a list of arguments required by
1167 FORMAT-STRING."
1168 `(progn
1169 (wesnoth-check-output outbuf ,format-string ,@args)
1170 (wesnoth-place-overlay (match-beginning 0) (match-end 0))))
1172 (defmacro wesnoth-overlay-at-pos-p (position)
1173 "Return non-nil when there is an overlay at POSITION."
1174 `(and (overlays-at (goto-char ,position))
1175 (overlay-get (car (overlays-at (point))) 'wesnoth-error)
1176 (overlay-start (car (overlays-at (point))))))
1178 (defmacro wesnoth-locate-warning (string start end)
1179 "Search for STRING and move to the warning in the given direction.
1180 Searching starts from `point' and will wrap from START if no
1181 match was found. STRING is a form to locate the warning in the
1182 required direction. START is the start of the region searched.
1183 END is the end of the region searched."
1184 `(let ((target nil))
1185 (save-excursion
1186 (cond
1187 ((setq target (wesnoth-overlay-at-pos-p ,string)))
1188 ((setq target (wesnoth-overlay-at-pos-p ,start)))
1189 ((and (not (= (goto-char ,string) ,end))
1190 (setq target (wesnoth-overlay-at-pos-p (point)))))
1192 (message "%s" "No warnings found")
1193 nil)))
1194 target))
1196 (defun wesnoth-forward-warning ()
1197 "Move to the next warning."
1198 (interactive)
1199 (when (fboundp 'next-overlay-change)
1200 (let ((target
1201 (save-excursion
1202 (end-of-line)
1203 (wesnoth-locate-warning (next-overlay-change (point))
1204 (point-min)
1205 (point-max)))))
1206 (and target (goto-char target)))))
1208 (defun wesnoth-backward-warning ()
1209 "Move to the previous warning."
1210 (interactive)
1211 (when (fboundp 'previous-overlay-change)
1212 (let ((target
1213 (save-excursion
1214 (beginning-of-line)
1215 (wesnoth-locate-warning (1- (previous-overlay-change (point)))
1216 (point-max)
1217 (point-min)))))
1218 (and target (goto-char target)))))
1220 (defun wesnoth-place-overlay (start end)
1221 "Place overlay in the region and apply necessary properties.
1222 START is the start of the region to place the overlay. END is
1223 the end of the region to place the overlay."
1224 (when (fboundp 'overlay-put)
1225 (let ((overlay (make-overlay start end)))
1226 (overlay-put overlay 'wesnoth-error t)
1227 (overlay-put overlay 'face 'wesnoth-warning-face))))
1229 (defun wesnoth-check-wml ()
1230 "Perform context-sensitive analysis of WML-code."
1231 (interactive)
1232 (wesnoth-update-project-information)
1233 (when (fboundp 'delete-overlay)
1234 (dolist (overlay (overlays-in (point-min) (point-max)))
1235 (if (eq 'wesnoth-warning-face (overlay-get overlay 'face))
1236 (delete-overlay overlay))))
1237 (when (= 0 (hash-table-count wesnoth-tag-hash-table))
1238 (error "WML data not available; unable to generate report"))
1239 (setq wesnoth-define-blocks (wesnoth-find-macro-definitions))
1240 (let ((unmatched '())
1241 (outbuf (and (interactive-p) (get-buffer-create "*WML*")))
1242 (last-match-pos 1)
1243 (details nil)
1244 (foreach '()))
1245 (save-excursion
1246 (set-buffer outbuf)
1247 (let ((buffer (buffer-name))
1248 (buffer-read-only nil))
1249 (erase-buffer)
1250 (insert (format "Checking %s...\n" buffer))
1251 (message (format "Checking %s..." buffer))))
1252 (save-excursion
1253 (goto-char (point-min))
1254 (while (setq details (wesnoth-find-next
1255 '(tag-opening tag-closing preprocessor attribute
1256 macro)))
1257 (save-excursion
1258 (goto-char (match-beginning 0))
1259 (cond ((nth 3 (parse-partial-sexp last-match-pos (point)))
1260 nil)
1261 ((eq (car details) 'macro)
1262 (dolist (macro (save-match-data
1263 (wesnoth-extract-macro-details
1264 (match-string-no-properties 0))))
1265 (unless (assoc macro
1266 (append (wesnoth-macro-arguments)
1267 wesnoth-local-macro-data
1268 wesnoth-macro-data))
1269 (wesnoth-check-process "Unknown macro: '%s'"
1270 macro)))
1271 (save-match-data
1272 (when
1273 (looking-at
1274 "{\\(FOREACH\\|NEXT\\).*[\t ]+\\(\\(?:\\w\\|_\\)+\\)}")
1275 (if (string= (match-string-no-properties 1) "FOREACH")
1276 (setq foreach
1277 (cons (match-string-no-properties 2) foreach))
1278 (if (string= (match-string-no-properties 1) "NEXT")
1279 (progn
1280 (unless (string= (car foreach)
1281 (match-string-no-properties 2))
1282 (wesnoth-check-process
1283 (concat "NEXT does not match corresponding "
1284 "FOREACH: '%s' found; '%s' expected.")
1285 (match-string-no-properties 2)
1286 (car foreach)))
1287 (setq foreach (cdr foreach))))))))
1288 ((looking-at "[\t ]*\\[\\+?\\(\\(\\w\\|_\\)+\\)\\]")
1289 (unless (wesnoth-check-element-type 0)
1290 (wesnoth-check-process
1291 "Tag not available in this context: '%s'"
1292 (match-string-no-properties 1)))
1293 (setq unmatched (cons (match-string-no-properties 1)
1294 unmatched)))
1295 ((looking-at
1296 (concat "[\t ]*\\(#define\\|#ifdef\\|#ifndef\\|#undef\\)"
1297 "\\( \\(\\w\\|_\\)+\\)*"))
1298 (unless (match-string-no-properties 2)
1299 (wesnoth-check-process
1300 (concat "Preprocessor statement has no argument: "
1301 (match-string-no-properties 1))))
1302 (unless (string= (match-string-no-properties 1) "#undef")
1303 (setq unmatched (cons (match-string-no-properties 1)
1304 unmatched))))
1305 ((looking-at wesnoth-preprocessor-closing-regexp)
1306 (when (and unmatched
1307 (not (string-match
1308 (cdr (assoc (match-string-no-properties 1)
1309 '(("enddef" . "#define")
1310 ("endif" . "#ifn?def"))))
1311 (car unmatched))))
1312 (wesnoth-check-process
1313 "Preprocessor statement does not nest correctly"))
1314 (setq unmatched (cdr unmatched)))
1315 ((looking-at "[\t ]*\\(\\(\\w\\|_\\)+\\)=\\(.+\\)?")
1316 (unless (wesnoth-check-element-type 1)
1317 (wesnoth-check-process
1318 "Attribute not available in this context: '%s'"
1319 (match-string-no-properties 1)))
1320 (unless (match-string 3)
1321 (wesnoth-check-process
1322 "Attribute has no value")))
1323 ((looking-at "[\t ]*#else")
1324 (unless (string-match "ifn?def" (car unmatched))
1325 (if (string= (car unmatched) "#define")
1326 (wesnoth-check-process "Expecting: '%s'"
1327 (car unmatched))
1328 (wesnoth-check-process "Expecting: '[/%s]'"
1329 (car unmatched)))))
1330 ((looking-at "[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]")
1331 (when (and unmatched
1332 (not (string= (match-string-no-properties 1)
1333 (car unmatched))))
1334 (wesnoth-check-process
1335 "Expecting '%s'"
1336 (or (cdr (assoc (car unmatched)
1337 '(("#define" . "#enddef")
1338 ("#ifdef" . "#endif")
1339 ("#ifndef" . "#endif"))))
1340 (concat "[/" (car unmatched) "]"))))
1341 (setq unmatched (cdr unmatched)
1342 last-match-pos (point))))))
1343 (when foreach
1344 (dolist (var foreach)
1345 (wesnoth-check-process "Unmatched FOREACH: '%s'" var)))
1346 (when unmatched
1347 (dolist (element unmatched)
1348 (wesnoth-check-process "Unmatched element: '%s'" element))))
1349 (save-excursion
1350 (setq wesnoth-define-blocks nil)
1351 (set-buffer outbuf)
1352 (toggle-read-only t)
1353 (let ((buffer (buffer-name))
1354 (buffer-read-only nil))
1355 (display-buffer outbuf t)
1356 (let ((warnings (- (wesnoth-line-number-at-pos
1357 (save-excursion (goto-char (point-max)))) 2)))
1358 (insert (format (concat "\nCheck complete. %d warning"
1359 (if (= warnings 1) "." "s.")) warnings)))
1360 (message (format "Checking %s...done" buffer))))))
1362 (defmacro wesnoth-element-requires (element requirement &optional pop)
1363 "Process requirements for corresponding preprocessor elements.
1364 ELEMENT is the current element being tested.
1365 REQUIREMENT is the element required to exist for correct nesting.
1366 POP is an optional argument indicating the element should be
1367 removed from the list of unmatched elements."
1368 `(when (string= ,element (match-string-no-properties 1))
1369 (if (string-match ,requirement (car unmatched))
1370 (progn
1371 (and ,pop (setq unmatched (cdr unmatched)))
1373 (setq position (point)))))
1375 (defmacro wesnoth-structure-result (position element)
1376 "Process results of the structure check.
1377 POSITION is the position of the error or nil, if no error was
1378 found. ELEMENT is the last unmatched element, or nil if all
1379 opening elements have been matched."
1380 `(let ((expected nil))
1381 (when ,element
1382 (cond ((string= ,element "define ") (setq expected "#enddef"))
1383 ((string-match "ifn?def " ,element) (setq expected "#endif"))))
1384 (if (interactive-p)
1385 (if (or ,element ,position)
1386 (progn
1387 (and ,position (goto-char ,position))
1388 (message "Expecting %s" (or expected
1389 (concat "[/" ,element "]"))))
1390 (message "%s" "Structure appears consistent."))
1391 (when (or expected ,element)
1392 (or expected (concat "[/" ,element "]"))))))
1394 (defun wesnoth-check-structure (&optional start end)
1395 "Check the buffer for correct nesting of elements.
1396 If a problem is found in the structure, point will be placed at
1397 the location which an element was expected and the expected
1398 element will be displayed in the mini-buffer.
1400 START and END define the region to be checked. If
1401 function `transient-mark-mode' is enabled, the region specified will be
1402 checked. Otherwise START and END will be the minimum and maximum
1403 positions of the buffer, respectively."
1404 (interactive)
1405 (unless (or start end)
1406 (if (and (boundp 'transient-mark-mode)
1407 (symbol-value 'transient-mark-mode)
1408 (symbol-value 'mark-active))
1409 (setq start (region-beginning)
1410 end (copy-marker (region-end)))
1411 (setq start (point-min)
1412 end (point-max))))
1413 (let ((unmatched '())
1414 (position nil))
1415 (save-excursion
1416 (and start (goto-char start))
1417 (while (and (search-forward-regexp
1418 (concat "^\\([\t ]*\\[\\(/?\\(\\w\\|_\\)+\\)\\]\\|"
1419 wesnoth-preprocessor-regexp "\\)") end t)
1420 (not position))
1421 (beginning-of-line)
1422 (if (or (looking-at "^[\t ]*\\[\\(\\(\\w\\|_\\)+\\)\\]")
1423 (looking-at "[\t ]*#\\(define \\|ifdef \\|ifndef \\)"))
1424 (setq unmatched (cons (match-string-no-properties 1)
1425 unmatched))
1426 (cond
1427 ((wesnoth-element-requires "#else" "ifn?def "))
1428 ((wesnoth-element-requires "#endif" "ifn?def " t))
1429 ((wesnoth-element-requires "#enddef" "define " t))
1430 ((looking-at (concat "^[\t ]*\\[/\\(\\(\\w\\|_\\)+\\)\\]\\|"
1431 wesnoth-preprocessor-closing-regexp))
1432 (if (string= (match-string-no-properties 1)
1433 (car unmatched))
1434 (setq unmatched (cdr unmatched))
1435 (setq position (point))))))
1436 (end-of-line)))
1437 (wesnoth-structure-result position (car unmatched))))
1439 ;;; wesnoth-mode
1440 (define-derived-mode wesnoth-mode fundamental-mode "wesnoth-mode"
1441 "Major mode for editing WML."
1442 (kill-all-local-variables)
1443 (use-local-map wesnoth-mode-map)
1444 (setq major-mode 'wesnoth-mode)
1445 (setq mode-name "WML")
1446 (set-syntax-table wesnoth-syntax-table)
1447 (set (make-local-variable 'outline-regexp) "[\t ]*#define")
1448 (set (make-local-variable 'comment-start) "#")
1449 (set (make-local-variable 'indent-line-function) 'wesnoth-indent)
1450 (set (make-local-variable 'indent-region-function) 'wesnoth-indent-region)
1451 (set (make-local-variable 'font-lock-defaults)
1452 '(wesnoth-font-lock-keywords
1453 nil t nil nil
1454 (font-lock-syntactic-keywords . wesnoth-syntactic-keywords)))
1455 (setq indent-tabs-mode nil)
1456 (easy-menu-add wesnoth-menu wesnoth-mode-map)
1457 (wesnoth-create-wml-hash-table)
1458 (wesnoth-update-project-information)
1459 (run-hooks 'wesnoth-mode-hook))
1461 (provide 'wesnoth-mode)
1463 ;;; wesnoth-mode.el ends here