]> code.delx.au - gnu-emacs/blob - lisp/progmodes/antlr-mode.el
Mark face aliases with "-face" suffix as obsolete.
[gnu-emacs] / lisp / progmodes / antlr-mode.el
1 ;;; antlr-mode.el --- major mode for ANTLR grammar files
2
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007,
4 ;; 2008, 2009 Free Software Foundation, Inc.
5
6 ;; Author: Christoph.Wedler@sap.com
7 ;; Keywords: languages, ANTLR, code generator
8 ;; Version: (see `antlr-version' below)
9 ;; X-URL: http://antlr-mode.sourceforge.net/
10
11 ;; This file is part of GNU Emacs.
12
13 ;; GNU Emacs is free software: you can redistribute it and/or modify
14 ;; it under the terms of the GNU General Public License as published by
15 ;; the Free Software Foundation, either version 3 of the License, or
16 ;; (at your option) any later version.
17
18 ;; GNU Emacs is distributed in the hope that it will be useful,
19 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
20 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
21 ;; GNU General Public License for more details.
22
23 ;; You should have received a copy of the GNU General Public License
24 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
25
26 ;;; Commentary:
27
28 ;; The Emacs package ANTLR-Mode provides: syntax highlighting for ANTLR grammar
29 ;; files, automatic indentation, menus containing rule/token definitions and
30 ;; supported options and various other things like running ANTLR from within
31 ;; Emacs.
32
33 ;; For details, check <http://antlr-mode.sourceforge.net/> or, if you prefer
34 ;; the manual style, follow all commands mentioned in the documentation of
35 ;; `antlr-mode'. ANTLR is a LL(k)-based recognition tool which generates
36 ;; lexers, parsers and tree transformers in Java, C++ or Sather and can be
37 ;; found at <http://www.antlr.org/>.
38
39 ;; Bug fixes, bug reports, improvements, and suggestions for the newest version
40 ;; are strongly appreciated.
41
42 ;; To-do/Wish-list:
43 ;;
44 ;; * Next Version [C-c C-w]. Produce HTML document with syntax highlighted
45 ;; and hyper-links (using htmlize).
46 ;; * Next Version [C-c C-u]. Insert/update special comments: each rule lists
47 ;; all rules which use the current rule. With font-lock update.
48 ;; * Next Version. Make hiding much more customizable.
49 ;; * Planned [C-c C-j]. Jump to generated coding.
50 ;; * Planned. Further support for imenu, i.e., include entries for method
51 ;; definitions at beginning of grammar class.
52 ;; * Planned [C-c C-p]. Pack/unpack rule/subrule & options (one/multi-line).
53 ;;
54 ;; * Probably. Show rules/dependencies for ANT like for Makefile (does ANT
55 ;; support vocabularies and grammar inheritance?), I have to look at
56 ;; jde-ant.el: http://jakarta.apache.org/ant/manual/OptionalTasks/antlr.html
57 ;; * Probably. Make `indent-region' faster, especially in actions. ELP
58 ;; profiling in a class init action shows half the time is spent in
59 ;; `antlr-next-rule', the other half in `c-guess-basic-syntax'.
60 ;; * Unlikely. Sather as generated language with syntax highlighting etc/.
61 ;; Questions/problems: is sather-mode.el the standard mode for sather, is it
62 ;; still supported, what is its relationship to eiffel3.el? Requirement:
63 ;; this mode must not depend on a Sather mode.
64 ;; * Unlikely. Faster syntax highlighting: sectionize the buffer into Antlr
65 ;; and action code and run special highlighting functions on these regions.
66 ;; Problems: code size, this mode would depend on font-lock internals.
67
68 ;;; Installation:
69
70 ;; This file requires Emacs-20.3, XEmacs-20.4 or higher and package cc-mode.
71
72 ;; If antlr-mode is not part of your distribution, put this file into your
73 ;; load-path and the following into your ~/.emacs:
74 ;; (autoload 'antlr-mode "antlr-mode" nil t)
75 ;; (setq auto-mode-alist (cons '("\\.g\\'" . antlr-mode) auto-mode-alist))
76 ;; (add-hook 'speedbar-load-hook ; would be too late in antlr-mode.el
77 ;; (lambda () (speedbar-add-supported-extension ".g")))
78
79 ;; I strongly recommend to use font-lock with a support mode like fast-lock,
80 ;; lazy-lock or better jit-lock (Emacs-21.1+) / lazy-shot (XEmacs).
81
82 ;; To customize, use menu item "Antlr" -> "Customize Antlr".
83
84 ;;; Code:
85
86 (eval-when-compile
87 (require 'cl))
88
89 (require 'easymenu)
90
91 ;; Just to get the rid of the byte compiler warning. The code for
92 ;; this function and its friends are too complex for their own good.
93 (declare-function cond-emacs-xemacs-macfn "antlr-mode" (args &optional msg))
94
95 ;; General Emacs/XEmacs-compatibility compile-time macros
96 (eval-when-compile
97 (defmacro cond-emacs-xemacs (&rest args)
98 (cond-emacs-xemacs-macfn
99 args "`cond-emacs-xemacs' must return exactly one element"))
100 (defun cond-emacs-xemacs-macfn (args &optional msg)
101 (if (atom args) args
102 (and (eq (car args) :@) (null msg) ; (:@ ...spliced...)
103 (setq args (cdr args)
104 msg "(:@ ....) must return exactly one element"))
105 (let ((ignore (if (featurep 'xemacs) :EMACS :XEMACS))
106 (mode :BOTH) code)
107 (while (consp args)
108 (if (memq (car args) '(:EMACS :XEMACS :BOTH)) (setq mode (pop args)))
109 (if (atom args)
110 (or args (error "Used selector %s without elements" mode))
111 (or (eq ignore mode)
112 (push (cond-emacs-xemacs-macfn (car args)) code))
113 (pop args)))
114 (cond (msg (if (or args (cdr code)) (error msg) (car code)))
115 ((or (null args) (eq ignore mode)) (nreverse code))
116 (t (nconc (nreverse code) args))))))
117 ;; Emacs/XEmacs-compatibility `defun': remove interactive "_" for Emacs, use
118 ;; existing functions when they are `fboundp', provide shortcuts if they are
119 ;; known to be defined in a specific Emacs branch (for short .elc)
120 (defmacro defunx (name arglist &rest definition)
121 (let ((xemacsp (featurep 'xemacs)) reuses)
122 (while (memq (car definition)
123 '(:try :emacs-and-try :xemacs-and-try))
124 (if (eq (pop definition) (if xemacsp :xemacs-and-try :emacs-and-try))
125 (setq reuses (car definition)
126 definition nil)
127 (push (pop definition) reuses)))
128 (if (and reuses (symbolp reuses))
129 `(defalias ',name ',reuses)
130 (let* ((docstring (if (stringp (car definition)) (pop definition)))
131 (spec (and (not xemacsp)
132 (eq (car-safe (car definition)) 'interactive)
133 (null (cddar definition))
134 (cadar definition))))
135 (if (and (stringp spec)
136 (not (string-equal spec ""))
137 (eq (aref spec 0) ?_))
138 (setq definition
139 (cons (if (string-equal spec "_")
140 '(interactive)
141 `(interactive ,(substring spec 1)))
142 (cdr definition))))
143 (if (null reuses)
144 `(defun ,name ,arglist ,docstring
145 ,@(cond-emacs-xemacs-macfn definition))
146 ;; no dynamic docstring in this case
147 `(eval-and-compile ; no warnings in Emacs
148 (defalias ',name
149 (cond ,@(mapcar (lambda (func) `((fboundp ',func) ',func))
150 (nreverse reuses))
151 (t ,(if definition
152 `(lambda ,arglist ,docstring
153 ,@(cond-emacs-xemacs-macfn definition))
154 'ignore))))))))))
155 (defmacro ignore-errors-x (&rest body)
156 (let ((specials '((scan-sexps . 4) (scan-lists . 5)))
157 spec nils)
158 (if (and (featurep 'xemacs)
159 (null (cdr body)) (consp (car body))
160 (setq spec (assq (caar body) specials))
161 (>= (setq nils (- (cdr spec) (length (car body)))) 0))
162 `(,@(car body) ,@(make-list nils nil) t)
163 `(ignore-errors ,@body)))))
164
165 ;; More compile-time-macros
166 (eval-when-compile
167 (defmacro save-buffer-state-x (&rest body) ; similar to EMACS/lazy-lock.el
168 (let ((modified (with-no-warnings (gensym "save-buffer-state-x-modified-"))))
169 `(let ((,modified (buffer-modified-p)))
170 (unwind-protect
171 (let ((buffer-undo-list t) (inhibit-read-only t)
172 ,@(unless (featurep 'xemacs)
173 '((inhibit-point-motion-hooks t) deactivate-mark))
174 before-change-functions after-change-functions
175 buffer-file-name buffer-file-truename)
176 ,@body)
177 (and (not ,modified) (buffer-modified-p)
178 (set-buffer-modified-p nil)))))))
179 (put 'save-buffer-state-x 'lisp-indent-function 0)
180
181 ;; get rid of byte-compile warnings
182 (eval-when-compile
183 (require 'cc-mode))
184
185 (defvar outline-level)
186 (defvar imenu-use-markers)
187 (defvar imenu-create-index-function)
188
189 ;; We cannot use `c-forward-syntactic-ws' directly since it is a macro since
190 ;; cc-mode-5.30 => antlr-mode compiled with older cc-mode would fail (macro
191 ;; call) when used with newer cc-mode. Also, antlr-mode compiled with newer
192 ;; cc-mode would fail (undefined `c-forward-sws') when used with older cc-mode.
193 ;; Additional to the `defalias' below, we must set `antlr-c-forward-sws' to
194 ;; `c-forward-syntactic-ws' when `c-forward-sws' is not defined after requiring
195 ;; cc-mode.
196 (defalias 'antlr-c-forward-sws 'c-forward-sws)
197
198
199 ;;;;##########################################################################
200 ;;;; Variables
201 ;;;;##########################################################################
202
203
204 (defgroup antlr nil
205 "Major mode for ANTLR grammar files."
206 :group 'languages
207 :link '(emacs-commentary-link "antlr-mode.el")
208 :link '(url-link "http://antlr-mode.sourceforge.net/")
209 :prefix "antlr-")
210
211 (defconst antlr-version "2.2c"
212 "ANTLR major mode version number.
213 Check <http://antlr-mode.sourceforge.net/> for the newest.")
214
215
216 ;;;===========================================================================
217 ;;; Controlling ANTLR's code generator (language option)
218 ;;;===========================================================================
219
220 (defvar antlr-language nil
221 "Major mode corresponding to ANTLR's \"language\" option.
222 Set via `antlr-language-alist'. The only useful place to change this
223 buffer-local variable yourself is in `antlr-mode-hook' or in the \"local
224 variable list\" near the end of the file, see
225 `enable-local-variables'.")
226
227 (defcustom antlr-language-alist
228 '((java-mode "Java" nil "\"Java\"" "Java")
229 (c++-mode "C++" "\"Cpp\"" "Cpp"))
230 "List of ANTLR's supported languages.
231 Each element in this list looks like
232 \(MAJOR-MODE MODELINE-STRING OPTION-VALUE...)
233
234 MAJOR-MODE, the major mode of the code in the grammar's actions, is the
235 value of `antlr-language' if the first group in the string matched by
236 REGEXP in `antlr-language-limit-n-regexp' is one of the OPTION-VALUEs.
237 An OPTION-VALUE of nil denotes the fallback element. MODELINE-STRING is
238 also displayed in the modeline next to \"Antlr\"."
239 :group 'antlr
240 :type '(repeat (group :value (java-mode "")
241 (function :tag "Major mode")
242 (string :tag "Modeline string")
243 (repeat :tag "ANTLR language option" :inline t
244 (choice (const :tag "Default" nil)
245 string )))))
246
247 (defcustom antlr-language-limit-n-regexp
248 '(8192 . "language[ \t]*=[ \t]*\\(\"?[A-Z][A-Za-z_]*\"?\\)")
249 "Used to set a reasonable value for `antlr-language'.
250 Looks like \(LIMIT \. REGEXP). Search for REGEXP from the beginning of
251 the buffer to LIMIT and use the first group in the matched string to set
252 the language according to `antlr-language-alist'."
253 :group 'antlr
254 :type '(cons (choice :tag "Limit" (const :tag "No" nil) (integer :value 0))
255 regexp))
256
257
258 ;;;===========================================================================
259 ;;; Hide/Unhide, Indent/Tabs
260 ;;;===========================================================================
261
262 (defcustom antlr-action-visibility 3
263 "Visibility of actions when command `antlr-hide-actions' is used.
264 If nil, the actions with their surrounding braces are hidden. If a
265 number, do not hide the braces, only hide the contents if its length is
266 greater than this number."
267 :group 'antlr
268 :type '(choice (const :tag "Completely hidden" nil)
269 (integer :tag "Hidden if longer than" :value 3)))
270
271 (defcustom antlr-indent-comment 'tab
272 "*Non-nil, if the indentation should touch lines in block comments.
273 If nil, no continuation line of a block comment is changed. If t, they
274 are changed according to `c-indentation-line'. When not nil and not t,
275 they are only changed by \\[antlr-indent-command]."
276 :group 'antlr
277 :type '(radio (const :tag "No" nil)
278 (const :tag "Always" t)
279 (sexp :tag "With TAB" :format "%t" :value tab)))
280
281 (defcustom antlr-tab-offset-alist
282 '((antlr-mode nil 4 nil)
283 (java-mode "antlr" 4 nil))
284 "Alist to determine whether to use ANTLR's convention for TABs.
285 Each element looks like \(MAJOR-MODE REGEXP TAB-WIDTH INDENT-TABS-MODE).
286 The first element whose MAJOR-MODE is nil or equal to `major-mode' and
287 whose REGEXP is nil or matches variable `buffer-file-name' is used to
288 set `tab-width' and `indent-tabs-mode'. This is useful to support both
289 ANTLR's and Java's indentation styles. Used by `antlr-set-tabs'."
290 :group 'antlr
291 :type '(repeat (group :value (antlr-mode nil 8 nil)
292 (choice (const :tag "All" nil)
293 (function :tag "Major mode"))
294 (choice (const :tag "All" nil) regexp)
295 (integer :tag "Tab width")
296 (boolean :tag "Indent-tabs-mode"))))
297
298 (defcustom antlr-indent-style "java"
299 "*If non-nil, cc-mode indentation style used for `antlr-mode'.
300 See `c-set-style' and for details, where the most interesting part in
301 `c-style-alist' is the value of `c-basic-offset'."
302 :group 'antlr
303 :type '(choice (const nil) regexp))
304
305 (defcustom antlr-indent-item-regexp
306 "[]}):;|&]" ; & is local ANTLR extension (SGML's and-connector)
307 "Regexp matching lines which should be indented by one TAB less.
308 See `antlr-indent-line' and command \\[antlr-indent-command]."
309 :group 'antlr
310 :type 'regexp)
311
312 (defcustom antlr-indent-at-bol-alist
313 ;; eval-when-compile not usable with defcustom...
314 '((java-mode . "\\(package\\|import\\)\\>")
315 (c++-mode . "#\\(assert\\|cpu\\|define\\|endif\\|el\\(if\\|se\\)\\|i\\(dent\\|f\\(def\\|ndef\\)?\\|mport\\|nclude\\(_next\\)?\\)\\|line\\|machine\\|pragma\\|system\\|un\\(assert\\|def\\)\\|warning\\)\\>"))
316 "Alist of regexps matching lines are indented at column 0.
317 Each element in this list looks like (MODE . REGEXP) where MODE is a
318 function and REGEXP is a regular expression.
319
320 If `antlr-language' equals to a MODE, the line starting at the first
321 non-whitespace is matched by the corresponding REGEXP, and the line is
322 part of a header action, indent the line at column 0 instead according
323 to the normal rules of `antlr-indent-line'."
324 :group 'antlr
325 :type '(repeat (cons (function :tag "Major mode") regexp)))
326
327 ;; adopt indentation to cc-engine
328 (defvar antlr-disabling-cc-syntactic-symbols
329 '(statement-block-intro
330 defun-block-intro topmost-intro statement-case-intro member-init-intro
331 arglist-intro brace-list-intro knr-argdecl-intro inher-intro
332 objc-method-intro
333 block-close defun-close class-close brace-list-close arglist-close
334 inline-close extern-lang-close namespace-close))
335
336
337 ;;;===========================================================================
338 ;;; Options: customization
339 ;;;===========================================================================
340
341 (defcustom antlr-options-use-submenus t
342 "*Non-nil, if the major mode menu should include option submenus.
343 If nil, the menu just includes a command to insert options. Otherwise,
344 it includes four submenus to insert file/grammar/rule/subrule options."
345 :group 'antlr
346 :type 'boolean)
347
348 (defcustom antlr-tool-version 20701
349 "*The version number of the Antlr tool.
350 The value is an integer of the form XYYZZ which stands for vX.YY.ZZ.
351 This variable is used to warn about non-supported options and to supply
352 version correct option values when using \\[antlr-insert-option].
353
354 Don't use a number smaller than 20600 since the stored history of
355 Antlr's options starts with v2.06.00, see `antlr-options-alists'. You
356 can make this variable buffer-local."
357 :group 'antlr
358 :type 'integer)
359
360 (defcustom antlr-options-auto-colon t
361 "*Non-nil, if `:' is inserted with a rule or subrule options section.
362 A `:' is only inserted if this value is non-nil, if a rule or subrule
363 option is inserted with \\[antlr-insert-option], if there was no rule or
364 subrule options section before, and if a `:' is not already present
365 after the section, ignoring whitespace, comments and the init action."
366 :group 'antlr
367 :type 'boolean)
368
369 (defcustom antlr-options-style nil
370 "List of symbols which determine the style of option values.
371 If a style symbol is present, the corresponding option value is put into
372 quotes, i.e., represented as a string, otherwise it is represented as an
373 identifier.
374
375 The only style symbol used in the default value of `antlr-options-alist'
376 is `language-as-string'. See also `antlr-read-value'."
377 :group 'antlr
378 :type '(repeat (symbol :tag "Style symbol")))
379
380 (defcustom antlr-options-push-mark t
381 "*Non-nil, if inserting an option should set & push mark.
382 If nil, never set mark when inserting an option with command
383 \\[antlr-insert-option]. If t, always set mark via `push-mark'. If a
384 number, only set mark if point was outside the options area before and
385 the number of lines between point and the insert position is greater
386 than this value. Otherwise, only set mark if point was outside the
387 options area before."
388 :group 'antlr
389 :type '(radio (const :tag "No" nil)
390 (const :tag "Always" t)
391 (integer :tag "Lines between" :value 10)
392 (sexp :tag "If outside options" :format "%t" :value outside)))
393
394 (defcustom antlr-options-assign-string " = "
395 "*String containing `=' to use between option name and value.
396 This string is only used if the option to insert did not exist before
397 or if there was no `=' after it. In other words, the spacing around an
398 existing `=' won't be changed when changing an option value."
399 :group 'antlr
400 :type 'string)
401
402
403 ;;;===========================================================================
404 ;;; Options: definitions
405 ;;;===========================================================================
406
407 (defvar antlr-options-headings '("file" "grammar" "rule" "subrule")
408 "Headings for the four different option kinds.
409 The standard value is (\"file\" \"grammar\" \"rule\" \"subrule\"). See
410 `antlr-options-alists'")
411
412 (defvar antlr-options-alists
413 '(;; file options ----------------------------------------------------------
414 (("language" antlr-language-option-extra
415 (20600 antlr-read-value
416 "Generated language: " language-as-string
417 (("Java") ("Cpp") ("HTML") ("Diagnostic")))
418 (20700 antlr-read-value
419 "Generated language: " language-as-string
420 (("Java") ("Cpp") ("HTML") ("Diagnostic") ("Sather"))))
421 ("mangleLiteralPrefix" nil
422 (20600 antlr-read-value
423 "Prefix for literals (default LITERAL_): " t))
424 ("namespace" antlr-c++-mode-extra
425 (20700 antlr-read-value
426 "Wrap generated C++ code in namespace: " t))
427 ("namespaceStd" antlr-c++-mode-extra
428 (20701 antlr-read-value
429 "Replace ANTLR_USE_NAMESPACE(std) by: " t))
430 ("namespaceAntlr" antlr-c++-mode-extra
431 (20701 antlr-read-value
432 "Replace ANTLR_USE_NAMESPACE(antlr) by: " t))
433 ("genHashLines" antlr-c++-mode-extra
434 (20701 antlr-read-boolean
435 "Include #line in generated C++ code? "))
436 )
437 ;; grammar options --------------------------------------------------------
438 (("k" nil
439 (20600 antlr-read-value
440 "Lookahead depth: "))
441 ("importVocab" nil
442 (20600 antlr-read-value
443 "Import vocabulary: "))
444 ("exportVocab" nil
445 (20600 antlr-read-value
446 "Export vocabulary: "))
447 ("testLiterals" nil ; lexer only
448 (20600 antlr-read-boolean
449 "Test each token against literals table? "))
450 ("defaultErrorHandler" nil ; not for lexer
451 (20600 antlr-read-boolean
452 "Generate default exception handler for each rule? "))
453 ("codeGenMakeSwitchThreshold" nil
454 (20600 antlr-read-value
455 "Min number of alternatives for 'switch': "))
456 ("codeGenBitsetTestThreshold" nil
457 (20600 antlr-read-value
458 "Min size of lookahead set for bitset test: "))
459 ("analyzerDebug" nil
460 (20600 antlr-read-boolean
461 "Display debugging info during grammar analysis? "))
462 ("codeGenDebug" nil
463 (20600 antlr-read-boolean
464 "Display debugging info during code generation? "))
465 ("buildAST" nil ; not for lexer
466 (20600 antlr-read-boolean
467 "Use automatic AST construction/transformation? "))
468 ("ASTLabelType" nil ; not for lexer
469 (20600 antlr-read-value
470 "Class of user-defined AST node: " t))
471 ("charVocabulary" nil ; lexer only
472 (20600 nil
473 "Insert character vocabulary"))
474 ("interactive" nil
475 (20600 antlr-read-boolean
476 "Generate interactive lexer/parser? "))
477 ("caseSensitive" nil ; lexer only
478 (20600 antlr-read-boolean
479 "Case significant when matching characters? "))
480 ("caseSensitiveLiterals" nil ; lexer only
481 (20600 antlr-read-boolean
482 "Case significant when testing literals table? "))
483 ("classHeaderSuffix" nil
484 (20600 nil
485 "Additional string for grammar class definition"))
486 ("filter" nil ; lexer only
487 (20600 antlr-read-boolean
488 "Skip rule (the name, true or false): "
489 antlr-grammar-tokens))
490 ("namespace" antlr-c++-mode-extra
491 (20700 antlr-read-value
492 "Wrap generated C++ code for grammar in namespace: " t))
493 ("namespaceStd" antlr-c++-mode-extra
494 (20701 antlr-read-value
495 "Replace ANTLR_USE_NAMESPACE(std) by: " t))
496 ("namespaceAntlr" antlr-c++-mode-extra
497 (20701 antlr-read-value
498 "Replace ANTLR_USE_NAMESPACE(antlr) by: " t))
499 ("genHashLines" antlr-c++-mode-extra
500 (20701 antlr-read-boolean
501 "Include #line in generated C++ code? "))
502 ;;; ("autoTokenDef" nil ; parser only
503 ;;; (80000 antlr-read-boolean ; default: true
504 ;;; "Automatically define referenced token? "))
505 ;;; ("keywordsMeltTo" nil ; parser only
506 ;;; (80000 antlr-read-value
507 ;;; "Change non-matching keywords to token type: "))
508 )
509 ;; rule options ----------------------------------------------------------
510 (("testLiterals" nil ; lexer only
511 (20600 antlr-read-boolean
512 "Test this token against literals table? "))
513 ("defaultErrorHandler" nil ; not for lexer
514 (20600 antlr-read-boolean
515 "Generate default exception handler for this rule? "))
516 ("ignore" nil ; lexer only
517 (20600 antlr-read-value
518 "In this rule, ignore tokens of type: " nil
519 antlr-grammar-tokens))
520 ("paraphrase" nil ; lexer only
521 (20600 antlr-read-value
522 "In messages, replace name of this token by: " t))
523 )
524 ;; subrule options -------------------------------------------------------
525 (("warnWhenFollowAmbig" nil
526 (20600 antlr-read-boolean
527 "Display warnings for ambiguities with FOLLOW? "))
528 ("generateAmbigWarnings" nil
529 (20600 antlr-read-boolean
530 "Display warnings for ambiguities? "))
531 ("greedy" nil
532 (20700 antlr-read-boolean
533 "Make this optional/loop subrule greedy? "))
534 ))
535 "Definitions for Antlr's options of all four different kinds.
536
537 The value looks like \(FILE GRAMMAR RULE SUBRULE) where each FILE,
538 GRAMMAR, RULE, and SUBRULE is a list of option definitions of the
539 corresponding kind, i.e., looks like \(OPTION-DEF...).
540
541 Each OPTION-DEF looks like \(OPTION-NAME EXTRA-FN VALUE-SPEC...) which
542 defines a file/grammar/rule/subrule option with name OPTION-NAME. The
543 OPTION-NAMEs are used for the creation of the \"Insert XXX Option\"
544 submenus, see `antlr-options-use-submenus', and to allow to insert the
545 option name with completion when using \\[antlr-insert-option].
546
547 If EXTRA-FN is a function, it is called at different phases of the
548 insertion with arguments \(PHASE OPTION-NAME). PHASE can have the
549 values `before-input' or `after-insertion', additional phases might be
550 defined in future versions of this mode. The phase `before-input'
551 occurs before the user is asked to insert a value. The phase
552 `after-insertion' occurs after the option value has been inserted.
553 EXTRA-FN might be called with additional arguments in future versions of
554 this mode.
555
556 Each specification VALUE-SPEC looks like \(VERSION READ-FN ARG...). The
557 last VALUE-SPEC in an OPTION-DEF whose VERSION is smaller or equal to
558 `antlr-tool-version' specifies how the user is asked for the value of
559 the option.
560
561 If READ-FN is nil, the only ARG is a string which is printed at the echo
562 area to guide the user what to insert at point. Otherwise, READ-FN is
563 called with arguments \(INIT-VALUE ARG...) to get the new value of the
564 option. INIT-VALUE is the old value of the option or nil.
565
566 The standard value contains the following functions as READ-FN:
567 `antlr-read-value' with ARGs = \(PROMPT AS-STRING TABLE) which reads a
568 general value, or `antlr-read-boolean' with ARGs = \(PROMPT TABLE) which
569 reads a boolean value or a member of TABLE. PROMPT is the prompt when
570 asking for a new value. If non-nil, TABLE is a table for completion or
571 a function evaluating to such a table. The return value is quoted if
572 AS-STRING is non-nil and is either t or a symbol which is a member of
573 `antlr-options-style'.")
574
575
576 ;;;===========================================================================
577 ;;; Run tool, create Makefile dependencies
578 ;;;===========================================================================
579
580 (defcustom antlr-tool-command "java antlr.Tool"
581 "*Command used in \\[antlr-run-tool] to run the Antlr tool.
582 This variable should include all options passed to Antlr except the
583 option \"-glib\" which is automatically suggested if necessary."
584 :group 'antlr
585 :type 'string)
586
587 (defcustom antlr-ask-about-save t
588 "*If not nil, \\[antlr-run-tool] asks which buffers to save.
589 Otherwise, it saves all modified buffers before running without asking."
590 :group 'antlr
591 :type 'boolean)
592
593 (defcustom antlr-makefile-specification
594 '("\n" ("GENS" "GENS%d" " \\\n\t") "$(ANTLR)")
595 "*Variable to specify the appearance of the generated makefile rules.
596 This variable influences the output of \\[antlr-show-makefile-rules].
597 It looks like \(RULE-SEP GEN-VAR-SPEC COMMAND).
598
599 RULE-SEP is the string to separate different makefile rules. COMMAND is
600 a string with the command which runs the Antlr tool, it should include
601 all options except the option \"-glib\" which is automatically added
602 if necessary.
603
604 If GEN-VAR-SPEC is nil, each target directly consists of a list of
605 files. If GEN-VAR-SPEC looks like \(GEN-VAR GEN-VAR-FORMAT GEN-SEP), a
606 Makefile variable is created for each rule target.
607
608 Then, GEN-VAR is a string with the name of the variable which contains
609 the file names of all makefile rules. GEN-VAR-FORMAT is a format string
610 producing the variable of each target with substitution COUNT/%d where
611 COUNT starts with 1. GEN-SEP is used to separate long variable values."
612 :group 'antlr
613 :type '(list (string :tag "Rule separator")
614 (choice
615 (const :tag "Direct targets" nil)
616 (list :tag "Variables for targets"
617 (string :tag "Variable for all targets")
618 (string :tag "Format for each target variable")
619 (string :tag "Variable separator")))
620 (string :tag "ANTLR command")))
621
622 (defvar antlr-file-formats-alist
623 '((java-mode ("%sTokenTypes.java") ("%s.java"))
624 (c++-mode ("%sTokenTypes.hpp") ("%s.cpp" "%s.hpp")))
625 "Language dependent formats which specify generated files.
626 Each element in this list looks looks like
627 \(MAJOR-MODE (VOCAB-FILE-FORMAT...) (CLASS-FILE-FORMAT...)).
628
629 The element whose MAJOR-MODE is equal to `antlr-language' is used to
630 specify the generated files which are language dependent. See variable
631 `antlr-special-file-formats' for language independent files.
632
633 VOCAB-FILE-FORMAT is a format string, it specifies with substitution
634 VOCAB/%s the generated file for each export vocabulary VOCAB.
635 CLASS-FILE-FORMAT is a format string, it specifies with substitution
636 CLASS/%s the generated file for each grammar class CLASS.")
637
638 (defvar antlr-special-file-formats '("%sTokenTypes.txt" "expanded%s.g")
639 "Language independent formats which specify generated files.
640 The value looks like \(VOCAB-FILE-FORMAT EXPANDED-GRAMMAR-FORMAT).
641
642 VOCAB-FILE-FORMAT is a format string, it specifies with substitution
643 VOCAB/%s the generated or input file for each export or import
644 vocabulary VOCAB, respectively. EXPANDED-GRAMMAR-FORMAT is a format
645 string, it specifies with substitution GRAMMAR/%s the constructed
646 grammar file if the file GRAMMAR.g contains a grammar class which
647 extends a class other than \"Lexer\", \"Parser\" or \"TreeParser\".
648
649 See variable `antlr-file-formats-alist' for language dependent
650 formats.")
651
652 (defvar antlr-unknown-file-formats '("?%s?.g" "?%s?")
653 "*Formats which specify the names of unknown files.
654 The value looks like \(SUPER-GRAMMAR-FILE-FORMAT SUPER-EVOCAB-FORMAT).
655
656 SUPER-GRAMMAR-FORMAT is a format string, it specifies with substitution
657 SUPER/%s the name of a grammar file for Antlr's option \"-glib\" if no
658 grammar file in the current directory defines the class SUPER or if it
659 is defined more than once. SUPER-EVOCAB-FORMAT is a format string, it
660 specifies with substitution SUPER/%s the name for the export vocabulary
661 of above mentioned class SUPER.")
662
663 (defvar antlr-help-unknown-file-text
664 "## The following rules contain filenames of the form
665 ## \"?SUPERCLASS?.g\" (and \"?SUPERCLASS?TokenTypes.txt\")
666 ## where SUPERCLASS is not found to be defined in any grammar file of
667 ## the current directory or is defined more than once. Please replace
668 ## these filenames by the grammar files (and their exportVocab).\n\n"
669 "String indicating the existence of unknown files in the Makefile.
670 See \\[antlr-show-makefile-rules] and `antlr-unknown-file-formats'.")
671
672 (defvar antlr-help-rules-intro
673 "The following Makefile rules define the dependencies for all (non-
674 expanded) grammars in directory \"%s\".\n
675 They are stored in the kill-ring, i.e., you can insert them with C-y
676 into your Makefile. You can also invoke M-x antlr-show-makefile-rules
677 from within a Makefile to insert them directly.\n\n\n"
678 "Introduction to use with \\[antlr-show-makefile-rules].
679 It is a format string and used with substitution DIRECTORY/%s where
680 DIRECTORY is the name of the current directory.")
681
682
683 ;;;===========================================================================
684 ;;; Menu
685 ;;;===========================================================================
686
687 (defcustom antlr-imenu-name t ; (featurep 'xemacs) ; TODO: Emacs-21 bug?
688 "*Non-nil, if a \"Index\" menu should be added to the menubar.
689 If it is a string, it is used instead \"Index\". Requires package
690 imenu."
691 :group 'antlr
692 :type '(choice (const :tag "No menu" nil)
693 (const :tag "Index menu" t)
694 (string :tag "Other menu name")))
695
696 (defvar antlr-mode-map
697 (let ((map (make-sparse-keymap)))
698 (define-key map "\t" 'antlr-indent-command)
699 (define-key map "\e\C-a" 'antlr-beginning-of-rule)
700 (define-key map "\e\C-e" 'antlr-end-of-rule)
701 (define-key map "\C-c\C-a" 'antlr-beginning-of-body)
702 (define-key map "\C-c\C-e" 'antlr-end-of-body)
703 (define-key map "\C-c\C-f" 'c-forward-into-nomenclature)
704 (define-key map "\C-c\C-b" 'c-backward-into-nomenclature)
705 (define-key map "\C-c\C-c" 'comment-region)
706 (define-key map "\C-c\C-v" 'antlr-hide-actions)
707 (define-key map "\C-c\C-r" 'antlr-run-tool)
708 (define-key map "\C-c\C-o" 'antlr-insert-option)
709 ;; I'm too lazy to define my own:
710 (define-key map "\ea" 'c-beginning-of-statement)
711 (define-key map "\ee" 'c-end-of-statement)
712 ;; electric keys:
713 (define-key map ":" 'antlr-electric-character)
714 (define-key map ";" 'antlr-electric-character)
715 (define-key map "|" 'antlr-electric-character)
716 (define-key map "&" 'antlr-electric-character)
717 (define-key map "(" 'antlr-electric-character)
718 (define-key map ")" 'antlr-electric-character)
719 (define-key map "{" 'antlr-electric-character)
720 (define-key map "}" 'antlr-electric-character)
721 map)
722 "Keymap used in `antlr-mode' buffers.")
723
724 (easy-menu-define antlr-mode-menu antlr-mode-map
725 "Major mode menu."
726 `("Antlr"
727 ,@(if (cond-emacs-xemacs
728 :EMACS (and antlr-options-use-submenus
729 (>= emacs-major-version 21))
730 :XEMACS antlr-options-use-submenus)
731 `(("Insert File Option"
732 :filter ,(lambda (x) (antlr-options-menu-filter 1 x)))
733 ("Insert Grammar Option"
734 :filter ,(lambda (x) (antlr-options-menu-filter 2 x)))
735 ("Insert Rule Option"
736 :filter ,(lambda (x) (antlr-options-menu-filter 3 x)))
737 ("Insert Subrule Option"
738 :filter ,(lambda (x) (antlr-options-menu-filter 4 x)))
739 "---")
740 '(["Insert Option" antlr-insert-option
741 :active (not buffer-read-only)]))
742 ("Forward/Backward"
743 ["Backward Rule" antlr-beginning-of-rule t]
744 ["Forward Rule" antlr-end-of-rule t]
745 ["Start of Rule Body" antlr-beginning-of-body
746 :active (antlr-inside-rule-p)]
747 ["End of Rule Body" antlr-end-of-body
748 :active (antlr-inside-rule-p)]
749 "---"
750 ["Backward Statement" c-beginning-of-statement t]
751 ["Forward Statement" c-end-of-statement t]
752 ["Backward Into Nomencl." c-backward-into-nomenclature t]
753 ["Forward Into Nomencl." c-forward-into-nomenclature t])
754 ["Indent Region" indent-region
755 :active (and (not buffer-read-only) (c-region-is-active-p))]
756 ["Comment Out Region" comment-region
757 :active (and (not buffer-read-only) (c-region-is-active-p))]
758 ["Uncomment Region"
759 (comment-region (region-beginning) (region-end) '(4))
760 :active (and (not buffer-read-only) (c-region-is-active-p))]
761 "---"
762 ["Hide Actions (incl. Args)" antlr-hide-actions t]
763 ["Hide Actions (excl. Args)" (antlr-hide-actions 2) t]
764 ["Unhide All Actions" (antlr-hide-actions 0) t]
765 "---"
766 ["Run Tool on Grammar" antlr-run-tool t]
767 ["Show Makefile Rules" antlr-show-makefile-rules t]
768 "---"
769 ["Customize Antlr" (customize-group 'antlr) t]))
770
771
772 ;;;===========================================================================
773 ;;; font-lock
774 ;;;===========================================================================
775
776 (defcustom antlr-font-lock-maximum-decoration 'inherit
777 "*The maximum decoration level for fontifying actions.
778 Value `none' means, do not fontify actions, just normal grammar code
779 according to `antlr-font-lock-additional-keywords'. Value `inherit'
780 means, use value of `font-lock-maximum-decoration'. Any other value is
781 interpreted as in `font-lock-maximum-decoration' with no level-0
782 fontification, see `antlr-font-lock-keywords-alist'.
783
784 While calculating the decoration level for actions, `major-mode' is
785 bound to `antlr-language'. For example, with value
786 \((java-mode \. 2) (c++-mode \. 0))
787 Java actions are fontified with level 2 and C++ actions are not
788 fontified at all."
789 :group 'antlr
790 :type '(choice (const :tag "None" none)
791 (const :tag "Inherit" inherit)
792 (const :tag "Default" nil)
793 (const :tag "Maximum" t)
794 (integer :tag "Level" 1)
795 (repeat :menu-tag "Mode specific" :tag "Mode specific"
796 :value ((t . t))
797 (cons :tag "Instance"
798 (radio :tag "Mode"
799 (const :tag "All" t)
800 (symbol :tag "Name"))
801 (radio :tag "Decoration"
802 (const :tag "Default" nil)
803 (const :tag "Maximum" t)
804 (integer :tag "Level" 1))))))
805
806 (defconst antlr-no-action-keywords nil
807 ;; Using nil directly won't work (would use highest level, see
808 ;; `font-lock-choose-keywords'), but a non-symbol, i.e., (list), at `car'
809 ;; would break Emacs-21.0:
810 "Empty font-lock keywords for actions.
811 Do not change the value of this constant.")
812
813 (defvar antlr-font-lock-keywords-alist
814 '((java-mode
815 antlr-no-action-keywords
816 java-font-lock-keywords-1 java-font-lock-keywords-2
817 java-font-lock-keywords-3)
818 (c++-mode
819 antlr-no-action-keywords
820 c++-font-lock-keywords-1 c++-font-lock-keywords-2
821 c++-font-lock-keywords-3))
822 "List of font-lock keywords for actions in the grammar.
823 Each element in this list looks like
824 \(MAJOR-MODE KEYWORD...)
825
826 If `antlr-language' is equal to MAJOR-MODE, the KEYWORDs are the
827 font-lock keywords according to `font-lock-defaults' used for the code
828 in the grammar's actions and semantic predicates, see
829 `antlr-font-lock-maximum-decoration'.")
830
831 (defvar antlr-default-face 'antlr-default)
832 (defface antlr-default '((t nil))
833 "Face to prevent strings from language dependent highlighting.
834 Do not change."
835 :group 'antlr)
836 ;; backward-compatibility alias
837 (put 'antlr-font-lock-default-face 'face-alias 'antlr-default)
838 (put 'antlr-font-lock-default-face 'obsolete-face "22.1")
839
840 (defvar antlr-keyword-face 'antlr-keyword)
841 (defface antlr-keyword
842 (cond-emacs-xemacs
843 '((((class color) (background light))
844 (:foreground "black" :EMACS :weight bold :XEMACS :bold t))
845 (t :inherit font-lock-keyword-face)))
846 "ANTLR keywords."
847 :group 'antlr)
848 ;; backward-compatibility alias
849 (put 'antlr-font-lock-keyword-face 'face-alias 'antlr-keyword)
850 (put 'antlr-font-lock-keyword-face 'obsolete-face "22.1")
851
852 (defvar antlr-syntax-face 'antlr-keyword)
853 (defface antlr-syntax
854 (cond-emacs-xemacs
855 '((((class color) (background light))
856 (:foreground "black" :EMACS :weight bold :XEMACS :bold t))
857 (t :inherit font-lock-constant-face)))
858 "ANTLR syntax symbols like :, |, (, ), ...."
859 :group 'antlr)
860 ;; backward-compatibility alias
861 (put 'antlr-font-lock-syntax-face 'face-alias 'antlr-syntax)
862 (put 'antlr-font-lock-syntax-face 'obsolete-face "22.1")
863
864 (defvar antlr-ruledef-face 'antlr-ruledef)
865 (defface antlr-ruledef
866 (cond-emacs-xemacs
867 '((((class color) (background light))
868 (:foreground "blue" :EMACS :weight bold :XEMACS :bold t))
869 (t :inherit font-lock-function-name-face)))
870 "ANTLR rule references (definition)."
871 :group 'antlr)
872 ;; backward-compatibility alias
873 (put 'antlr-font-lock-ruledef-face 'face-alias 'antlr-ruledef)
874 (put 'antlr-font-lock-ruledef-face 'obsolete-face "22.1")
875
876 (defvar antlr-tokendef-face 'antlr-tokendef)
877 (defface antlr-tokendef
878 (cond-emacs-xemacs
879 '((((class color) (background light))
880 (:foreground "blue" :EMACS :weight bold :XEMACS :bold t))
881 (t :inherit font-lock-function-name-face)))
882 "ANTLR token references (definition)."
883 :group 'antlr)
884 ;; backward-compatibility alias
885 (put 'antlr-font-lock-tokendef-face 'face-alias 'antlr-tokendef)
886 (put 'antlr-font-lock-tokendef-face 'obsolete-face "22.1")
887
888 (defvar antlr-ruleref-face 'antlr-ruleref)
889 (defface antlr-ruleref
890 '((((class color) (background light)) (:foreground "blue4"))
891 (t :inherit font-lock-type-face))
892 "ANTLR rule references (usage)."
893 :group 'antlr)
894 ;; backward-compatibility alias
895 (put 'antlr-font-lock-ruleref-face 'face-alias 'antlr-ruleref)
896 (put 'antlr-font-lock-ruleref-face 'obsolete-face "22.1")
897
898 (defvar antlr-tokenref-face 'antlr-tokenref)
899 (defface antlr-tokenref
900 '((((class color) (background light)) (:foreground "orange4"))
901 (t :inherit font-lock-type-face))
902 "ANTLR token references (usage)."
903 :group 'antlr)
904 ;; backward-compatibility alias
905 (put 'antlr-font-lock-tokenref-face 'face-alias 'antlr-tokenref)
906 (put 'antlr-font-lock-tokenref-face 'obsolete-face "22.1")
907
908 (defvar antlr-literal-face 'antlr-literal)
909 (defface antlr-literal
910 (cond-emacs-xemacs
911 '((((class color) (background light))
912 (:foreground "brown4" :EMACS :weight bold :XEMACS :bold t))
913 (t :inherit font-lock-string-face)))
914 "ANTLR special literal tokens.
915 It is used to highlight strings matched by the first regexp group of
916 `antlr-font-lock-literal-regexp'."
917 :group 'antlr)
918 ;; backward-compatibility alias
919 (put 'antlr-font-lock-literal-face 'face-alias 'antlr-literal)
920 (put 'antlr-font-lock-literal-face 'obsolete-face "22.1")
921
922 (defcustom antlr-font-lock-literal-regexp "\"\\(\\sw\\(\\sw\\|-\\)*\\)\""
923 "Regexp matching literals with special syntax highlighting, or nil.
924 If nil, there is no special syntax highlighting for some literals.
925 Otherwise, it should be a regular expression which must contain a regexp
926 group. The string matched by the first group is highlighted with
927 `antlr-font-lock-literal-face'."
928 :group 'antlr
929 :type '(choice (const :tag "None" nil) regexp))
930
931 (defvar antlr-class-header-regexp
932 "\\(class\\)[ \t]+\\([A-Za-z\300-\326\330-\337]\\sw*\\)[ \t]+\\(extends\\)[ \t]+\\([A-Za-z\300-\326\330-\337]\\sw*\\)[ \t]*;"
933 "Regexp matching class headers.")
934
935 (defvar antlr-font-lock-additional-keywords
936 (cond-emacs-xemacs
937 `((antlr-invalidate-context-cache)
938 ("\\$setType[ \t]*(\\([A-Za-z\300-\326\330-\337]\\sw*\\))"
939 (1 antlr-tokendef-face))
940 ("\\$\\sw+" (0 antlr-keyword-face))
941 ;; the tokens are already fontified as string/docstrings:
942 (,(lambda (limit)
943 (if antlr-font-lock-literal-regexp
944 (antlr-re-search-forward antlr-font-lock-literal-regexp limit)))
945 (1 antlr-literal-face t)
946 :XEMACS (0 nil)) ; XEmacs bug workaround
947 (,(lambda (limit)
948 (antlr-re-search-forward antlr-class-header-regexp limit))
949 (1 antlr-keyword-face)
950 (2 antlr-ruledef-face)
951 (3 antlr-keyword-face)
952 (4 (if (member (match-string 4) '("Lexer" "Parser" "TreeParser"))
953 antlr-keyword-face
954 type-face)))
955 (,(lambda (limit)
956 (antlr-re-search-forward
957 "\\<\\(header\\|options\\|tokens\\|exception\\|catch\\|returns\\)\\>"
958 limit))
959 (1 antlr-keyword-face))
960 (,(lambda (limit)
961 (antlr-re-search-forward
962 "^\\(private\\|public\\|protected\\)\\>[ \t]*\\(\\(\\sw+[ \t]*\\(:\\)?\\)\\)?"
963 limit))
964 (1 font-lock-type-face) ; not XEmacs' java level-3 fruit salad
965 (3 (if (antlr-upcase-p (char-after (match-beginning 3)))
966 antlr-tokendef-face
967 antlr-ruledef-face) nil t)
968 (4 antlr-syntax-face nil t))
969 (,(lambda (limit)
970 (antlr-re-search-forward "^\\(\\sw+\\)[ \t]*\\(:\\)?" limit))
971 (1 (if (antlr-upcase-p (char-after (match-beginning 0)))
972 antlr-tokendef-face
973 antlr-ruledef-face) nil t)
974 (2 antlr-syntax-face nil t))
975 (,(lambda (limit)
976 ;; v:ruleref and v:"literal" is allowed...
977 (antlr-re-search-forward "\\(\\sw+\\)[ \t]*\\([=:]\\)?" limit))
978 (1 (if (match-beginning 2)
979 (if (eq (char-after (match-beginning 2)) ?=)
980 antlr-default-face
981 font-lock-variable-name-face)
982 (if (antlr-upcase-p (char-after (match-beginning 1)))
983 antlr-tokenref-face
984 antlr-ruleref-face)))
985 (2 antlr-default-face nil t))
986 (,(lambda (limit)
987 (antlr-re-search-forward "[|&:;(~]\\|)\\([*+?]\\|=>\\)?" limit))
988 (0 antlr-syntax-face))))
989 "Font-lock keywords for ANTLR's normal grammar code.
990 See `antlr-font-lock-keywords-alist' for the keywords of actions.")
991
992 (defvar antlr-font-lock-defaults
993 '(antlr-font-lock-keywords
994 nil nil ((?_ . "w") (?\( . ".") (?\) . ".")) beginning-of-defun)
995 "Font-lock defaults used for ANTLR syntax highlighting.
996 The SYNTAX-ALIST element is also used to initialize
997 `antlr-action-syntax-table'.")
998
999
1000 ;;;===========================================================================
1001 ;;; Internal variables
1002 ;;;===========================================================================
1003
1004 (defvar antlr-mode-hook nil
1005 "Hook called by `antlr-mode'.")
1006
1007 (defvar antlr-mode-syntax-table nil
1008 "Syntax table used in `antlr-mode' buffers.
1009 If non-nil, it will be initialized in `antlr-mode'.")
1010
1011 ;; used for "in Java/C++ code" = syntactic-depth>0
1012 (defvar antlr-action-syntax-table nil
1013 "Syntax table used for ANTLR action parsing.
1014 Initialized by `antlr-mode-syntax-table', changed by SYNTAX-ALIST in
1015 `antlr-font-lock-defaults'. This table should be selected if you use
1016 `buffer-syntactic-context' and `buffer-syntactic-context-depth' in order
1017 not to confuse their context_cache.")
1018
1019 (defvar antlr-mode-abbrev-table nil
1020 "Abbreviation table used in `antlr-mode' buffers.")
1021 (define-abbrev-table 'antlr-mode-abbrev-table ())
1022
1023 (defvar antlr-slow-cache-enabling-symbol 'loudly
1024 ;; Emacs' font-lock changes buffer's tick counter, therefore this value should
1025 ;; be a parameter of a font-lock function, but not any other variable of
1026 ;; functions which call `antlr-slow-syntactic-context'.
1027 "If value is a bound symbol, cache will be used even with text changes.
1028 This is no user option. Used for `antlr-slow-syntactic-context'.")
1029
1030 (defvar antlr-slow-cache-diff-threshold 5000
1031 "Maximum distance between `point' and cache position for cache use.
1032 Used for `antlr-slow-syntactic-context'.")
1033
1034
1035 ;;;;##########################################################################
1036 ;;;; The Code
1037 ;;;;##########################################################################
1038
1039
1040
1041 ;;;===========================================================================
1042 ;;; Syntax functions -- Emacs vs XEmacs dependent, part 1
1043 ;;;===========================================================================
1044
1045 ;; From help.el (XEmacs-21.1), without `copy-syntax-table'
1046 (defmacro antlr-with-syntax-table (syntab &rest body)
1047 "Evaluate BODY with the syntax table SYNTAB."
1048 `(let ((stab (syntax-table)))
1049 (unwind-protect
1050 (progn (set-syntax-table ,syntab) ,@body)
1051 (set-syntax-table stab))))
1052 (put 'antlr-with-syntax-table 'lisp-indent-function 1)
1053 (put 'antlr-with-syntax-table 'edebug-form-spec '(form body))
1054
1055 (defunx antlr-default-directory ()
1056 :xemacs-and-try default-directory
1057 "Return `default-directory'."
1058 default-directory)
1059
1060 ;; Check Emacs-21.1 simple.el, `shell-command'.
1061 (defunx antlr-read-shell-command (prompt &optional initial-input history)
1062 :xemacs-and-try read-shell-command
1063 "Read a string from the minibuffer, using `shell-command-history'."
1064 (read-from-minibuffer prompt initial-input nil nil
1065 (or history 'shell-command-history)))
1066
1067 (defunx antlr-with-displaying-help-buffer (thunk &optional name)
1068 :xemacs-and-try with-displaying-help-buffer
1069 "Make a help buffer and call `thunk' there."
1070 (with-output-to-temp-buffer "*Help*"
1071 (save-excursion (funcall thunk))))
1072
1073
1074 ;;;===========================================================================
1075 ;;; Context cache
1076 ;;;===========================================================================
1077
1078 (defvar antlr-slow-context-cache nil "Internal.")
1079
1080 ;;;(defvar antlr-statistics-full-neg 0)
1081 ;;;(defvar antlr-statistics-full-diff 0)
1082 ;;;(defvar antlr-statistics-full-other 0)
1083 ;;;(defvar antlr-statistics-cache 0)
1084 ;;;(defvar antlr-statistics-inval 0)
1085
1086 (defunx antlr-invalidate-context-cache (&rest dummies)
1087 ;; checkdoc-params: (dummies)
1088 "Invalidate context cache for syntactical context information."
1089 :XEMACS ; XEmacs bug workaround
1090 (save-excursion
1091 (set-buffer (get-buffer-create " ANTLR XEmacs bug workaround"))
1092 (buffer-syntactic-context-depth)
1093 nil)
1094 :EMACS
1095 ;;; (incf antlr-statistics-inval)
1096 (setq antlr-slow-context-cache nil))
1097
1098 (defunx antlr-syntactic-context ()
1099 "Return some syntactic context information.
1100 Return `string' if point is within a string, `block-comment' or
1101 `comment' is point is within a comment or the depth within all
1102 parenthesis-syntax delimiters at point otherwise.
1103 WARNING: this may alter `match-data'."
1104 :XEMACS
1105 (or (buffer-syntactic-context) (buffer-syntactic-context-depth))
1106 :EMACS
1107 (let ((orig (point)) diff state
1108 ;; Arg, Emacs' (buffer-modified-tick) changes with font-lock. Use
1109 ;; hack that `loudly' is bound during font-locking => cache use will
1110 ;; increase from 7% to 99.99% during font-locking.
1111 (tick (or (boundp antlr-slow-cache-enabling-symbol)
1112 (buffer-modified-tick))))
1113 (if (and (cdr antlr-slow-context-cache)
1114 (>= (setq diff (- orig (cadr antlr-slow-context-cache))) 0)
1115 (< diff antlr-slow-cache-diff-threshold)
1116 (eq (current-buffer) (caar antlr-slow-context-cache))
1117 (eq tick (cdar antlr-slow-context-cache)))
1118 ;; (setq antlr-statistics-cache (1+ antlr-statistics-cache) ...)
1119 (setq state (parse-partial-sexp (cadr antlr-slow-context-cache) orig
1120 nil nil
1121 (cddr antlr-slow-context-cache)))
1122 (if (>= orig antlr-slow-cache-diff-threshold)
1123 (beginning-of-defun)
1124 (goto-char (point-min)))
1125 ;;; (cond ((and diff (< diff 0)) (incf antlr-statistics-full-neg))
1126 ;;; ((and diff (>= diff 3000)) (incf antlr-statistics-full-diff))
1127 ;;; (t (incf antlr-statistics-full-other)))
1128 (setq state (parse-partial-sexp (point) orig)))
1129 (goto-char orig)
1130 (if antlr-slow-context-cache
1131 (setcdr antlr-slow-context-cache (cons orig state))
1132 (setq antlr-slow-context-cache
1133 (cons (cons (current-buffer) tick)
1134 (cons orig state))))
1135 (cond ((nth 3 state) 'string)
1136 ((nth 4 state) 'comment) ; block-comment? -- we don't care
1137 (t (car state)))))
1138
1139 ;;; (incf (aref antlr-statistics 2))
1140 ;;; (unless (and (eq (current-buffer)
1141 ;;; (caar antlr-slow-context-cache))
1142 ;;; (eq (buffer-modified-tick)
1143 ;;; (cdar antlr-slow-context-cache)))
1144 ;;; (incf (aref antlr-statistics 1))
1145 ;;; (setq antlr-slow-context-cache nil))
1146 ;;; (let* ((orig (point))
1147 ;;; (base (cadr antlr-slow-context-cache))
1148 ;;; (curr (cddr antlr-slow-context-cache))
1149 ;;; (state (cond ((eq orig (car curr)) (cdr curr))
1150 ;;; ((eq orig (car base)) (cdr base))))
1151 ;;; diff diff2)
1152 ;;; (unless state
1153 ;;; (incf (aref antlr-statistics 3))
1154 ;;; (when curr
1155 ;;; (if (< (setq diff (abs (- orig (car curr))))
1156 ;;; (setq diff2 (abs (- orig (car base)))))
1157 ;;; (setq state curr)
1158 ;;; (setq state base
1159 ;;; diff diff2))
1160 ;;; (if (or (>= (1+ diff) (point)) (>= diff 3000))
1161 ;;; (setq state nil))) ; start from bod/bob
1162 ;;; (if state
1163 ;;; (setq state
1164 ;;; (parse-partial-sexp (car state) orig nil nil (cdr state)))
1165 ;;; (if (>= orig 3000) (beginning-of-defun) (goto-char (point-min)))
1166 ;;; (incf (aref antlr-statistics 4))
1167 ;;; (setq cw (list orig (point) base curr))
1168 ;;; (setq state (parse-partial-sexp (point) orig)))
1169 ;;; (goto-char orig)
1170 ;;; (if antlr-slow-context-cache
1171 ;;; (setcdr (cdr antlr-slow-context-cache) (cons orig state))
1172 ;;; (setq antlr-slow-context-cache
1173 ;;; (cons (cons (current-buffer) (buffer-modified-tick))
1174 ;;; (cons (cons orig state) (cons orig state))))))
1175 ;;; (cond ((nth 3 state) 'string)
1176 ;;; ((nth 4 state) 'comment) ; block-comment? -- we don't care
1177 ;;; (t (car state)))))
1178
1179 ;;; (beginning-of-defun)
1180 ;;; (let ((state (parse-partial-sexp (point) orig)))
1181 ;;; (goto-char orig)
1182 ;;; (cond ((nth 3 state) 'string)
1183 ;;; ((nth 4 state) 'comment) ; block-comment? -- we don't care
1184 ;;; (t (car state))))))
1185
1186
1187 ;;;===========================================================================
1188 ;;; Miscellaneous functions
1189 ;;;===========================================================================
1190
1191 (defun antlr-upcase-p (char)
1192 "Non-nil, if CHAR is an uppercase character (if CHAR was a char)."
1193 ;; in XEmacs, upcase only works for ASCII
1194 (or (and (<= ?A char) (<= char ?Z))
1195 (and (<= ?\300 char) (<= char ?\337)))) ; ?\327 is no letter
1196
1197 (defun antlr-re-search-forward (regexp bound)
1198 "Search forward from point for regular expression REGEXP.
1199 Set point to the end of the occurrence found, and return point. Return
1200 nil if no occurrence was found. Do not search within comments, strings
1201 and actions/semantic predicates. BOUND bounds the search; it is a
1202 buffer position. See also the functions `match-beginning', `match-end'
1203 and `replace-match'."
1204 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1205 (let ((continue t))
1206 (while (and (re-search-forward regexp bound 'limit)
1207 (save-match-data
1208 (if (eq (antlr-syntactic-context) 0)
1209 (setq continue nil)
1210 t))))
1211 (if continue nil (point))))
1212
1213 (defun antlr-search-forward (string)
1214 "Search forward from point for STRING.
1215 Set point to the end of the occurrence found, and return point. Return
1216 nil if no occurrence was found. Do not search within comments, strings
1217 and actions/semantic predicates."
1218 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1219 (let ((continue t))
1220 (while (and (search-forward string nil 'limit)
1221 (if (eq (antlr-syntactic-context) 0) (setq continue nil) t)))
1222 (if continue nil (point))))
1223
1224 (defun antlr-search-backward (string)
1225 "Search backward from point for STRING.
1226 Set point to the beginning of the occurrence found, and return point.
1227 Return nil if no occurrence was found. Do not search within comments,
1228 strings and actions/semantic predicates."
1229 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1230 (let ((continue t))
1231 (while (and (search-backward string nil 'limit)
1232 (if (eq (antlr-syntactic-context) 0) (setq continue nil) t)))
1233 (if continue nil (point))))
1234
1235 (defsubst antlr-skip-sexps (count)
1236 "Skip the next COUNT balanced expressions and the comments after it.
1237 Return position before the comments after the last expression."
1238 (goto-char (or (ignore-errors-x (scan-sexps (point) count)) (point-max)))
1239 (prog1 (point)
1240 (antlr-c-forward-sws)))
1241
1242
1243 ;;;===========================================================================
1244 ;;; font-lock
1245 ;;;===========================================================================
1246
1247 (defun antlr-font-lock-keywords ()
1248 "Return font-lock keywords for current buffer.
1249 See `antlr-font-lock-additional-keywords', `antlr-language' and
1250 `antlr-font-lock-maximum-decoration'."
1251 (if (eq antlr-font-lock-maximum-decoration 'none)
1252 antlr-font-lock-additional-keywords
1253 (append antlr-font-lock-additional-keywords
1254 (eval (let ((major-mode antlr-language)) ; dynamic
1255 (font-lock-choose-keywords
1256 (cdr (assq antlr-language
1257 antlr-font-lock-keywords-alist))
1258 (if (eq antlr-font-lock-maximum-decoration 'inherit)
1259 font-lock-maximum-decoration
1260 antlr-font-lock-maximum-decoration)))))))
1261
1262
1263 ;;;===========================================================================
1264 ;;; imenu support
1265 ;;;===========================================================================
1266
1267 (defun antlr-grammar-tokens ()
1268 "Return alist for tokens defined in current buffer."
1269 (save-excursion (antlr-imenu-create-index-function t)))
1270
1271 (defun antlr-imenu-create-index-function (&optional tokenrefs-only)
1272 "Return imenu index-alist for ANTLR grammar files.
1273 IF TOKENREFS-ONLY is non-nil, just return alist with tokenref names."
1274 (let ((items nil)
1275 (classes nil)
1276 (continue t))
1277 ;; Using `imenu-progress-message' would require imenu for compilation, but
1278 ;; nobody is missing these messages. The generic imenu function searches
1279 ;; backward, which is slower and more likely not to work during editing.
1280 (antlr-with-syntax-table antlr-action-syntax-table
1281 (antlr-invalidate-context-cache)
1282 (goto-char (point-min))
1283 (antlr-skip-file-prelude t)
1284 (while continue
1285 (if (looking-at "{") (antlr-skip-sexps 1))
1286 (if (looking-at antlr-class-header-regexp)
1287 (or tokenrefs-only
1288 (push (cons (match-string 2)
1289 (if imenu-use-markers
1290 (copy-marker (match-beginning 2))
1291 (match-beginning 2)))
1292 classes))
1293 (if (looking-at "p\\(ublic\\|rotected\\|rivate\\)")
1294 (antlr-skip-sexps 1))
1295 (when (looking-at "\\sw+")
1296 (if tokenrefs-only
1297 (if (antlr-upcase-p (char-after (point)))
1298 (push (list (match-string 0)) items))
1299 (push (cons (match-string 0)
1300 (if imenu-use-markers
1301 (copy-marker (match-beginning 0))
1302 (match-beginning 0)))
1303 items))))
1304 (if (setq continue (antlr-search-forward ";"))
1305 (antlr-skip-exception-part t))))
1306 (if classes
1307 (cons (cons "Classes" (nreverse classes)) (nreverse items))
1308 (nreverse items))))
1309
1310
1311 ;;;===========================================================================
1312 ;;; Parse grammar files (internal functions)
1313 ;;;===========================================================================
1314
1315 (defun antlr-skip-exception-part (skip-comment)
1316 "Skip exception part of current rule, i.e., everything after `;'.
1317 This also includes the options and tokens part of a grammar class
1318 header. If SKIP-COMMENT is non-nil, also skip the comment after that
1319 part."
1320 (let ((pos (point))
1321 (class nil))
1322 (antlr-c-forward-sws)
1323 (while (looking-at "options\\>\\|tokens\\>")
1324 (setq class t)
1325 (setq pos (antlr-skip-sexps 2)))
1326 (if class
1327 ;; Problem: an action only belongs to a class def, not a normal rule.
1328 ;; But checking the current rule type is too expensive => only expect
1329 ;; an action if we have found an option or tokens part.
1330 (if (looking-at "{") (setq pos (antlr-skip-sexps 1)))
1331 (while (looking-at "exception\\>")
1332 (setq pos (antlr-skip-sexps 1))
1333 (when (looking-at "\\[")
1334 (setq pos (antlr-skip-sexps 1)))
1335 (while (looking-at "catch\\>")
1336 (setq pos (antlr-skip-sexps 3)))))
1337 (or skip-comment (goto-char pos))))
1338
1339 (defun antlr-skip-file-prelude (skip-comment)
1340 "Skip the file prelude: the header and file options.
1341 If SKIP-COMMENT is non-nil, also skip the comment after that part.
1342 Return the start position of the file prelude.
1343
1344 Hack: if SKIP-COMMENT is `header-only' only skip header and return
1345 position before the comment after the header."
1346 (let* ((pos (point))
1347 (pos0 pos))
1348 (antlr-c-forward-sws)
1349 (if skip-comment (setq pos0 (point)))
1350 (while (looking-at "header\\>[ \t]*\\(\"\\)?")
1351 (setq pos (antlr-skip-sexps (if (match-beginning 1) 3 2))))
1352 (if (eq skip-comment 'header-only) ; a hack...
1353 pos
1354 (when (looking-at "options\\>")
1355 (setq pos (antlr-skip-sexps 2)))
1356 (or skip-comment (goto-char pos))
1357 pos0)))
1358
1359 (defun antlr-next-rule (arg skip-comment)
1360 "Move forward to next end of rule. Do it ARG many times.
1361 A grammar class header and the file prelude are also considered as a
1362 rule. Negative argument ARG means move back to ARGth preceding end of
1363 rule. The behavior is not defined when ARG is zero. If SKIP-COMMENT
1364 is non-nil, move to beginning of the rule."
1365 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1366 ;; PRE: ARG<>0
1367 (let ((pos (point))
1368 (beg (point)))
1369 ;; first look whether point is in exception part
1370 (if (antlr-search-backward ";")
1371 (progn
1372 (setq beg (point))
1373 (forward-char)
1374 (antlr-skip-exception-part skip-comment))
1375 (antlr-skip-file-prelude skip-comment))
1376 (if (< arg 0)
1377 (unless (and (< (point) pos) (zerop (incf arg)))
1378 ;; if we have moved backward, we already moved one defun backward
1379 (goto-char beg) ; rewind (to ";" / point)
1380 (while (and arg (<= (incf arg) 0))
1381 (if (antlr-search-backward ";")
1382 (setq beg (point))
1383 (when (>= arg -1)
1384 ;; try file prelude:
1385 (setq pos (antlr-skip-file-prelude skip-comment))
1386 (if (zerop arg)
1387 (if (>= (point) beg)
1388 (goto-char (if (>= pos beg) (point-min) pos)))
1389 (goto-char (if (or (>= (point) beg) (= (point) pos))
1390 (point-min) pos))))
1391 (setq arg nil)))
1392 (when arg ; always found a ";"
1393 (forward-char)
1394 (antlr-skip-exception-part skip-comment)))
1395 (if (<= (point) pos) ; moved backward?
1396 (goto-char pos) ; rewind
1397 (decf arg)) ; already moved one defun forward
1398 (unless (zerop arg)
1399 (while (>= (decf arg) 0)
1400 (antlr-search-forward ";"))
1401 (antlr-skip-exception-part skip-comment)))))
1402
1403 (defun antlr-outside-rule-p ()
1404 "Non-nil if point is outside a grammar rule.
1405 Move to the beginning of the current rule if point is inside a rule."
1406 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1407 (let ((pos (point)))
1408 (antlr-next-rule -1 nil)
1409 (let ((between (or (bobp) (< (point) pos))))
1410 (antlr-c-forward-sws)
1411 (and between (> (point) pos) (goto-char pos)))))
1412
1413
1414 ;;;===========================================================================
1415 ;;; Parse grammar files (commands)
1416 ;;;===========================================================================
1417 ;; No (interactive "_") in Emacs... use `zmacs-region-stays'.
1418
1419 (defun antlr-inside-rule-p ()
1420 "Non-nil if point is inside a grammar rule.
1421 A grammar class header and the file prelude are also considered as a
1422 rule."
1423 (save-excursion
1424 (antlr-with-syntax-table antlr-action-syntax-table
1425 (not (antlr-outside-rule-p)))))
1426
1427 (defunx antlr-end-of-rule (&optional arg)
1428 "Move forward to next end of rule. Do it ARG [default: 1] many times.
1429 A grammar class header and the file prelude are also considered as a
1430 rule. Negative argument ARG means move back to ARGth preceding end of
1431 rule. If ARG is zero, run `antlr-end-of-body'."
1432 (interactive "_p")
1433 (if (zerop arg)
1434 (antlr-end-of-body)
1435 (antlr-with-syntax-table antlr-action-syntax-table
1436 (antlr-next-rule arg nil))))
1437
1438 (defunx antlr-beginning-of-rule (&optional arg)
1439 "Move backward to preceding beginning of rule. Do it ARG many times.
1440 A grammar class header and the file prelude are also considered as a
1441 rule. Negative argument ARG means move forward to ARGth next beginning
1442 of rule. If ARG is zero, run `antlr-beginning-of-body'."
1443 (interactive "_p")
1444 (if (zerop arg)
1445 (antlr-beginning-of-body)
1446 (antlr-with-syntax-table antlr-action-syntax-table
1447 (antlr-next-rule (- arg) t))))
1448
1449 (defunx antlr-end-of-body (&optional msg)
1450 "Move to position after the `;' of the current rule.
1451 A grammar class header is also considered as a rule. With optional
1452 prefix arg MSG, move to `:'."
1453 (interactive "_")
1454 (antlr-with-syntax-table antlr-action-syntax-table
1455 (let ((orig (point)))
1456 (if (antlr-outside-rule-p)
1457 (error "Outside an ANTLR rule"))
1458 (let ((bor (point)))
1459 (when (< (antlr-skip-file-prelude t) (point))
1460 ;; Yes, we are in the file prelude
1461 (goto-char orig)
1462 (error (or msg "The file prelude is without `;'")))
1463 (antlr-search-forward ";")
1464 (when msg
1465 (when (< (point)
1466 (progn (goto-char bor)
1467 (or (antlr-search-forward ":") (point-max))))
1468 (goto-char orig)
1469 (error msg))
1470 (antlr-c-forward-sws))))))
1471
1472 (defunx antlr-beginning-of-body ()
1473 "Move to the first element after the `:' of the current rule."
1474 (interactive "_")
1475 (antlr-end-of-body "Class headers and the file prelude are without `:'"))
1476
1477
1478 ;;;===========================================================================
1479 ;;; Literal normalization, Hide Actions
1480 ;;;===========================================================================
1481
1482 (defun antlr-downcase-literals (&optional transform)
1483 "Convert all literals in buffer to lower case.
1484 If non-nil, TRANSFORM is used on literals instead of `downcase-region'."
1485 (interactive)
1486 (or transform (setq transform 'downcase-region))
1487 (let ((literals 0))
1488 (save-excursion
1489 (goto-char (point-min))
1490 (antlr-with-syntax-table antlr-action-syntax-table
1491 (antlr-invalidate-context-cache)
1492 (while (antlr-re-search-forward "\"\\(\\sw\\(\\sw\\|-\\)*\\)\"" nil)
1493 (funcall transform (match-beginning 0) (match-end 0))
1494 (incf literals))))
1495 (message "Transformed %d literals" literals)))
1496
1497 (defun antlr-upcase-literals ()
1498 "Convert all literals in buffer to upper case."
1499 (interactive)
1500 (antlr-downcase-literals 'upcase-region))
1501
1502 (defun antlr-hide-actions (arg &optional silent)
1503 "Hide or unhide all actions in buffer.
1504 Hide all actions including arguments in brackets if ARG is 1 or if
1505 called interactively without prefix argument. Hide all actions
1506 excluding arguments in brackets if ARG is 2 or higher. Unhide all
1507 actions if ARG is 0 or negative. See `antlr-action-visibility'.
1508
1509 Display a message unless optional argument SILENT is non-nil."
1510 (interactive "p")
1511 (save-buffer-state-x
1512 (if (> arg 0)
1513 (let ((regexp (if (= arg 1) "[]}]" "}"))
1514 (diff (and antlr-action-visibility
1515 (+ (max antlr-action-visibility 0) 2))))
1516 (antlr-hide-actions 0 t)
1517 (save-excursion
1518 (goto-char (point-min))
1519 (antlr-with-syntax-table antlr-action-syntax-table
1520 (antlr-invalidate-context-cache)
1521 (while (antlr-re-search-forward regexp nil)
1522 (let ((beg (ignore-errors-x (scan-sexps (point) -1))))
1523 (when beg
1524 (if diff ; braces are visible
1525 (if (> (point) (+ beg diff))
1526 (add-text-properties (1+ beg) (1- (point))
1527 '(invisible t intangible t)))
1528 ;; if actions is on line(s) of its own, hide WS
1529 (and (looking-at "[ \t]*$")
1530 (save-excursion
1531 (goto-char beg)
1532 (skip-chars-backward " \t")
1533 (and (bolp) (setq beg (point))))
1534 (beginning-of-line 2)) ; beginning of next line
1535 (add-text-properties beg (point)
1536 '(invisible t intangible t))))))))
1537 (or silent
1538 (message "Hide all actions (%s arguments)...done"
1539 (if (= arg 1) "including" "excluding"))))
1540 (remove-text-properties (point-min) (point-max)
1541 '(invisible nil intangible nil))
1542 (or silent
1543 (message "Unhide all actions (including arguments)...done")))))
1544
1545
1546 ;;;===========================================================================
1547 ;;; Insert option: command
1548 ;;;===========================================================================
1549
1550 (defun antlr-insert-option (level option &optional location)
1551 "Insert file/grammar/rule/subrule option near point.
1552 LEVEL determines option kind to insert: 1=file, 2=grammar, 3=rule,
1553 4=subrule. OPTION is a string with the name of the option to insert.
1554 LOCATION can be specified for not calling `antlr-option-kind' twice.
1555
1556 Inserting an option with this command works as follows:
1557
1558 1. When called interactively, LEVEL is determined by the prefix
1559 argument or automatically deduced without prefix argument.
1560 2. Signal an error if no option of that level could be inserted, e.g.,
1561 if the buffer is read-only, the option area is outside the visible
1562 part of the buffer or a subrule/rule option should be inserted with
1563 point outside a subrule/rule.
1564 3. When called interactively, OPTION is read from the minibuffer with
1565 completion over the known options of the given LEVEL.
1566 4. Ask user for confirmation if the given OPTION does not seem to be a
1567 valid option to insert into the current file.
1568 5. Find a correct position to insert the option.
1569 6. Depending on the option, insert it the following way \(inserting an
1570 option also means inserting the option section if necessary\):
1571 - Insert the option and let user insert the value at point.
1572 - Read a value (with completion) from the minibuffer, using a
1573 previous value as initial contents, and insert option with value.
1574 7. Final action depending on the option. For example, set the language
1575 according to a newly inserted language option.
1576
1577 The name of all options with a specification for their values are stored
1578 in `antlr-options-alists'. The used specification also depends on the
1579 value of `antlr-tool-version', i.e., step 4 will warn you if you use an
1580 option that has been introduced in newer version of ANTLR, and step 5
1581 will offer completion using version-correct values.
1582
1583 If the option already exists inside the visible part of the buffer, this
1584 command can be used to change the value of that option. Otherwise, find
1585 a correct position where the option can be inserted near point.
1586
1587 The search for a correct position is as follows:
1588
1589 * If search is within an area where options can be inserted, use the
1590 position of point. Inside the options section and if point is in
1591 the middle of a option definition, skip the rest of it.
1592 * If an options section already exists, insert the options at the end.
1593 If only the beginning of the area is visible, insert at the
1594 beginning.
1595 * Otherwise, find the position where an options section can be
1596 inserted and insert a new section before any comments. If the
1597 position before the comments is not visible, insert the new section
1598 after the comments.
1599
1600 This function also inserts \"options {...}\" and the \":\" if necessary,
1601 see `antlr-options-auto-colon'. See also `antlr-options-assign-string'.
1602
1603 This command might also set the mark like \\[set-mark-command] does, see
1604 `antlr-options-push-mark'."
1605 (interactive (antlr-insert-option-interactive current-prefix-arg))
1606 (barf-if-buffer-read-only)
1607 (or location (setq location (cdr (antlr-option-kind level))))
1608 (cond ((null level)
1609 (error "Cannot deduce what kind of option to insert"))
1610 ((atom location)
1611 (error "Cannot insert any %s options around here"
1612 (elt antlr-options-headings (1- level)))))
1613 (let ((area (car location))
1614 (place (cdr location)))
1615 (cond ((null place) ; invisible
1616 (error (if area
1617 "Invisible %s options, use %s to make them visible"
1618 "Invisible area for %s options, use %s to make it visible")
1619 (elt antlr-options-headings (1- level))
1620 (substitute-command-keys "\\[widen]")))
1621 ((null area) ; without option part
1622 (antlr-insert-option-do level option nil
1623 (null (cdr place))
1624 (car place)))
1625 ((save-excursion ; with option part, option visible
1626 (goto-char (max (point-min) (car area)))
1627 (re-search-forward (concat "\\(^\\|;\\)[ \t]*\\(\\<"
1628 (regexp-quote option)
1629 "\\>\\)[ \t\n]*\\(\\(=[ \t]?\\)[ \t]*\\(\\(\\sw\\|\\s_\\)+\\|\"\\([^\n\"\\]\\|[\\][^\n]\\)*\"\\)?\\)?")
1630 ;; 2=name, 3=4+5, 4="=", 5=value
1631 (min (point-max) (cdr area))
1632 t))
1633 (antlr-insert-option-do level option
1634 (cons (or (match-beginning 5)
1635 (match-beginning 3))
1636 (match-end 5))
1637 (and (null (cdr place)) area)
1638 (or (match-beginning 5)
1639 (match-end 4)
1640 (match-end 2))))
1641 (t ; with option part, option not yet
1642 (antlr-insert-option-do level option t
1643 (and (null (cdr place)) area)
1644 (car place))))))
1645
1646 (defun antlr-insert-option-interactive (arg)
1647 "Interactive specification for `antlr-insert-option'.
1648 Return \(LEVEL OPTION LOCATION)."
1649 (barf-if-buffer-read-only)
1650 (if arg (setq arg (prefix-numeric-value arg)))
1651 (unless (memq arg '(nil 1 2 3 4))
1652 (error "Valid prefix args: no=auto, 1=file, 2=grammar, 3=rule, 4=subrule"))
1653 (let* ((kind (antlr-option-kind arg))
1654 (level (car kind)))
1655 (if (atom (cdr kind))
1656 (list level nil (cdr kind))
1657 (let* ((table (elt antlr-options-alists (1- level)))
1658 (completion-ignore-case t) ;dynamic
1659 (input (completing-read (format "Insert %s option: "
1660 (elt antlr-options-headings
1661 (1- level)))
1662 table)))
1663 (list level input (cdr kind))))))
1664
1665 (defun antlr-options-menu-filter (level menu-items)
1666 "Return items for options submenu of level LEVEL."
1667 ;; checkdoc-params: (menu-items)
1668 (let ((active (if buffer-read-only
1669 nil
1670 (consp (cdr-safe (cdr (antlr-option-kind level)))))))
1671 (mapcar (lambda (option)
1672 (vector option
1673 (list 'antlr-insert-option level option)
1674 :active active))
1675 (sort (mapcar 'car (elt antlr-options-alists (1- level)))
1676 'string-lessp))))
1677
1678
1679 ;;;===========================================================================
1680 ;;; Insert option: determine section-kind
1681 ;;;===========================================================================
1682
1683 (defun antlr-option-kind (requested)
1684 "Return level and location for option to insert near point.
1685 Call function `antlr-option-level' with argument REQUESTED. If the
1686 result is nil, return \(REQUESTED \. error). If the result has the
1687 non-nil value LEVEL, return \(LEVEL \. LOCATION) where LOCATION looks
1688 like \(AREA \. PLACE), see `antlr-option-location'."
1689 (save-excursion
1690 (save-restriction
1691 (let ((min0 (point-min)) ; before `widen'!
1692 (max0 (point-max))
1693 (orig (point))
1694 (level (antlr-option-level requested)) ; calls `widen'!
1695 pos)
1696 (cond ((null level)
1697 (setq level requested))
1698 ((eq level 1) ; file options
1699 (goto-char (point-min))
1700 (setq pos (antlr-skip-file-prelude 'header-only)))
1701 ((not (eq level 3)) ; grammar or subrule options
1702 (setq pos (point))
1703 (antlr-c-forward-sws))
1704 ((looking-at "^\\(private[ \t\n]\\|public[ \t\n]\\|protected[ \t\n]\\)?[ \t\n]*\\(\\(\\sw\\|\\s_\\)+\\)[ \t\n]*\\(!\\)?[ \t\n]*\\(\\[\\)?")
1705 ;; rule options, with complete rule header
1706 (goto-char (or (match-end 4) (match-end 3)))
1707 (setq pos (antlr-skip-sexps (if (match-end 5) 1 0)))
1708 (when (looking-at "returns[ \t\n]*\\[")
1709 (goto-char (1- (match-end 0)))
1710 (setq pos (antlr-skip-sexps 1)))))
1711 (cons level
1712 (cond ((null pos) 'error)
1713 ((looking-at "options[ \t\n]*{")
1714 (goto-char (match-end 0))
1715 (setq pos (ignore-errors-x (scan-lists (point) 1 1)))
1716 (antlr-option-location orig min0 max0
1717 (point)
1718 (if pos (1- pos) (point-max))
1719 t))
1720 (t
1721 (antlr-option-location orig min0 max0
1722 pos (point)
1723 nil))))))))
1724
1725 (defun antlr-option-level (requested)
1726 "Return level for option to insert near point.
1727 Remove any restrictions from current buffer and return level for the
1728 option to insert near point, i.e., 1, 2, 3, 4, or nil if no such option
1729 can be inserted. If REQUESTED is non-nil, it is the only possible value
1730 to return except nil. If REQUESTED is nil, return level for the nearest
1731 option kind, i.e., the highest number possible.
1732
1733 If the result is 2, point is at the beginning of the class after the
1734 class definition. If the result is 3 or 4, point is at the beginning of
1735 the rule/subrule after the init action. Otherwise, the point position
1736 is undefined."
1737 (widen)
1738 (if (eq requested 1)
1739 1
1740 (antlr-with-syntax-table antlr-action-syntax-table
1741 (antlr-invalidate-context-cache)
1742 (let* ((orig (point))
1743 (outsidep (antlr-outside-rule-p))
1744 bor depth)
1745 (if (eq (char-after) ?\{) (antlr-skip-sexps 1))
1746 (setq bor (point)) ; beginning of rule (after init action)
1747 (cond ((eq requested 2) ; grammar options required?
1748 (let (boc) ; beginning of class
1749 (goto-char (point-min))
1750 (while (and (<= (point) bor)
1751 (antlr-re-search-forward antlr-class-header-regexp
1752 nil))
1753 (if (<= (match-beginning 0) bor)
1754 (setq boc (match-end 0))))
1755 (when boc
1756 (goto-char boc)
1757 2)))
1758 ((save-excursion ; in region of file options?
1759 (goto-char (point-min))
1760 (antlr-skip-file-prelude t) ; ws/comment after: OK
1761 (< orig (point)))
1762 (and (null requested) 1))
1763 (outsidep ; outside rule not OK
1764 nil)
1765 ((looking-at antlr-class-header-regexp) ; rule = class def?
1766 (goto-char (match-end 0))
1767 (and (null requested) 2))
1768 ((eq requested 3) ; rule options required?
1769 (goto-char bor)
1770 3)
1771 ((setq depth (antlr-syntactic-grammar-depth orig bor))
1772 (if (> depth 0) ; move out of actions
1773 (goto-char (scan-lists (point) -1 depth)))
1774 (set-syntax-table antlr-mode-syntax-table)
1775 (antlr-invalidate-context-cache)
1776 (if (eq (antlr-syntactic-context) 0) ; not in subrule?
1777 (unless (eq requested 4)
1778 (goto-char bor)
1779 3)
1780 (goto-char (1+ (scan-lists (point) -1 1)))
1781 4)))))))
1782
1783 (defun antlr-option-location (orig min-vis max-vis min-area max-area withp)
1784 "Return location for the options area.
1785 ORIG is the original position of `point', MIN-VIS is `point-min' and
1786 MAX-VIS is `point-max'. If WITHP is non-nil, there exists an option
1787 specification and it starts after the brace at MIN-AREA and stops at
1788 MAX-AREA. If WITHP is nil, there is no area and the region where it
1789 could be inserted starts at MIN-AREA and stops at MAX-AREA.
1790
1791 The result has the form (AREA . PLACE). AREA is (MIN-AREA . MAX-AREA)
1792 if WITHP is non-nil, and nil otherwise. PLACE is nil if the area is
1793 invisible, (ORIG) if ORIG is inside the area, (MIN-AREA . beginning) for
1794 a visible start position and (MAX-AREA . end) for a visible end position
1795 where the beginning is preferred if WITHP is nil and the end if WITHP is
1796 non-nil."
1797 (cons (and withp (cons min-area max-area))
1798 (cond ((and (<= min-area orig) (<= orig max-area)
1799 (save-excursion
1800 (goto-char orig)
1801 (not (memq (antlr-syntactic-context)
1802 '(comment block-comment)))))
1803 ;; point in options area and not in comment
1804 (list orig))
1805 ((and (null withp) (<= min-vis min-area) (<= min-area max-vis))
1806 ;; use start of options area (only if not `withp')
1807 (cons min-area 'beginning))
1808 ((and (<= min-vis max-area) (<= max-area max-vis))
1809 ;; use end of options area
1810 (cons max-area 'end))
1811 ((and withp (<= min-vis min-area) (<= min-area max-vis))
1812 ;; use start of options area (only if `withp')
1813 (cons min-area 'beginning)))))
1814
1815 (defun antlr-syntactic-grammar-depth (pos beg)
1816 "Return syntactic context depth at POS.
1817 Move to POS and from there on to the beginning of the string or comment
1818 if POS is inside such a construct. Then, return the syntactic context
1819 depth at point if the point position is smaller than BEG.
1820 WARNING: this may alter `match-data'."
1821 (goto-char pos)
1822 (let ((context (or (antlr-syntactic-context) 0)))
1823 (while (and context (not (integerp context)))
1824 (cond ((eq context 'string)
1825 (setq context
1826 (and (search-backward "\"" nil t)
1827 (>= (point) beg)
1828 (or (antlr-syntactic-context) 0))))
1829 ((memq context '(comment block-comment))
1830 (setq context
1831 (and (re-search-backward "/[/*]" nil t)
1832 (>= (point) beg)
1833 (or (antlr-syntactic-context) 0))))))
1834 context))
1835
1836
1837 ;;;===========================================================================
1838 ;;; Insert options: do the insertion
1839 ;;;===========================================================================
1840
1841 (defun antlr-insert-option-do (level option old area pos)
1842 "Insert option into buffer at position POS.
1843 Insert option of level LEVEL and name OPTION. If OLD is non-nil, an
1844 options area is already exists. If OLD looks like \(BEG \. END), the
1845 option already exists. Then, BEG is the start position of the option
1846 value, the position of the `=' or nil, and END is the end position of
1847 the option value or nil.
1848
1849 If the original point position was outside an options area, AREA is nil.
1850 Otherwise, and if an option specification already exists, AREA is a cons
1851 cell where the two values determine the area inside the braces."
1852 (let* ((spec (cdr (assoc option (elt antlr-options-alists (1- level)))))
1853 (value (antlr-option-spec level option (cdr spec) (consp old))))
1854 (if (fboundp (car spec)) (funcall (car spec) 'before-input option))
1855 ;; set mark (unless point was inside options area before)
1856 (if (cond (area (eq antlr-options-push-mark t))
1857 ((numberp antlr-options-push-mark)
1858 (> (count-lines (min (point) pos) (max (point) pos))
1859 antlr-options-push-mark))
1860 (antlr-options-push-mark))
1861 (push-mark))
1862 ;; read option value -----------------------------------------------------
1863 (goto-char pos)
1864 (if (null value)
1865 ;; no option specification found
1866 (if (y-or-n-p (format "Insert unknown %s option %s? "
1867 (elt antlr-options-headings (1- level))
1868 option))
1869 (message "Insert value for %s option %s"
1870 (elt antlr-options-headings (1- level))
1871 option)
1872 (error "Didn't insert unknown %s option %s"
1873 (elt antlr-options-headings (1- level))
1874 option))
1875 ;; option specification found
1876 (setq value (cdr value))
1877 (if (car value)
1878 (let ((initial (and (consp old) (cdr old)
1879 (buffer-substring (car old) (cdr old)))))
1880 (setq value (apply (car value)
1881 (and initial
1882 (if (eq (aref initial 0) ?\")
1883 (read initial)
1884 initial))
1885 (cdr value))))
1886 (message "%s" (or (cadr value) ""))
1887 (setq value nil)))
1888 ;; insert value ----------------------------------------------------------
1889 (if (consp old)
1890 (antlr-insert-option-existing old value)
1891 (if (consp area)
1892 ;; Move outside string/comment if point is inside option spec
1893 (antlr-syntactic-grammar-depth (point) (car area)))
1894 (antlr-insert-option-space area old)
1895 (or old (antlr-insert-option-area level))
1896 (insert option " = ;")
1897 (backward-char)
1898 (if value (insert value)))
1899 ;; final -----------------------------------------------------------------
1900 (if (fboundp (car spec)) (funcall (car spec) 'after-insertion option))))
1901
1902 (defun antlr-option-spec (level option specs existsp)
1903 "Return version correct option value specification.
1904 Return specification for option OPTION of kind level LEVEL. SPECS
1905 should correspond to the VALUE-SPEC... in `antlr-option-alists'.
1906 EXISTSP determines whether the option already exists."
1907 (let (value)
1908 (while (and specs (>= antlr-tool-version (caar specs)))
1909 (setq value (pop specs)))
1910 (cond (value) ; found correct spec
1911 ((null specs) nil) ; didn't find any specs
1912 (existsp (car specs)) ; wrong version, but already present
1913 ((y-or-n-p (format "Insert v%s %s option %s in v%s? "
1914 (antlr-version-string (caar specs))
1915 (elt antlr-options-headings (1- level))
1916 option
1917 (antlr-version-string antlr-tool-version)))
1918 (car specs))
1919 (t
1920 (error "Didn't insert v%s %s option %s in v%s"
1921 (antlr-version-string (caar specs))
1922 (elt antlr-options-headings (1- level))
1923 option
1924 (antlr-version-string antlr-tool-version))))))
1925
1926 (defun antlr-version-string (version)
1927 "Format the Antlr version number VERSION, see `antlr-tool-version'."
1928 (let ((version100 (/ version 100)))
1929 (format "%d.%d.%d"
1930 (/ version100 100) (mod version100 100) (mod version 100))))
1931
1932
1933 ;;;===========================================================================
1934 ;;; Insert options: the details (used by `antlr-insert-option-do')
1935 ;;;===========================================================================
1936
1937 (defun antlr-insert-option-existing (old value)
1938 "Insert option value VALUE at point for existing option.
1939 For OLD, see `antlr-insert-option-do'."
1940 ;; no = => insert =
1941 (unless (car old) (insert antlr-options-assign-string))
1942 ;; with user input => insert if necessary
1943 (when value
1944 (if (cdr old) ; with value
1945 (if (string-equal value (buffer-substring (car old) (cdr old)))
1946 (goto-char (cdr old))
1947 (delete-region (car old) (cdr old))
1948 (insert value))
1949 (insert value)))
1950 (unless (looking-at "\\([^\n=;{}/'\"]\\|'\\([^\n'\\]\\|\\\\.\\)*'\\|\"\\([^\n\"\\]\\|\\\\.\\)*\"\\)*;")
1951 ;; stuff (no =, {, } or /) at point is not followed by ";"
1952 (insert ";")
1953 (backward-char)))
1954
1955 (defun antlr-insert-option-space (area old)
1956 "Find appropriate place to insert option, insert newlines/spaces.
1957 For AREA and OLD, see `antlr-insert-option-do'."
1958 (let ((orig (point))
1959 (open t))
1960 (skip-chars-backward " \t")
1961 (unless (bolp)
1962 (let ((before (char-after (1- (point)))))
1963 (goto-char orig)
1964 (and old ; with existing options area
1965 (consp area) ; if point inside existing area
1966 (not (eq before ?\;)) ; if not at beginning of option
1967 ; => skip to end of option
1968 (if (and (search-forward ";" (cdr area) t)
1969 (let ((context (antlr-syntactic-context)))
1970 (or (null context) (numberp context))))
1971 (setq orig (point))
1972 (goto-char orig)))
1973 (skip-chars-forward " \t")
1974
1975 (if (looking-at "$\\|//")
1976 ;; just comment after point => skip (+ lines w/ same col comment)
1977 (let ((same (if (> (match-end 0) (match-beginning 0))
1978 (current-column))))
1979 (beginning-of-line 2)
1980 (or (bolp) (insert "\n"))
1981 (when (and same (null area)) ; or (consp area)?
1982 (while (and (looking-at "[ \t]*\\(//\\)")
1983 (goto-char (match-beginning 1))
1984 (= (current-column) same))
1985 (beginning-of-line 2)
1986 (or (bolp) (insert "\n")))))
1987 (goto-char orig)
1988 (if (null old)
1989 (progn (insert "\n") (antlr-indent-line))
1990 (unless (eq (char-after (1- (point))) ?\ )
1991 (insert " "))
1992 (unless (eq (char-after (point)) ?\ )
1993 (insert " ")
1994 (backward-char))
1995 (setq open nil)))))
1996 (when open
1997 (beginning-of-line 1)
1998 (insert "\n")
1999 (backward-char)
2000 (antlr-indent-line))))
2001
2002 (defun antlr-insert-option-area (level)
2003 "Insert new options area for options of level LEVEL.
2004 Used by `antlr-insert-option-do'."
2005 (insert "options {\n\n}")
2006 (when (and antlr-options-auto-colon
2007 (memq level '(3 4))
2008 (save-excursion
2009 (antlr-c-forward-sws)
2010 (if (eq (char-after (point)) ?\{) (antlr-skip-sexps 1))
2011 (not (eq (char-after (point)) ?\:))))
2012 (insert "\n:")
2013 (antlr-indent-line)
2014 (end-of-line 0))
2015 (backward-char 1)
2016 (antlr-indent-line)
2017 (beginning-of-line 0)
2018 (antlr-indent-line))
2019
2020
2021 ;;;===========================================================================
2022 ;;; Insert options: in `antlr-options-alists'
2023 ;;;===========================================================================
2024
2025 (defun antlr-read-value (initial-contents prompt
2026 &optional as-string table table-x)
2027 "Read a string from the minibuffer, possibly with completion.
2028 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
2029 PROMPT is a string to prompt with, normally it ends in a colon and a
2030 space. If AS-STRING is t or is a member \(comparison done with `eq') of
2031 `antlr-options-style', return printed representation of the user input,
2032 otherwise return the user input directly.
2033
2034 If TABLE or TABLE-X is non-nil, read with completion. The completion
2035 table is the resulting alist of TABLE-X concatenated with TABLE where
2036 TABLE can also be a function evaluation to an alist.
2037
2038 Used inside `antlr-options-alists'."
2039 (let* ((completion-ignore-case t) ; dynamic
2040 (table0 (and (or table table-x)
2041 (append table-x
2042 (if (functionp table) (funcall table) table))))
2043 (input (if table0
2044 (completing-read prompt table0 nil nil initial-contents)
2045 (read-from-minibuffer prompt initial-contents))))
2046 (if (and as-string
2047 (or (eq as-string t)
2048 (cdr (assq as-string antlr-options-style))))
2049 (format "%S" input)
2050 input)))
2051
2052 (defun antlr-read-boolean (initial-contents prompt &optional table)
2053 "Read a boolean value from the minibuffer, with completion.
2054 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
2055 PROMPT is a string to prompt with, normally it ends in a question mark
2056 and a space. \"(true or false) \" is appended if TABLE is nil.
2057
2058 Read with completion over \"true\", \"false\" and the keys in TABLE, see
2059 also `antlr-read-value'.
2060
2061 Used inside `antlr-options-alists'."
2062 (antlr-read-value initial-contents
2063 (if table prompt (concat prompt "(true or false) "))
2064 nil
2065 table '(("false") ("true"))))
2066
2067 (defun antlr-language-option-extra (phase &rest dummies)
2068 ;; checkdoc-params: (dummies)
2069 "Change language according to the new value of the \"language\" option.
2070 Call `antlr-mode' if the new language would be different from the value
2071 of `antlr-language', keeping the value of variable `font-lock-mode'.
2072
2073 Called in PHASE `after-insertion', see `antlr-options-alists'."
2074 (when (eq phase 'after-insertion)
2075 (let ((new-language (antlr-language-option t)))
2076 (or (null new-language)
2077 (eq new-language antlr-language)
2078 (let ((font-lock (and (boundp 'font-lock-mode) font-lock-mode)))
2079 (if font-lock (font-lock-mode 0))
2080 (antlr-mode)
2081 (and font-lock (null font-lock-mode) (font-lock-mode 1)))))))
2082
2083 (defun antlr-c++-mode-extra (phase option &rest dummies)
2084 ;; checkdoc-params: (option dummies)
2085 "Warn if C++ option is used with the wrong language.
2086 Ask user \(\"y or n\"), if a C++ only option is going to be inserted but
2087 `antlr-language' has not the value `c++-mode'.
2088
2089 Called in PHASE `before-input', see `antlr-options-alists'."
2090 (and (eq phase 'before-input)
2091 (not (eq antlr-language 'c++-mode))
2092 (not (y-or-n-p (format "Insert C++ %s option? " option)))
2093 (error "Didn't insert C++ %s option with language %s"
2094 option (cadr (assq antlr-language antlr-language-alist)))))
2095
2096
2097 ;;;===========================================================================
2098 ;;; Compute dependencies
2099 ;;;===========================================================================
2100
2101 (defun antlr-file-dependencies ()
2102 "Return dependencies for grammar in current buffer.
2103 The result looks like \(FILE \(CLASSES \. SUPERS) VOCABS \. LANGUAGE)
2104 where CLASSES = ((CLASS . CLASS-EVOCAB) ...),
2105 SUPERS = ((SUPER . USE-EVOCAB-P) ...), and
2106 VOCABS = ((EVOCAB ...) . (IVOCAB ...))
2107
2108 FILE is the current buffer's file-name without directory part and
2109 LANGUAGE is the value of `antlr-language' in the current buffer. Each
2110 EVOCAB is an export vocabulary and each IVOCAB is an import vocabulary.
2111
2112 Each CLASS is a grammar class with its export vocabulary CLASS-EVOCAB.
2113 Each SUPER is a super-grammar class where USE-EVOCAB-P indicates whether
2114 its export vocabulary is used as an import vocabulary."
2115 (unless buffer-file-name
2116 (error "Grammar buffer does not visit a file"))
2117 (let (classes export-vocabs import-vocabs superclasses default-vocab)
2118 (antlr-with-syntax-table antlr-action-syntax-table
2119 (goto-char (point-min))
2120 (while (antlr-re-search-forward antlr-class-header-regexp nil)
2121 ;; parse class definition --------------------------------------------
2122 (let* ((class (match-string 2))
2123 (sclass (match-string 4))
2124 ;; export vocab defaults to class name (first grammar in file)
2125 ;; or to the export vocab of the first grammar in file:
2126 (evocab (or default-vocab class))
2127 (ivocab nil))
2128 (goto-char (match-end 0))
2129 (antlr-c-forward-sws)
2130 (while (looking-at "options\\>\\|\\(tokens\\)\\>")
2131 (if (match-beginning 1)
2132 (antlr-skip-sexps 2)
2133 (goto-char (match-end 0))
2134 (antlr-c-forward-sws)
2135 ;; parse grammar option sections -------------------------------
2136 (when (eq (char-after (point)) ?\{)
2137 (let* ((beg (1+ (point)))
2138 (end (1- (antlr-skip-sexps 1)))
2139 (cont (point)))
2140 (goto-char beg)
2141 (if (re-search-forward "\\<exportVocab[ \t]*=[ \t]*\\([A-Za-z\300-\326\330-\337]\\sw*\\)" end t)
2142 (setq evocab (match-string 1)))
2143 (goto-char beg)
2144 (if (re-search-forward "\\<importVocab[ \t]*=[ \t]*\\([A-Za-z\300-\326\330-\337]\\sw*\\)" end t)
2145 (setq ivocab (match-string 1)))
2146 (goto-char cont)))))
2147 (unless (member sclass '("Parser" "Lexer" "TreeParser"))
2148 (let ((super (assoc sclass superclasses)))
2149 (if super
2150 (or ivocab (setcdr super t))
2151 (push (cons sclass (null ivocab)) superclasses))))
2152 ;; remember class with export vocabulary:
2153 (push (cons class evocab) classes)
2154 ;; default export vocab is export vocab of first grammar in file:
2155 (or default-vocab (setq default-vocab evocab))
2156 (or (member evocab export-vocabs) (push evocab export-vocabs))
2157 (or (null ivocab)
2158 (member ivocab import-vocabs) (push ivocab import-vocabs)))))
2159 (if classes
2160 (list* (file-name-nondirectory buffer-file-name)
2161 (cons (nreverse classes) (nreverse superclasses))
2162 (cons (nreverse export-vocabs) (nreverse import-vocabs))
2163 antlr-language))))
2164
2165 (defun antlr-directory-dependencies (dirname)
2166 "Return dependencies for all grammar files in directory DIRNAME.
2167 The result looks like \((CLASS-SPEC ...) \. \(FILE-DEP ...))
2168 where CLASS-SPEC = (CLASS (FILE \. EVOCAB) ...).
2169
2170 FILE-DEP are the dependencies for each grammar file in DIRNAME, see
2171 `antlr-file-dependencies'. For each grammar class CLASS, FILE is a
2172 grammar file in which CLASS is defined and EVOCAB is the name of the
2173 export vocabulary specified in that file."
2174 (let ((grammar (directory-files dirname t "\\.g\\'")))
2175 (when grammar
2176 (let ((temp-buffer (get-buffer-create
2177 (generate-new-buffer-name " *temp*")))
2178 (antlr-imenu-name nil) ; dynamic-let: no imenu
2179 (expanded-regexp (concat (format (regexp-quote
2180 (cadr antlr-special-file-formats))
2181 ".+")
2182 "\\'"))
2183 classes dependencies)
2184 (unwind-protect
2185 (save-excursion
2186 (set-buffer temp-buffer)
2187 (widen) ; just in case...
2188 (dolist (file grammar)
2189 (when (and (file-regular-p file)
2190 (null (string-match expanded-regexp file)))
2191 (insert-file-contents file t nil nil t)
2192 (normal-mode t) ; necessary for major-mode, syntax
2193 ; table and `antlr-language'
2194 (when (eq major-mode 'antlr-mode)
2195 (let* ((file-deps (antlr-file-dependencies))
2196 (file (car file-deps)))
2197 (when file-deps
2198 (dolist (class-def (caadr file-deps))
2199 (let ((file-evocab (cons file (cdr class-def)))
2200 (class-spec (assoc (car class-def) classes)))
2201 (if class-spec
2202 (nconc (cdr class-spec) (list file-evocab))
2203 (push (list (car class-def) file-evocab)
2204 classes))))
2205 (push file-deps dependencies)))))))
2206 (kill-buffer temp-buffer))
2207 (cons (nreverse classes) (nreverse dependencies))))))
2208
2209
2210 ;;;===========================================================================
2211 ;;; Compilation: run ANTLR tool
2212 ;;;===========================================================================
2213
2214 (defun antlr-superclasses-glibs (supers classes)
2215 "Compute the grammar lib option for the super grammars SUPERS.
2216 Look in CLASSES for the right grammar lib files for SUPERS. SUPERS is
2217 part SUPER in the result of `antlr-file-dependencies'. CLASSES is the
2218 part \(CLASS-SPEC ...) in the result of `antlr-directory-dependencies'.
2219
2220 The result looks like \(OPTION WITH-UNKNOWN GLIB ...). OPTION is the
2221 complete \"-glib\" option. WITH-UNKNOWN is t if there is none or more
2222 than one grammar file for at least one super grammar.
2223
2224 Each GLIB looks like \(GRAMMAR-FILE \. EVOCAB). GRAMMAR-FILE is a file
2225 in which a super-grammar is defined. EVOCAB is the value of the export
2226 vocabulary of the super-grammar or nil if it is not needed."
2227 ;; If the superclass is defined in the same file, that file will be included
2228 ;; with -glib again. This will lead to a redefinition. But defining a
2229 ;; analyzer of the same class twice in a file will lead to an error anyway...
2230 (let (glibs unknown)
2231 (while supers
2232 (let* ((super (pop supers))
2233 (sup-files (cdr (assoc (car super) classes)))
2234 (file (and sup-files (null (cdr sup-files)) (car sup-files))))
2235 (or file (setq unknown t)) ; not exactly one file
2236 (push (cons (or (car file)
2237 (format (car antlr-unknown-file-formats)
2238 (car super)))
2239 (and (cdr super)
2240 (or (cdr file)
2241 (format (cadr antlr-unknown-file-formats)
2242 (car super)))))
2243 glibs)))
2244 (cons (if glibs (concat " -glib " (mapconcat 'car glibs ";")) "")
2245 (cons unknown glibs))))
2246
2247 (defun antlr-run-tool (command file &optional saved)
2248 "Run Antlr took COMMAND on grammar FILE.
2249 When called interactively, COMMAND is read from the minibuffer and
2250 defaults to `antlr-tool-command' with a computed \"-glib\" option if
2251 necessary.
2252
2253 Save all buffers first unless optional value SAVED is non-nil. When
2254 called interactively, the buffers are always saved, see also variable
2255 `antlr-ask-about-save'."
2256 (interactive (antlr-run-tool-interactive))
2257 (or saved (save-some-buffers (not antlr-ask-about-save)))
2258 (let ((default-directory (file-name-directory file)))
2259 (compilation-start (concat command " " (file-name-nondirectory file))
2260 nil #'(lambda (mode-name) "*Antlr-Run*"))))
2261
2262 (defun antlr-run-tool-interactive ()
2263 ;; code in `interactive' is not compiled
2264 "Interactive specification for `antlr-run-tool'.
2265 Use prefix argument ARG to return \(COMMAND FILE SAVED)."
2266 (let* ((supers (cdadr (save-excursion
2267 (save-restriction
2268 (widen)
2269 (antlr-file-dependencies)))))
2270 (glibs ""))
2271 (when supers
2272 (save-some-buffers (not antlr-ask-about-save) nil)
2273 (setq glibs (car (antlr-superclasses-glibs
2274 supers
2275 (car (antlr-directory-dependencies
2276 (antlr-default-directory)))))))
2277 (list (antlr-read-shell-command "Run Antlr on current file with: "
2278 (concat antlr-tool-command glibs " "))
2279 buffer-file-name
2280 supers)))
2281
2282
2283 ;;;===========================================================================
2284 ;;; Makefile creation
2285 ;;;===========================================================================
2286
2287 (defun antlr-makefile-insert-variable (number pre post)
2288 "Insert Makefile variable numbered NUMBER according to specification.
2289 Also insert strings PRE and POST before and after the variable."
2290 (let ((spec (cadr antlr-makefile-specification)))
2291 (when spec
2292 (insert pre
2293 (if number (format (cadr spec) number) (car spec))
2294 post))))
2295
2296 (defun antlr-insert-makefile-rules (&optional in-makefile)
2297 "Insert Makefile rules in the current buffer at point.
2298 IN-MAKEFILE is non-nil, if the current buffer is the Makefile. See
2299 command `antlr-show-makefile-rules' for detail."
2300 (let* ((dirname (antlr-default-directory))
2301 (deps0 (antlr-directory-dependencies dirname))
2302 (classes (car deps0)) ; CLASS -> (FILE . EVOCAB) ...
2303 (deps (cdr deps0)) ; FILE -> (c . s) (ev . iv) . LANGUAGE
2304 (with-error nil)
2305 (gen-sep (or (caddr (cadr antlr-makefile-specification)) " "))
2306 (n (and (cdr deps) (cadr antlr-makefile-specification) 0)))
2307 (or in-makefile (set-buffer standard-output))
2308 (dolist (dep deps)
2309 (let ((supers (cdadr dep))
2310 (lang (cdr (assoc (cdddr dep) antlr-file-formats-alist))))
2311 (if n (incf n))
2312 (antlr-makefile-insert-variable n "" " =")
2313 (if supers
2314 (insert " "
2315 (format (cadr antlr-special-file-formats)
2316 (file-name-sans-extension (car dep)))))
2317 (dolist (class-def (caadr dep))
2318 (let ((sep gen-sep))
2319 (dolist (class-file (cadr lang))
2320 (insert sep (format class-file (car class-def)))
2321 (setq sep " "))))
2322 (dolist (evocab (caaddr dep))
2323 (let ((sep gen-sep))
2324 (dolist (vocab-file (cons (car antlr-special-file-formats)
2325 (car lang)))
2326 (insert sep (format vocab-file evocab))
2327 (setq sep " "))))
2328 (antlr-makefile-insert-variable n "\n$(" ")")
2329 (insert ": " (car dep))
2330 (dolist (ivocab (cdaddr dep))
2331 (insert " " (format (car antlr-special-file-formats) ivocab)))
2332 (let ((glibs (antlr-superclasses-glibs supers classes)))
2333 (if (cadr glibs) (setq with-error t))
2334 (dolist (super (cddr glibs))
2335 (insert " " (car super))
2336 (if (cdr super)
2337 (insert " " (format (car antlr-special-file-formats)
2338 (cdr super)))))
2339 (insert "\n\t"
2340 (caddr antlr-makefile-specification)
2341 (car glibs)
2342 " $<\n"
2343 (car antlr-makefile-specification)))))
2344 (if n
2345 (let ((i 0))
2346 (antlr-makefile-insert-variable nil "" " =")
2347 (while (<= (incf i) n)
2348 (antlr-makefile-insert-variable i " $(" ")"))
2349 (insert "\n" (car antlr-makefile-specification))))
2350 (if (string-equal (car antlr-makefile-specification) "\n")
2351 (backward-delete-char 1))
2352 (when with-error
2353 (goto-char (point-min))
2354 (insert antlr-help-unknown-file-text))
2355 (unless in-makefile
2356 (copy-region-as-kill (point-min) (point-max))
2357 (goto-char (point-min))
2358 (insert (format antlr-help-rules-intro dirname)))))
2359
2360 ;;;###autoload
2361 (defun antlr-show-makefile-rules ()
2362 "Show Makefile rules for all grammar files in the current directory.
2363 If the `major-mode' of the current buffer has the value `makefile-mode',
2364 the rules are directory inserted at point. Otherwise, a *Help* buffer
2365 is shown with the rules which are also put into the `kill-ring' for
2366 \\[yank].
2367
2368 This command considers import/export vocabularies and grammar
2369 inheritance and provides a value for the \"-glib\" option if necessary.
2370 Customize variable `antlr-makefile-specification' for the appearance of
2371 the rules.
2372
2373 If the file for a super-grammar cannot be determined, special file names
2374 are used according to variable `antlr-unknown-file-formats' and a
2375 commentary with value `antlr-help-unknown-file-text' is added. The
2376 *Help* buffer always starts with the text in `antlr-help-rules-intro'."
2377 (interactive)
2378 (if (null (eq major-mode 'makefile-mode))
2379 (antlr-with-displaying-help-buffer 'antlr-insert-makefile-rules)
2380 (push-mark)
2381 (antlr-insert-makefile-rules t)))
2382
2383
2384 ;;;===========================================================================
2385 ;;; Indentation
2386 ;;;===========================================================================
2387
2388 (defun antlr-indent-line ()
2389 "Indent the current line as ANTLR grammar code.
2390 The indentation of grammar lines are calculated by `c-basic-offset',
2391 multiplied by:
2392 - the level of the paren/brace/bracket depth,
2393 - plus 0/2/1, depending on the position inside the rule: header, body,
2394 exception part,
2395 - minus 1 if `antlr-indent-item-regexp' matches the beginning of the
2396 line starting from the first non-whitespace.
2397
2398 Lines inside block comments are indented by `c-indent-line' according to
2399 `antlr-indent-comment'.
2400
2401 Lines in actions except top-level actions in a header part or an option
2402 area are indented by `c-indent-line'.
2403
2404 Lines in header actions are indented at column 0 if `antlr-language'
2405 equals to a key in `antlr-indent-at-bol-alist' and the line starting at
2406 the first non-whitespace is matched by the corresponding value.
2407
2408 For the initialization of `c-basic-offset', see `antlr-indent-style' and,
2409 to a lesser extent, `antlr-tab-offset-alist'."
2410 (save-restriction
2411 (let ((orig (point))
2412 (min0 (point-min))
2413 bol boi indent syntax cc-syntax)
2414 (widen)
2415 (beginning-of-line)
2416 (setq bol (point))
2417 (if (< bol min0)
2418 (error "Beginning of current line not visible"))
2419 (skip-chars-forward " \t")
2420 (setq boi (point))
2421 ;; check syntax at beginning of indentation ----------------------------
2422 (antlr-with-syntax-table antlr-action-syntax-table
2423 (antlr-invalidate-context-cache)
2424 (setq syntax (antlr-syntactic-context))
2425 (cond ((symbolp syntax)
2426 (setq indent nil)) ; block-comments, strings, (comments)
2427 ((progn
2428 (antlr-next-rule -1 t)
2429 (if (antlr-search-forward ":") (< boi (1- (point))) t))
2430 (setq indent 0)) ; in rule header
2431 ((if (antlr-search-forward ";") (< boi (point)) t)
2432 (setq indent 2)) ; in rule body
2433 (t
2434 (forward-char)
2435 (antlr-skip-exception-part nil)
2436 (setq indent (if (> (point) boi) 1 0))))) ; in exception part?
2437 ;; check whether to use indentation engine of cc-mode ------------------
2438 (antlr-invalidate-context-cache)
2439 (goto-char boi)
2440 (when (and indent (> syntax 0))
2441 (cond ((> syntax 1) ; block in action => use cc-mode
2442 (setq indent nil))
2443 ((and (= indent 0)
2444 (assq antlr-language antlr-indent-at-bol-alist)
2445 (looking-at (cdr (assq antlr-language
2446 antlr-indent-at-bol-alist))))
2447 (setq syntax 'bol))
2448 ((setq cc-syntax (c-guess-basic-syntax))
2449 (let ((cc cc-syntax) symbol)
2450 (while (setq symbol (pop cc))
2451 (when (cdr symbol)
2452 (or (memq (car symbol)
2453 antlr-disabling-cc-syntactic-symbols)
2454 (setq indent nil))
2455 (setq cc nil)))))))
2456 ;;; ((= indent 1) ; exception part => use cc-mode
2457 ;;; (setq indent nil))
2458 ;;; ((save-restriction ; not in option part => cc-mode
2459 ;;; (goto-char (scan-lists (point) -1 1))
2460 ;;; (skip-chars-backward " \t\n")
2461 ;;; (narrow-to-region (point-min) (point))
2462 ;;; (not (re-search-backward "\\<options\\'" nil t)))
2463 ;;; (setq indent nil)))))
2464 ;; compute the corresponding indentation and indent --------------------
2465 (if (null indent)
2466 ;; Use the indentation engine of cc-mode
2467 (progn
2468 (goto-char orig)
2469 (if (or (numberp syntax)
2470 (if (eq syntax 'string) nil (eq antlr-indent-comment t)))
2471 (c-indent-line cc-syntax)))
2472 ;; do it ourselves
2473 (goto-char boi)
2474 (unless (symbolp syntax) ; direct indentation
2475 ;;(antlr-invalidate-context-cache)
2476 (incf indent (antlr-syntactic-context))
2477 (and (> indent 0) (looking-at antlr-indent-item-regexp) (decf indent))
2478 (setq indent (* indent c-basic-offset)))
2479 ;; the usual major-mode indent stuff ---------------------------------
2480 (setq orig (- (point-max) orig))
2481 (unless (= (current-column) indent)
2482 (delete-region bol boi)
2483 (beginning-of-line)
2484 (indent-to indent))
2485 ;; If initial point was within line's indentation,
2486 ;; position after the indentation. Else stay at same point in text.
2487 (if (> (- (point-max) orig) (point))
2488 (goto-char (- (point-max) orig)))))))
2489
2490 (defun antlr-indent-command (&optional arg)
2491 "Indent the current line or insert tabs/spaces.
2492 With optional prefix argument ARG or if the previous command was this
2493 command, insert ARG tabs or spaces according to `indent-tabs-mode'.
2494 Otherwise, indent the current line with `antlr-indent-line'."
2495 (interactive "*P")
2496 (if (or arg (eq last-command 'antlr-indent-command))
2497 (insert-tab arg)
2498 (let ((antlr-indent-comment (and antlr-indent-comment t))) ; dynamic
2499 (antlr-indent-line))))
2500
2501 (defun antlr-electric-character (&optional arg)
2502 "Insert the character you type and indent the current line.
2503 Insert the character like `self-insert-command' and indent the current
2504 line as `antlr-indent-command' does. Do not indent the line if
2505
2506 * this command is called with a prefix argument ARG,
2507 * there are characters except whitespaces between point and the
2508 beginning of the line, or
2509 * point is not inside a normal grammar code, { and } are also OK in
2510 actions.
2511
2512 This command is useful for a character which has some special meaning in
2513 ANTLR's syntax and influences the auto indentation, see
2514 `antlr-indent-item-regexp'."
2515 (interactive "*P")
2516 (if (or arg
2517 (save-excursion (skip-chars-backward " \t") (not (bolp)))
2518 (antlr-with-syntax-table antlr-action-syntax-table
2519 (antlr-invalidate-context-cache)
2520 (let ((context (antlr-syntactic-context)))
2521 (not (and (numberp context)
2522 (or (zerop context)
2523 (memq last-command-event '(?\{ ?\}))))))))
2524 (self-insert-command (prefix-numeric-value arg))
2525 (self-insert-command (prefix-numeric-value arg))
2526 (antlr-indent-line)))
2527
2528
2529 ;;;===========================================================================
2530 ;;; Mode entry
2531 ;;;===========================================================================
2532
2533 (defun antlr-c-init-language-vars ()
2534 "Like `c-init-language-vars-for' when using cc-mode before v5.29."
2535 (let ((settings ; (cdr '(setq...)) will be optimized
2536 (if (eq antlr-language 'c++-mode)
2537 (cdr '(setq ;' from `c++-mode' v5.20, v5.28
2538 c-keywords (c-identifier-re c-C++-keywords)
2539 c-conditional-key c-C++-conditional-key
2540 c-comment-start-regexp c-C++-comment-start-regexp
2541 c-class-key c-C++-class-key
2542 c-extra-toplevel-key c-C++-extra-toplevel-key
2543 c-access-key c-C++-access-key
2544 c-recognize-knr-p nil
2545 c-bitfield-key c-C-bitfield-key ; v5.28
2546 ))
2547 (cdr '(setq ; from `java-mode' v5.20, v5.28
2548 c-keywords (c-identifier-re c-Java-keywords)
2549 c-conditional-key c-Java-conditional-key
2550 c-comment-start-regexp c-Java-comment-start-regexp
2551 c-class-key c-Java-class-key
2552 c-method-key nil
2553 c-baseclass-key nil
2554 c-recognize-knr-p nil
2555 c-access-key c-Java-access-key ; v5.20
2556 c-inexpr-class-key c-Java-inexpr-class-key ; v5.28
2557 )))))
2558 (while settings
2559 (when (boundp (car settings))
2560 (ignore-errors
2561 (set (car settings) (eval (cadr settings)))))
2562 (setq settings (cddr settings)))))
2563
2564 (defun antlr-language-option (search)
2565 "Find language in `antlr-language-alist' for language option.
2566 If SEARCH is non-nil, find element for language option. Otherwise, find
2567 the default language."
2568 (let ((value (and search
2569 (save-excursion
2570 (goto-char (point-min))
2571 (re-search-forward (cdr antlr-language-limit-n-regexp)
2572 (car antlr-language-limit-n-regexp)
2573 t))
2574 (match-string 1)))
2575 (seq antlr-language-alist)
2576 r)
2577 ;; Like (find VALUE antlr-language-alist :key 'cddr :test 'member)
2578 (while seq
2579 (setq r (pop seq))
2580 (if (member value (cddr r))
2581 (setq seq nil) ; stop
2582 (setq r nil))) ; no result yet
2583 (car r)))
2584
2585 ;;;###autoload
2586 (defun antlr-mode ()
2587 "Major mode for editing ANTLR grammar files.
2588 \\{antlr-mode-map}"
2589 (interactive)
2590 (kill-all-local-variables)
2591 (c-initialize-cc-mode) ; cc-mode is required
2592 (unless (fboundp 'c-forward-sws) ; see above
2593 (fset 'antlr-c-forward-sws 'c-forward-syntactic-ws))
2594 ;; ANTLR specific ----------------------------------------------------------
2595 (setq major-mode 'antlr-mode
2596 mode-name "Antlr")
2597 (setq local-abbrev-table antlr-mode-abbrev-table)
2598 (unless antlr-mode-syntax-table
2599 (setq antlr-mode-syntax-table (make-syntax-table))
2600 (c-populate-syntax-table antlr-mode-syntax-table))
2601 (set-syntax-table antlr-mode-syntax-table)
2602 (unless antlr-action-syntax-table
2603 (let ((slist (nth 3 antlr-font-lock-defaults)))
2604 (setq antlr-action-syntax-table
2605 (copy-syntax-table antlr-mode-syntax-table))
2606 (while slist
2607 (modify-syntax-entry (caar slist) (cdar slist)
2608 antlr-action-syntax-table)
2609 (setq slist (cdr slist)))))
2610 (use-local-map antlr-mode-map)
2611 (make-local-variable 'antlr-language)
2612 (unless antlr-language
2613 (setq antlr-language
2614 (or (antlr-language-option t) (antlr-language-option nil))))
2615 (if (stringp (cadr (assq antlr-language antlr-language-alist)))
2616 (setq mode-name
2617 (concat "Antlr."
2618 (cadr (assq antlr-language antlr-language-alist)))))
2619 ;; indentation, for the C engine -------------------------------------------
2620 (setq c-buffer-is-cc-mode antlr-language)
2621 (cond ((fboundp 'c-init-language-vars-for) ; cc-mode 5.30.5+
2622 (c-init-language-vars-for antlr-language))
2623 ((fboundp 'c-init-c-language-vars) ; cc-mode 5.30 to 5.30.4
2624 (c-init-c-language-vars) ; not perfect, but OK
2625 (setq c-recognize-knr-p nil))
2626 ((fboundp 'c-init-language-vars) ; cc-mode 5.29
2627 (let ((init-fn 'c-init-language-vars))
2628 (funcall init-fn))) ; is a function in v5.29
2629 (t ; cc-mode upto 5.28
2630 (antlr-c-init-language-vars))) ; do it myself
2631 (c-basic-common-init antlr-language (or antlr-indent-style "gnu"))
2632 (make-local-variable 'outline-regexp)
2633 (make-local-variable 'outline-level)
2634 (make-local-variable 'require-final-newline)
2635 (make-local-variable 'indent-line-function)
2636 (make-local-variable 'indent-region-function)
2637 (setq outline-regexp "[^#\n\^M]"
2638 outline-level 'c-outline-level) ; TODO: define own
2639 (setq require-final-newline mode-require-final-newline)
2640 (setq indent-line-function 'antlr-indent-line
2641 indent-region-function nil) ; too lazy
2642 (setq comment-start "// "
2643 comment-end ""
2644 comment-start-skip "/\\*+ *\\|// *")
2645 ;; various -----------------------------------------------------------------
2646 (make-local-variable 'font-lock-defaults)
2647 (setq font-lock-defaults antlr-font-lock-defaults)
2648 (easy-menu-add antlr-mode-menu)
2649 (make-local-variable 'imenu-create-index-function)
2650 (setq imenu-create-index-function 'antlr-imenu-create-index-function)
2651 (make-local-variable 'imenu-generic-expression)
2652 (setq imenu-generic-expression t) ; fool stupid test
2653 (and antlr-imenu-name ; there should be a global variable...
2654 (fboundp 'imenu-add-to-menubar)
2655 (imenu-add-to-menubar
2656 (if (stringp antlr-imenu-name) antlr-imenu-name "Index")))
2657 (antlr-set-tabs)
2658 (run-mode-hooks 'antlr-mode-hook))
2659
2660 ;; A smarter version of `group-buffers-menu-by-mode-then-alphabetically' (in
2661 ;; XEmacs) could use the following property. The header of the submenu would
2662 ;; be "Antlr" instead of "Antlr.C++" or (not and!) "Antlr.Java".
2663 (put 'antlr-mode 'mode-name "Antlr")
2664
2665 ;;;###autoload
2666 (defun antlr-set-tabs ()
2667 "Use ANTLR's convention for TABs according to `antlr-tab-offset-alist'.
2668 Used in `antlr-mode'. Also a useful function in `java-mode-hook'."
2669 (if buffer-file-name
2670 (let ((alist antlr-tab-offset-alist) elem)
2671 (while alist
2672 (setq elem (pop alist))
2673 (and (or (null (car elem)) (eq (car elem) major-mode))
2674 (or (null (cadr elem))
2675 (string-match (cadr elem) buffer-file-name))
2676 (setq tab-width (caddr elem)
2677 indent-tabs-mode (cadddr elem)
2678 alist nil))))))
2679
2680 (provide 'antlr-mode)
2681
2682 ;;; Local IspellPersDict: .ispell_antlr
2683
2684 ;; arch-tag: 5de2be79-3d13-4560-8fbc-f7d0234dcb5c
2685 ;;; antlr-mode.el ends here