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