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