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