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