1 ;;; antlr-mode.el --- major mode for ANTLR grammar files
3 ;; Copyright (C) 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.
5 ;; Author: Christoph.Wedler@sap.com
6 ;; Keywords: languages, ANTLR, code generator
7 ;; Version: (see `antlr-version' below)
8 ;; X-URL: http://antlr-mode.sourceforge.net/
10 ;; This file is part of GNU Emacs.
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)
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.
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.
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
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/>.
40 ;; Bug fixes, bug reports, improvements, and suggestions for the newest version
41 ;; are strongly appreciated.
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).
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
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'.
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.
71 ;; This file requires Emacs-20.3, XEmacs-20.4 or higher and package cc-mode.
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")))
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).
83 ;; To customize, use menu item "Antlr" -> "Customize Antlr".
90 ;; General Emacs/XEmacs-compatibility compile-time macros
93 (defmacro cond-emacs-xemacs (&rest args)
94 (cond-emacs-xemacs-macfn
95 args "`cond-emacs-xemacs' must return exactly one element"))
96 (defun cond-emacs-xemacs-macfn (args &optional msg)
98 (and (eq (car args) :@) (null msg) ; (:@ ...spliced...)
100 msg "(:@ ....) must return exactly one element"))
101 (let ((ignore (if (string-match "XEmacs" emacs-version) :EMACS :XEMACS))
104 (if (memq (car args) '(:EMACS :XEMACS :BOTH)) (setq mode (pop args)))
106 (or args (error "Used selector %s without elements" mode))
108 (push (cond-emacs-xemacs-macfn (car args)) code))
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)
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) ?_))
135 (cons (if (string-equal spec "_")
137 `(interactive ,(substring spec 1)))
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
145 (cond ,@(mapcar (lambda (func) `((fboundp ',func) ',func))
148 `(lambda ,arglist ,docstring
149 ,@(cond-emacs-xemacs-macfn definition))
151 (defmacro ignore-errors-x (&rest body)
152 (let ((specials '((scan-sexps . 4) (scan-lists . 5)))
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)))))
161 ;; More compile-time-macros
163 (defmacro save-buffer-state-x (&rest body) ; similar to EMACS/lazy-lock.el
164 (let ((modified (with-no-warnings (gensym "save-buffer-state-x-modified-"))))
165 `(let ((,modified (buffer-modified-p)))
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)
173 (and (not ,modified) (buffer-modified-p)
174 (set-buffer-modified-p nil)))))))
175 (put 'save-buffer-state-x 'lisp-indent-function 0)
177 ;; get rid of byte-compile warnings
178 (eval-when-compile ; required and optional libraries
180 (ignore-errors (require 'font-lock))
181 (ignore-errors (require 'compile))
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!
185 (defvar outline-level) (defvar imenu-use-markers)
186 (defvar imenu-create-index-function))
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
195 (defalias 'antlr-c-forward-sws 'c-forward-sws)
198 ;;;;##########################################################################
200 ;;;;##########################################################################
204 "Major mode for ANTLR grammar files."
206 :link '(emacs-commentary-link "antlr-mode.el")
207 :link '(url-link "http://antlr-mode.sourceforge.net/")
210 (defconst antlr-version "2.2c"
211 "ANTLR major mode version number.
212 Check <http://antlr-mode.sourceforge.net/> for the newest.")
215 ;;;===========================================================================
216 ;;; Controlling ANTLR's code generator (language option)
217 ;;;===========================================================================
219 (defvar antlr-language nil
220 "Major mode corresponding to ANTLR's \"language\" option.
221 Set via `antlr-language-alist'. The only useful place to change this
222 buffer-local variable yourself is in `antlr-mode-hook' or in the \"local
223 variable list\" near the end of the file, see
224 `enable-local-variables'.")
226 (defcustom antlr-language-alist
227 '((java-mode "Java" nil "\"Java\"" "Java")
228 (c++-mode "C++" "\"Cpp\"" "Cpp"))
229 "List of ANTLR's supported languages.
230 Each element in this list looks like
231 \(MAJOR-MODE MODELINE-STRING OPTION-VALUE...)
233 MAJOR-MODE, the major mode of the code in the grammar's actions, is the
234 value of `antlr-language' if the first group in the string matched by
235 REGEXP in `antlr-language-limit-n-regexp' is one of the OPTION-VALUEs.
236 An OPTION-VALUE of nil denotes the fallback element. MODELINE-STRING is
237 also displayed in the modeline next to \"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)
246 (defcustom antlr-language-limit-n-regexp
247 '(8192 . "language[ \t]*=[ \t]*\\(\"?[A-Z][A-Za-z_]*\"?\\)")
248 "Used to set a reasonable value for `antlr-language'.
249 Looks like \(LIMIT \. REGEXP). Search for REGEXP from the beginning of
250 the buffer to LIMIT and use the first group in the matched string to set
251 the language according to `antlr-language-alist'."
253 :type '(cons (choice :tag "Limit" (const :tag "No" nil) (integer :value 0))
257 ;;;===========================================================================
258 ;;; Hide/Unhide, Indent/Tabs
259 ;;;===========================================================================
261 (defcustom antlr-action-visibility 3
262 "Visibility of actions when command `antlr-hide-actions' is used.
263 If nil, the actions with their surrounding braces are hidden. If a
264 number, do not hide the braces, only hide the contents if its length is
265 greater than this number."
267 :type '(choice (const :tag "Completely hidden" nil)
268 (integer :tag "Hidden if longer than" :value 3)))
270 (defcustom antlr-indent-comment 'tab
271 "*Non-nil, if the indentation should touch lines in block comments.
272 If nil, no continuation line of a block comment is changed. If t, they
273 are changed according to `c-indentation-line'. When not nil and not t,
274 they are only changed by \\[antlr-indent-command]."
276 :type '(radio (const :tag "No" nil)
277 (const :tag "Always" t)
278 (sexp :tag "With TAB" :format "%t" :value tab)))
280 (defcustom antlr-tab-offset-alist
281 '((antlr-mode nil 4 nil)
282 (java-mode "antlr" 4 nil))
283 "Alist to determine whether to use ANTLR's convention for TABs.
284 Each element looks like \(MAJOR-MODE REGEXP TAB-WIDTH INDENT-TABS-MODE).
285 The first element whose MAJOR-MODE is nil or equal to `major-mode' and
286 whose REGEXP is nil or matches variable `buffer-file-name' is used to
287 set `tab-width' and `indent-tabs-mode'. This is useful to support both
288 ANTLR's and Java's indentation styles. Used by `antlr-set-tabs'."
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"))))
297 (defcustom antlr-indent-style "java"
298 "*If non-nil, cc-mode indentation style used for `antlr-mode'.
299 See `c-set-style' and for details, where the most interesting part in
300 `c-style-alist' is the value of `c-basic-offset'."
302 :type '(choice (const nil) regexp))
304 (defcustom antlr-indent-item-regexp
305 "[]}):;|&]" ; & is local ANTLR extension (SGML's and-connector)
306 "Regexp matching lines which should be indented by one TAB less.
307 See `antlr-indent-line' and command \\[antlr-indent-command]."
311 (defcustom antlr-indent-at-bol-alist
312 ;; eval-when-compile not usable with defcustom...
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\\)\\>"))
315 "Alist of regexps matching lines are indented at column 0.
316 Each element in this list looks like (MODE . REGEXP) where MODE is a
317 function and REGEXP is a regular expression.
319 If `antlr-language' equals to a MODE, the line starting at the first
320 non-whitespace is matched by the corresponding REGEXP, and the line is
321 part of an header action, indent the line at column 0 instead according
322 to the normal rules of `antlr-indent-line'."
324 :type '(repeat (cons (function :tag "Major mode") regexp)))
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
332 block-close defun-close class-close brace-list-close arglist-close
333 inline-close extern-lang-close namespace-close))
336 ;;;===========================================================================
337 ;;; Options: customization
338 ;;;===========================================================================
340 (defcustom antlr-options-use-submenus t
341 "*Non-nil, if the major mode menu should include option submenus.
342 If nil, the menu just includes a command to insert options. Otherwise,
343 it includes four submenus to insert file/grammar/rule/subrule options."
347 (defcustom antlr-tool-version 20701
348 "*The version number of the Antlr tool.
349 The value is an integer of the form XYYZZ which stands for vX.YY.ZZ.
350 This variable is used to warn about non-supported options and to supply
351 version correct option values when using \\[antlr-insert-option].
353 Don't use a number smaller than 20600 since the stored history of
354 Antlr's options starts with v2.06.00, see `antlr-options-alists'. You
355 can make this variable buffer-local."
359 (defcustom antlr-options-auto-colon t
360 "*Non-nil, if `:' is inserted with a rule or subrule options section.
361 A `:' is only inserted if this value is non-nil, if a rule or subrule
362 option is inserted with \\[antlr-insert-option], if there was no rule or
363 subrule options section before, and if a `:' is not already present
364 after the section, ignoring whitespace, comments and the init action."
368 (defcustom antlr-options-style nil
369 "List of symbols which determine the style of option values.
370 If a style symbol is present, the corresponding option value is put into
371 quotes, i.e., represented as a string, otherwise it is represented as an
374 The only style symbol used in the default value of `antlr-options-alist'
375 is `language-as-string'. See also `antlr-read-value'."
377 :type '(repeat (symbol :tag "Style symbol")))
379 (defcustom antlr-options-push-mark t
380 "*Non-nil, if inserting an option should set & push mark.
381 If nil, never set mark when inserting an option with command
382 \\[antlr-insert-option]. If t, always set mark via `push-mark'. If a
383 number, only set mark if point was outside the options area before and
384 the number of lines between point and the insert position is greater
385 than this value. Otherwise, only set mark if point was outside the
386 options area before."
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)))
393 (defcustom antlr-options-assign-string " = "
394 "*String containing `=' to use between option name and value.
395 This string is only used if the option to insert did not exist before
396 or if there was no `=' after it. In other words, the spacing around an
397 existing `=' won't be changed when changing an option value."
402 ;;;===========================================================================
403 ;;; Options: definitions
404 ;;;===========================================================================
406 (defvar antlr-options-headings '("file" "grammar" "rule" "subrule")
407 "Headings for the four different option kinds.
408 The standard value is (\"file\" \"grammar\" \"rule\" \"subrule\"). See
409 `antlr-options-alists'")
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? "))
436 ;; grammar options --------------------------------------------------------
438 (20600 antlr-read-value
439 "Lookahead depth: "))
441 (20600 antlr-read-value
442 "Import vocabulary: "))
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: "))
459 (20600 antlr-read-boolean
460 "Display debugging info during grammar analysis? "))
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
472 "Insert character vocabulary"))
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
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: "))
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))
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? "))
531 (20700 antlr-read-boolean
532 "Make this optional/loop subrule greedy? "))
534 "Definitions for Antlr's options of all four different kinds.
536 The value looks like \(FILE GRAMMAR RULE SUBRULE) where each FILE,
537 GRAMMAR, RULE, and SUBRULE is a list of option definitions of the
538 corresponding kind, i.e., looks like \(OPTION-DEF...).
540 Each OPTION-DEF looks like \(OPTION-NAME EXTRA-FN VALUE-SPEC...) which
541 defines a file/grammar/rule/subrule option with name OPTION-NAME. The
542 OPTION-NAMEs are used for the creation of the \"Insert XXX Option\"
543 submenus, see `antlr-options-use-submenus', and to allow to insert the
544 option name with completion when using \\[antlr-insert-option].
546 If EXTRA-FN is a function, it is called at different phases of the
547 insertion with arguments \(PHASE OPTION-NAME). PHASE can have the
548 values `before-input' or `after-insertion', additional phases might be
549 defined in future versions of this mode. The phase `before-input'
550 occurs before the user is asked to insert a value. The phase
551 `after-insertion' occurs after the option value has been inserted.
552 EXTRA-FN might be called with additional arguments in future versions of
555 Each specification VALUE-SPEC looks like \(VERSION READ-FN ARG...). The
556 last 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
560 If READ-FN is nil, the only ARG is a string which is printed at the echo
561 area to guide the user what to insert at point. Otherwise, READ-FN is
562 called with arguments \(INIT-VALUE ARG...) to get the new value of the
563 option. INIT-VALUE is the old value of the option or nil.
565 The standard value contains the following functions as READ-FN:
566 `antlr-read-value' with ARGs = \(PROMPT AS-STRING TABLE) which reads a
567 general value, or `antlr-read-boolean' with ARGs = \(PROMPT TABLE) which
568 reads a boolean value or a member of TABLE. PROMPT is the prompt when
569 asking for a new value. If non-nil, TABLE is a table for completion or
570 a function evaluating to such a table. The return value is quoted iff
571 AS-STRING is non-nil and is either t or a symbol which is a member of
572 `antlr-options-style'.")
575 ;;;===========================================================================
576 ;;; Run tool, create Makefile dependencies
577 ;;;===========================================================================
579 (defcustom antlr-tool-command "java antlr.Tool"
580 "*Command used in \\[antlr-run-tool] to run the Antlr tool.
581 This variable should include all options passed to Antlr except the
582 option \"-glib\" which is automatically suggested if necessary."
586 (defcustom antlr-ask-about-save t
587 "*If not nil, \\[antlr-run-tool] asks which buffers to save.
588 Otherwise, it saves all modified buffers before running without asking."
592 (defcustom antlr-makefile-specification
593 '("\n" ("GENS" "GENS%d" " \\\n\t") "$(ANTLR)")
594 "*Variable to specify the appearance of the generated makefile rules.
595 This variable influences the output of \\[antlr-show-makefile-rules].
596 It looks like \(RULE-SEP GEN-VAR-SPEC COMMAND).
598 RULE-SEP is the string to separate different makefile rules. COMMAND is
599 a string with the command which runs the Antlr tool, it should include
600 all options except the option \"-glib\" which is automatically added
603 If GEN-VAR-SPEC is nil, each target directly consists of a list of
604 files. If GEN-VAR-SPEC looks like \(GEN-VAR GEN-VAR-FORMAT GEN-SEP), a
605 Makefile variable is created for each rule target.
607 Then, GEN-VAR is a string with the name of the variable which contains
608 the file names of all makefile rules. GEN-VAR-FORMAT is a format string
609 producing the variable of each target with substitution COUNT/%d where
610 COUNT starts with 1. GEN-SEP is used to separate long variable values."
612 :type '(list (string :tag "Rule separator")
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")))
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.
625 Each element in this list looks looks like
626 \(MAJOR-MODE (VOCAB-FILE-FORMAT...) (CLASS-FILE-FORMAT...)).
628 The element whose MAJOR-MODE is equal to `antlr-language' is used to
629 specify the generated files which are language dependent. See variable
630 `antlr-special-file-formats' for language independent files.
632 VOCAB-FILE-FORMAT is a format string, it specifies with substitution
633 VOCAB/%s the generated file for each export vocabulary VOCAB.
634 CLASS-FILE-FORMAT is a format string, it specifies with substitution
635 CLASS/%s the generated file for each grammar class CLASS.")
637 (defvar antlr-special-file-formats '("%sTokenTypes.txt" "expanded%s.g")
638 "Language independent formats which specify generated files.
639 The value looks like \(VOCAB-FILE-FORMAT EXPANDED-GRAMMAR-FORMAT).
641 VOCAB-FILE-FORMAT is a format string, it specifies with substitution
642 VOCAB/%s the generated or input file for each export or import
643 vocabulary VOCAB, respectively. EXPANDED-GRAMMAR-FORMAT is a format
644 string, it specifies with substitution GRAMMAR/%s the constructed
645 grammar file if the file GRAMMAR.g contains a grammar class which
646 extends a class other than \"Lexer\", \"Parser\" or \"TreeParser\".
648 See variable `antlr-file-formats-alist' for language dependent
651 (defvar antlr-unknown-file-formats '("?%s?.g" "?%s?")
652 "*Formats which specify the names of unknown files.
653 The value looks like \(SUPER-GRAMMAR-FILE-FORMAT SUPER-EVOCAB-FORMAT).
655 SUPER-GRAMMAR-FORMAT is a format string, it specifies with substitution
656 SUPER/%s the name of a grammar file for Antlr's option \"-glib\" if no
657 grammar file in the current directory defines the class SUPER or if it
658 is defined more than once. SUPER-EVOCAB-FORMAT is a format string, it
659 specifies with substitution SUPER/%s the name for the export vocabulary
660 of above mentioned class SUPER.")
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.
669 See \\[antlr-show-makefile-rules] and `antlr-unknown-file-formats'.")
671 (defvar antlr-help-rules-intro
672 "The following Makefile rules define the dependencies for all (non-
673 expanded) grammars in directory \"%s\".\n
674 They are stored in the kill-ring, i.e., you can insert them with C-y
675 into your Makefile. You can also invoke M-x antlr-show-makefile-rules
676 from within a Makefile to insert them directly.\n\n\n"
677 "Introduction to use with \\[antlr-show-makefile-rules].
678 It is a format string and used with substitution DIRECTORY/%s where
679 DIRECTORY is the name of the current directory.")
682 ;;;===========================================================================
684 ;;;===========================================================================
686 (defcustom antlr-imenu-name t ; (featurep 'xemacs) ; TODO: Emacs-21 bug?
687 "*Non-nil, if a \"Index\" menu should be added to the menubar.
688 If it is a string, it is used instead \"Index\". Requires package
691 :type '(choice (const :tag "No menu" nil)
692 (const :tag "Index menu" t)
693 (string :tag "Other menu name")))
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)
704 (define-key map "\C-c\C-c" 'comment-region)
705 (define-key map "\C-c\C-v" 'antlr-hide-actions)
706 (define-key map "\C-c\C-r" 'antlr-run-tool)
707 (define-key map "\C-c\C-o" 'antlr-insert-option)
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)
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)
721 "Keymap used in `antlr-mode' buffers.")
723 (easy-menu-define antlr-mode-menu antlr-mode-map
726 ,@(if (cond-emacs-xemacs
727 :EMACS (and antlr-options-use-submenus
728 (>= emacs-major-version 21))
729 :XEMACS antlr-options-use-submenus)
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)))
739 '(["Insert Option" antlr-insert-option
740 :active (not buffer-read-only)]))
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)]
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))]
758 (comment-region (region-beginning) (region-end) '(4))
759 :active (and (not buffer-read-only) (c-region-is-active-p))]
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]
765 ["Run Tool on Grammar" antlr-run-tool t]
766 ["Show Makefile Rules" antlr-show-makefile-rules t]
768 ["Customize Antlr" (customize-group 'antlr) t]))
771 ;;;===========================================================================
773 ;;;===========================================================================
775 (defcustom antlr-font-lock-maximum-decoration 'inherit
776 "*The maximum decoration level for fontifying actions.
777 Value `none' means, do not fontify actions, just normal grammar code
778 according to `antlr-font-lock-additional-keywords'. Value `inherit'
779 means, use value of `font-lock-maximum-decoration'. Any other value is
780 interpreted as in `font-lock-maximum-decoration' with no level-0
781 fontification, see `antlr-font-lock-keywords-alist'.
783 While calculating the decoration level for actions, `major-mode' is
784 bound to `antlr-language'. For example, with value
785 \((java-mode \. 2) (c++-mode \. 0))
786 Java actions are fontified with level 2 and C++ actions are not
789 :type '(choice (const :tag "None" none)
790 (const :tag "Inherit" inherit)
791 (const :tag "Default" nil)
792 (const :tag "Maximum" t)
793 (integer :tag "Level" 1)
794 (repeat :menu-tag "Mode specific" :tag "Mode specific"
796 (cons :tag "Instance"
799 (symbol :tag "Name"))
800 (radio :tag "Decoration"
801 (const :tag "Default" nil)
802 (const :tag "Maximum" t)
803 (integer :tag "Level" 1))))))
805 (defconst antlr-no-action-keywords nil
806 ;; Using nil directly won't work (would use highest level, see
807 ;; `font-lock-choose-keywords'), but a non-symbol, i.e., (list), at `car'
808 ;; would break Emacs-21.0:
809 "Empty font-lock keywords for actions.
810 Do not change the value of this constant.")
812 (defvar antlr-font-lock-keywords-alist
814 antlr-no-action-keywords
815 java-font-lock-keywords-1 java-font-lock-keywords-2
816 java-font-lock-keywords-3)
818 antlr-no-action-keywords
819 c++-font-lock-keywords-1 c++-font-lock-keywords-2
820 c++-font-lock-keywords-3))
821 "List of font-lock keywords for actions in the grammar.
822 Each element in this list looks like
823 \(MAJOR-MODE KEYWORD...)
825 If `antlr-language' is equal to MAJOR-MODE, the KEYWORDs are the
826 font-lock keywords according to `font-lock-defaults' used for the code
827 in the grammar's actions and semantic predicates, see
828 `antlr-font-lock-maximum-decoration'.")
830 (defvar antlr-font-lock-default-face 'antlr-font-lock-default-face)
831 (defface antlr-font-lock-default-face nil
832 "Face to prevent strings from language dependent highlighting.
836 (defvar antlr-font-lock-keyword-face 'antlr-font-lock-keyword-face)
837 (defface antlr-font-lock-keyword-face
839 '((((class color) (background light))
840 (:foreground "black" :EMACS :weight bold :XEMACS :bold t))))
844 (defvar antlr-font-lock-syntax-face 'antlr-font-lock-keyword-face)
845 (defface antlr-font-lock-syntax-face
847 '((((class color) (background light))
848 (:foreground "black" :EMACS :weight bold :XEMACS :bold t))))
849 "ANTLR syntax symbols like :, |, (, ), ...."
852 (defvar antlr-font-lock-ruledef-face 'antlr-font-lock-ruledef-face)
853 (defface antlr-font-lock-ruledef-face
855 '((((class color) (background light))
856 (:foreground "blue" :EMACS :weight bold :XEMACS :bold t))))
857 "ANTLR rule references (definition)."
860 (defvar antlr-font-lock-tokendef-face 'antlr-font-lock-tokendef-face)
861 (defface antlr-font-lock-tokendef-face
863 '((((class color) (background light))
864 (:foreground "blue" :EMACS :weight bold :XEMACS :bold t))))
865 "ANTLR token references (definition)."
868 (defvar antlr-font-lock-ruleref-face 'antlr-font-lock-ruleref-face)
869 (defface antlr-font-lock-ruleref-face
870 '((((class color) (background light)) (:foreground "blue4")))
871 "ANTLR rule references (usage)."
874 (defvar antlr-font-lock-tokenref-face 'antlr-font-lock-tokenref-face)
875 (defface antlr-font-lock-tokenref-face
876 '((((class color) (background light)) (:foreground "orange4")))
877 "ANTLR token references (usage)."
880 (defvar antlr-font-lock-literal-face 'antlr-font-lock-literal-face)
881 (defface antlr-font-lock-literal-face
883 '((((class color) (background light))
884 (:foreground "brown4" :EMACS :weight bold :XEMACS :bold t))))
885 "ANTLR special literal tokens.
886 It is used to highlight strings matched by the first regexp group of
887 `antlr-font-lock-literal-regexp'."
890 (defcustom antlr-font-lock-literal-regexp "\"\\(\\sw\\(\\sw\\|-\\)*\\)\""
891 "Regexp matching literals with special syntax highlighting, or nil.
892 If nil, there is no special syntax highlighting for some literals.
893 Otherwise, it should be a regular expression which must contain a regexp
894 group. The string matched by the first group is highlighted with
895 `antlr-font-lock-literal-face'."
897 :type '(choice (const :tag "None" nil) regexp))
899 (defvar antlr-class-header-regexp
900 "\\(class\\)[ \t]+\\([A-Za-z\300-\326\330-\337]\\sw*\\)[ \t]+\\(extends\\)[ \t]+\\([A-Za-z\300-\326\330-\337]\\sw*\\)[ \t]*;"
901 "Regexp matching class headers.")
903 (defvar antlr-font-lock-additional-keywords
905 `((antlr-invalidate-context-cache)
906 ("\\$setType[ \t]*(\\([A-Za-z\300-\326\330-\337]\\sw*\\))"
907 (1 antlr-font-lock-tokendef-face))
908 ("\\$\\sw+" (0 font-lock-keyword-face))
909 ;; the tokens are already fontified as string/docstrings:
911 (if antlr-font-lock-literal-regexp
912 (antlr-re-search-forward antlr-font-lock-literal-regexp limit)))
913 (1 antlr-font-lock-literal-face t)
914 :XEMACS (0 nil)) ; XEmacs bug workaround
916 (antlr-re-search-forward antlr-class-header-regexp limit))
917 (1 antlr-font-lock-keyword-face)
918 (2 antlr-font-lock-ruledef-face)
919 (3 antlr-font-lock-keyword-face)
920 (4 (if (member (match-string 4) '("Lexer" "Parser" "TreeParser"))
921 'antlr-font-lock-keyword-face
922 'font-lock-type-face)))
924 (antlr-re-search-forward
925 "\\<\\(header\\|options\\|tokens\\|exception\\|catch\\|returns\\)\\>"
927 (1 antlr-font-lock-keyword-face))
929 (antlr-re-search-forward
930 "^\\(private\\|public\\|protected\\)\\>[ \t]*\\(\\(\\sw+[ \t]*\\(:\\)?\\)\\)?"
932 (1 font-lock-type-face) ; not XEmacs' java level-3 fruit salad
933 (3 (if (antlr-upcase-p (char-after (match-beginning 3)))
934 'antlr-font-lock-tokendef-face
935 'antlr-font-lock-ruledef-face) nil t)
936 (4 antlr-font-lock-syntax-face nil t))
938 (antlr-re-search-forward "^\\(\\sw+\\)[ \t]*\\(:\\)?" limit))
939 (1 (if (antlr-upcase-p (char-after (match-beginning 0)))
940 'antlr-font-lock-tokendef-face
941 'antlr-font-lock-ruledef-face) nil t)
942 (2 antlr-font-lock-syntax-face nil t))
944 ;; v:ruleref and v:"literal" is allowed...
945 (antlr-re-search-forward "\\(\\sw+\\)[ \t]*\\([=:]\\)?" limit))
946 (1 (if (match-beginning 2)
947 (if (eq (char-after (match-beginning 2)) ?=)
948 'antlr-font-lock-default-face
949 'font-lock-variable-name-face)
950 (if (antlr-upcase-p (char-after (match-beginning 1)))
951 'antlr-font-lock-tokenref-face
952 'antlr-font-lock-ruleref-face)))
953 (2 antlr-font-lock-default-face nil t))
955 (antlr-re-search-forward "[|&:;(~]\\|)\\([*+?]\\|=>\\)?" limit))
956 (0 'antlr-font-lock-syntax-face))))
957 "Font-lock keywords for ANTLR's normal grammar code.
958 See `antlr-font-lock-keywords-alist' for the keywords of actions.")
960 (defvar antlr-font-lock-defaults
961 '(antlr-font-lock-keywords
962 nil nil ((?_ . "w") (?\( . ".") (?\) . ".")) beginning-of-defun)
963 "Font-lock defaults used for ANTLR syntax highlighting.
964 The SYNTAX-ALIST element is also used to initialize
965 `antlr-action-syntax-table'.")
968 ;;;===========================================================================
969 ;;; Internal variables
970 ;;;===========================================================================
972 (defvar antlr-mode-hook nil
973 "Hook called by `antlr-mode'.")
975 (defvar antlr-mode-syntax-table nil
976 "Syntax table used in `antlr-mode' buffers.
977 If non-nil, it will be initialized in `antlr-mode'.")
979 ;; used for "in Java/C++ code" = syntactic-depth>0
980 (defvar antlr-action-syntax-table nil
981 "Syntax table used for ANTLR action parsing.
982 Initialized by `antlr-mode-syntax-table', changed by SYNTAX-ALIST in
983 `antlr-font-lock-defaults'. This table should be selected if you use
984 `buffer-syntactic-context' and `buffer-syntactic-context-depth' in order
985 not to confuse their context_cache.")
987 (defvar antlr-mode-abbrev-table nil
988 "Abbreviation table used in `antlr-mode' buffers.")
989 (define-abbrev-table 'antlr-mode-abbrev-table ())
991 (defvar antlr-slow-cache-enabling-symbol 'loudly
992 ;; Emacs' font-lock changes buffer's tick counter, therefore this value should
993 ;; be a parameter of a font-lock function, but not any other variable of
994 ;; functions which call `antlr-slow-syntactic-context'.
995 "If value is a bound symbol, cache will be used even with text changes.
996 This is no user option. Used for `antlr-slow-syntactic-context'.")
998 (defvar antlr-slow-cache-diff-threshold 5000
999 "Maximum distance between `point' and cache position for cache use.
1000 Used for `antlr-slow-syntactic-context'.")
1003 ;;;;##########################################################################
1005 ;;;;##########################################################################
1009 ;;;===========================================================================
1010 ;;; Syntax functions -- Emacs vs XEmacs dependent, part 1
1011 ;;;===========================================================================
1013 ;; From help.el (XEmacs-21.1), without `copy-syntax-table'
1014 (defmacro antlr-with-syntax-table (syntab &rest body)
1015 "Evaluate BODY with the syntax table SYNTAB."
1016 `(let ((stab (syntax-table)))
1018 (progn (set-syntax-table ,syntab) ,@body)
1019 (set-syntax-table stab))))
1020 (put 'antlr-with-syntax-table 'lisp-indent-function 1)
1021 (put 'antlr-with-syntax-table 'edebug-form-spec '(form body))
1023 (defunx antlr-default-directory ()
1024 :xemacs-and-try default-directory
1025 "Return `default-directory'."
1028 ;; Check Emacs-21.1 simple.el, `shell-command'.
1029 (defunx antlr-read-shell-command (prompt &optional initial-input history)
1030 :xemacs-and-try read-shell-command
1031 "Read a string from the minibuffer, using `shell-command-history'."
1032 (read-from-minibuffer prompt initial-input nil nil
1033 (or history 'shell-command-history)))
1035 (defunx antlr-with-displaying-help-buffer (thunk &optional name)
1036 :xemacs-and-try with-displaying-help-buffer
1037 "Make a help buffer and call `thunk' there."
1038 (with-output-to-temp-buffer "*Help*"
1039 (save-excursion (funcall thunk))))
1042 ;;;===========================================================================
1044 ;;;===========================================================================
1046 (defvar antlr-slow-context-cache nil "Internal.")
1048 ;;;(defvar antlr-statistics-full-neg 0)
1049 ;;;(defvar antlr-statistics-full-diff 0)
1050 ;;;(defvar antlr-statistics-full-other 0)
1051 ;;;(defvar antlr-statistics-cache 0)
1052 ;;;(defvar antlr-statistics-inval 0)
1054 (defunx antlr-invalidate-context-cache (&rest dummies)
1055 ;; checkdoc-params: (dummies)
1056 "Invalidate context cache for syntactical context information."
1057 :XEMACS ; XEmacs bug workaround
1059 (set-buffer (get-buffer-create " ANTLR XEmacs bug workaround"))
1060 (buffer-syntactic-context-depth)
1063 ;;; (incf antlr-statistics-inval)
1064 (setq antlr-slow-context-cache nil))
1066 (defunx antlr-syntactic-context ()
1067 "Return some syntactic context information.
1068 Return `string' if point is within a string, `block-comment' or
1069 `comment' is point is within a comment or the depth within all
1070 parenthesis-syntax delimiters at point otherwise.
1071 WARNING: this may alter `match-data'."
1073 (or (buffer-syntactic-context) (buffer-syntactic-context-depth))
1075 (let ((orig (point)) diff state
1076 ;; Arg, Emacs' (buffer-modified-tick) changes with font-lock. Use
1077 ;; hack that `loudly' is bound during font-locking => cache use will
1078 ;; increase from 7% to 99.99% during font-locking.
1079 (tick (or (boundp antlr-slow-cache-enabling-symbol)
1080 (buffer-modified-tick))))
1081 (if (and (cdr antlr-slow-context-cache)
1082 (>= (setq diff (- orig (cadr antlr-slow-context-cache))) 0)
1083 (< diff antlr-slow-cache-diff-threshold)
1084 (eq (current-buffer) (caar antlr-slow-context-cache))
1085 (eq tick (cdar antlr-slow-context-cache)))
1086 ;; (setq antlr-statistics-cache (1+ antlr-statistics-cache) ...)
1087 (setq state (parse-partial-sexp (cadr antlr-slow-context-cache) orig
1089 (cddr antlr-slow-context-cache)))
1090 (if (>= orig antlr-slow-cache-diff-threshold)
1091 (beginning-of-defun)
1092 (goto-char (point-min)))
1093 ;;; (cond ((and diff (< diff 0)) (incf antlr-statistics-full-neg))
1094 ;;; ((and diff (>= diff 3000)) (incf antlr-statistics-full-diff))
1095 ;;; (t (incf antlr-statistics-full-other)))
1096 (setq state (parse-partial-sexp (point) orig)))
1098 (if antlr-slow-context-cache
1099 (setcdr antlr-slow-context-cache (cons orig state))
1100 (setq antlr-slow-context-cache
1101 (cons (cons (current-buffer) tick)
1102 (cons orig state))))
1103 (cond ((nth 3 state) 'string)
1104 ((nth 4 state) 'comment) ; block-comment? -- we don't care
1107 ;;; (incf (aref antlr-statistics 2))
1108 ;;; (unless (and (eq (current-buffer)
1109 ;;; (caar antlr-slow-context-cache))
1110 ;;; (eq (buffer-modified-tick)
1111 ;;; (cdar antlr-slow-context-cache)))
1112 ;;; (incf (aref antlr-statistics 1))
1113 ;;; (setq antlr-slow-context-cache nil))
1114 ;;; (let* ((orig (point))
1115 ;;; (base (cadr antlr-slow-context-cache))
1116 ;;; (curr (cddr antlr-slow-context-cache))
1117 ;;; (state (cond ((eq orig (car curr)) (cdr curr))
1118 ;;; ((eq orig (car base)) (cdr base))))
1121 ;;; (incf (aref antlr-statistics 3))
1123 ;;; (if (< (setq diff (abs (- orig (car curr))))
1124 ;;; (setq diff2 (abs (- orig (car base)))))
1125 ;;; (setq state curr)
1126 ;;; (setq state base
1128 ;;; (if (or (>= (1+ diff) (point)) (>= diff 3000))
1129 ;;; (setq state nil))) ; start from bod/bob
1132 ;;; (parse-partial-sexp (car state) orig nil nil (cdr state)))
1133 ;;; (if (>= orig 3000) (beginning-of-defun) (goto-char (point-min)))
1134 ;;; (incf (aref antlr-statistics 4))
1135 ;;; (setq cw (list orig (point) base curr))
1136 ;;; (setq state (parse-partial-sexp (point) orig)))
1137 ;;; (goto-char orig)
1138 ;;; (if antlr-slow-context-cache
1139 ;;; (setcdr (cdr antlr-slow-context-cache) (cons orig state))
1140 ;;; (setq antlr-slow-context-cache
1141 ;;; (cons (cons (current-buffer) (buffer-modified-tick))
1142 ;;; (cons (cons orig state) (cons orig state))))))
1143 ;;; (cond ((nth 3 state) 'string)
1144 ;;; ((nth 4 state) 'comment) ; block-comment? -- we don't care
1145 ;;; (t (car state)))))
1147 ;;; (beginning-of-defun)
1148 ;;; (let ((state (parse-partial-sexp (point) orig)))
1149 ;;; (goto-char orig)
1150 ;;; (cond ((nth 3 state) 'string)
1151 ;;; ((nth 4 state) 'comment) ; block-comment? -- we don't care
1152 ;;; (t (car state))))))
1155 ;;;===========================================================================
1156 ;;; Miscellaneous functions
1157 ;;;===========================================================================
1159 (defun antlr-upcase-p (char)
1160 "Non-nil, if CHAR is an uppercase character (if CHAR was a char)."
1161 ;; in XEmacs, upcase only works for ASCII
1162 (or (and (<= ?A char) (<= char ?Z))
1163 (and (<= ?\300 char) (<= char ?\337)))) ; ?\327 is no letter
1165 (defun antlr-re-search-forward (regexp bound)
1166 "Search forward from point for regular expression REGEXP.
1167 Set point to the end of the occurrence found, and return point. Return
1168 nil if no occurrence was found. Do not search within comments, strings
1169 and actions/semantic predicates. BOUND bounds the search; it is a
1170 buffer position. See also the functions `match-beginning', `match-end'
1171 and `replace-match'."
1172 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1174 (while (and (re-search-forward regexp bound 'limit)
1176 (if (eq (antlr-syntactic-context) 0)
1179 (if continue nil (point))))
1181 (defun antlr-search-forward (string)
1182 "Search forward from point for STRING.
1183 Set point to the end of the occurrence found, and return point. Return
1184 nil if no occurrence was found. Do not search within comments, strings
1185 and actions/semantic predicates."
1186 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1188 (while (and (search-forward string nil 'limit)
1189 (if (eq (antlr-syntactic-context) 0) (setq continue nil) t)))
1190 (if continue nil (point))))
1192 (defun antlr-search-backward (string)
1193 "Search backward from point for STRING.
1194 Set point to the beginning of the occurrence found, and return point.
1195 Return nil if no occurrence was found. Do not search within comments,
1196 strings and actions/semantic predicates."
1197 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1199 (while (and (search-backward string nil 'limit)
1200 (if (eq (antlr-syntactic-context) 0) (setq continue nil) t)))
1201 (if continue nil (point))))
1203 (defsubst antlr-skip-sexps (count)
1204 "Skip the next COUNT balanced expressions and the comments after it.
1205 Return position before the comments after the last expression."
1206 (goto-char (or (ignore-errors-x (scan-sexps (point) count)) (point-max)))
1208 (antlr-c-forward-sws)))
1211 ;;;===========================================================================
1213 ;;;===========================================================================
1215 (defun antlr-font-lock-keywords ()
1216 "Return font-lock keywords for current buffer.
1217 See `antlr-font-lock-additional-keywords', `antlr-language' and
1218 `antlr-font-lock-maximum-decoration'."
1219 (if (eq antlr-font-lock-maximum-decoration 'none)
1220 antlr-font-lock-additional-keywords
1221 (append antlr-font-lock-additional-keywords
1222 (eval (let ((major-mode antlr-language)) ; dynamic
1223 (font-lock-choose-keywords
1224 (cdr (assq antlr-language
1225 antlr-font-lock-keywords-alist))
1226 (if (eq antlr-font-lock-maximum-decoration 'inherit)
1227 font-lock-maximum-decoration
1228 antlr-font-lock-maximum-decoration)))))))
1231 ;;;===========================================================================
1233 ;;;===========================================================================
1235 (defun antlr-grammar-tokens ()
1236 "Return alist for tokens defined in current buffer."
1237 (save-excursion (antlr-imenu-create-index-function t)))
1239 (defun antlr-imenu-create-index-function (&optional tokenrefs-only)
1240 "Return imenu index-alist for ANTLR grammar files.
1241 IF TOKENREFS-ONLY is non-nil, just return alist with tokenref names."
1245 ;; Using `imenu-progress-message' would require imenu for compilation, but
1246 ;; nobody is missing these messages. The generic imenu function searches
1247 ;; backward, which is slower and more likely not to work during editing.
1248 (antlr-with-syntax-table antlr-action-syntax-table
1249 (antlr-invalidate-context-cache)
1250 (goto-char (point-min))
1251 (antlr-skip-file-prelude t)
1253 (if (looking-at "{") (antlr-skip-sexps 1))
1254 (if (looking-at antlr-class-header-regexp)
1256 (push (cons (match-string 2)
1257 (if imenu-use-markers
1258 (copy-marker (match-beginning 2))
1259 (match-beginning 2)))
1261 (if (looking-at "p\\(ublic\\|rotected\\|rivate\\)")
1262 (antlr-skip-sexps 1))
1263 (when (looking-at "\\sw+")
1265 (if (antlr-upcase-p (char-after (point)))
1266 (push (list (match-string 0)) items))
1267 (push (cons (match-string 0)
1268 (if imenu-use-markers
1269 (copy-marker (match-beginning 0))
1270 (match-beginning 0)))
1272 (if (setq continue (antlr-search-forward ";"))
1273 (antlr-skip-exception-part t))))
1275 (cons (cons "Classes" (nreverse classes)) (nreverse items))
1279 ;;;===========================================================================
1280 ;;; Parse grammar files (internal functions)
1281 ;;;===========================================================================
1283 (defun antlr-skip-exception-part (skip-comment)
1284 "Skip exception part of current rule, i.e., everything after `;'.
1285 This also includes the options and tokens part of a grammar class
1286 header. If SKIP-COMMENT is non-nil, also skip the comment after that
1290 (antlr-c-forward-sws)
1291 (while (looking-at "options\\>\\|tokens\\>")
1293 (setq pos (antlr-skip-sexps 2)))
1295 ;; Problem: an action only belongs to a class def, not a normal rule.
1296 ;; But checking the current rule type is too expensive => only expect
1297 ;; an action if we have found an option or tokens part.
1298 (if (looking-at "{") (setq pos (antlr-skip-sexps 1)))
1299 (while (looking-at "exception\\>")
1300 (setq pos (antlr-skip-sexps 1))
1301 (when (looking-at "\\[")
1302 (setq pos (antlr-skip-sexps 1)))
1303 (while (looking-at "catch\\>")
1304 (setq pos (antlr-skip-sexps 3)))))
1305 (or skip-comment (goto-char pos))))
1307 (defun antlr-skip-file-prelude (skip-comment)
1308 "Skip the file prelude: the header and file options.
1309 If SKIP-COMMENT is non-nil, also skip the comment after that part.
1310 Return the start position of the file prelude.
1312 Hack: if SKIP-COMMENT is `header-only' only skip header and return
1313 position before the comment after the header."
1314 (let* ((pos (point))
1316 (antlr-c-forward-sws)
1317 (if skip-comment (setq pos0 (point)))
1318 (while (looking-at "header\\>[ \t]*\\(\"\\)?")
1319 (setq pos (antlr-skip-sexps (if (match-beginning 1) 3 2))))
1320 (if (eq skip-comment 'header-only) ; a hack...
1322 (when (looking-at "options\\>")
1323 (setq pos (antlr-skip-sexps 2)))
1324 (or skip-comment (goto-char pos))
1327 (defun antlr-next-rule (arg skip-comment)
1328 "Move forward to next end of rule. Do it ARG many times.
1329 A grammar class header and the file prelude are also considered as a
1330 rule. Negative argument ARG means move back to ARGth preceding end of
1331 rule. The behavior is not defined when ARG is zero. If SKIP-COMMENT
1332 is non-nil, move to beginning of the rule."
1333 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1337 ;; first look whether point is in exception part
1338 (if (antlr-search-backward ";")
1342 (antlr-skip-exception-part skip-comment))
1343 (antlr-skip-file-prelude skip-comment))
1345 (unless (and (< (point) pos) (zerop (incf arg)))
1346 ;; if we have moved backward, we already moved one defun backward
1347 (goto-char beg) ; rewind (to ";" / point)
1348 (while (and arg (<= (incf arg) 0))
1349 (if (antlr-search-backward ";")
1352 ;; try file prelude:
1353 (setq pos (antlr-skip-file-prelude skip-comment))
1355 (if (>= (point) beg)
1356 (goto-char (if (>= pos beg) (point-min) pos)))
1357 (goto-char (if (or (>= (point) beg) (= (point) pos))
1360 (when arg ; always found a ";"
1362 (antlr-skip-exception-part skip-comment)))
1363 (if (<= (point) pos) ; moved backward?
1364 (goto-char pos) ; rewind
1365 (decf arg)) ; already moved one defun forward
1367 (while (>= (decf arg) 0)
1368 (antlr-search-forward ";"))
1369 (antlr-skip-exception-part skip-comment)))))
1371 (defun antlr-outside-rule-p ()
1372 "Non-nil if point is outside a grammar rule.
1373 Move to the beginning of the current rule if point is inside a rule."
1374 ;; WARNING: Should only be used with `antlr-action-syntax-table'!
1375 (let ((pos (point)))
1376 (antlr-next-rule -1 nil)
1377 (let ((between (or (bobp) (< (point) pos))))
1378 (antlr-c-forward-sws)
1379 (and between (> (point) pos) (goto-char pos)))))
1382 ;;;===========================================================================
1383 ;;; Parse grammar files (commands)
1384 ;;;===========================================================================
1385 ;; No (interactive "_") in Emacs... use `zmacs-region-stays'.
1387 (defun antlr-inside-rule-p ()
1388 "Non-nil if point is inside a grammar rule.
1389 A grammar class header and the file prelude are also considered as a
1392 (antlr-with-syntax-table antlr-action-syntax-table
1393 (not (antlr-outside-rule-p)))))
1395 (defunx antlr-end-of-rule (&optional arg)
1396 "Move forward to next end of rule. Do it ARG [default: 1] many times.
1397 A grammar class header and the file prelude are also considered as a
1398 rule. Negative argument ARG means move back to ARGth preceding end of
1399 rule. If ARG is zero, run `antlr-end-of-body'."
1403 (antlr-with-syntax-table antlr-action-syntax-table
1404 (antlr-next-rule arg nil))))
1406 (defunx antlr-beginning-of-rule (&optional arg)
1407 "Move backward to preceding beginning of rule. Do it ARG many times.
1408 A grammar class header and the file prelude are also considered as a
1409 rule. Negative argument ARG means move forward to ARGth next beginning
1410 of rule. If ARG is zero, run `antlr-beginning-of-body'."
1413 (antlr-beginning-of-body)
1414 (antlr-with-syntax-table antlr-action-syntax-table
1415 (antlr-next-rule (- arg) t))))
1417 (defunx antlr-end-of-body (&optional msg)
1418 "Move to position after the `;' of the current rule.
1419 A grammar class header is also considered as a rule. With optional
1420 prefix arg MSG, move to `:'."
1422 (antlr-with-syntax-table antlr-action-syntax-table
1423 (let ((orig (point)))
1424 (if (antlr-outside-rule-p)
1425 (error "Outside an ANTLR rule"))
1426 (let ((bor (point)))
1427 (when (< (antlr-skip-file-prelude t) (point))
1428 ;; Yes, we are in the file prelude
1430 (error (or msg "The file prelude is without `;'")))
1431 (antlr-search-forward ";")
1434 (progn (goto-char bor)
1435 (or (antlr-search-forward ":") (point-max))))
1438 (antlr-c-forward-sws))))))
1440 (defunx antlr-beginning-of-body ()
1441 "Move to the first element after the `:' of the current rule."
1443 (antlr-end-of-body "Class headers and the file prelude are without `:'"))
1446 ;;;===========================================================================
1447 ;;; Literal normalization, Hide Actions
1448 ;;;===========================================================================
1450 (defun antlr-downcase-literals (&optional transform)
1451 "Convert all literals in buffer to lower case.
1452 If non-nil, TRANSFORM is used on literals instead of `downcase-region'."
1454 (or transform (setq transform 'downcase-region))
1457 (goto-char (point-min))
1458 (antlr-with-syntax-table antlr-action-syntax-table
1459 (antlr-invalidate-context-cache)
1460 (while (antlr-re-search-forward "\"\\(\\sw\\(\\sw\\|-\\)*\\)\"" nil)
1461 (funcall transform (match-beginning 0) (match-end 0))
1463 (message "Transformed %d literals" literals)))
1465 (defun antlr-upcase-literals ()
1466 "Convert all literals in buffer to upper case."
1468 (antlr-downcase-literals 'upcase-region))
1470 (defun antlr-hide-actions (arg &optional silent)
1471 "Hide or unhide all actions in buffer.
1472 Hide all actions including arguments in brackets if ARG is 1 or if
1473 called interactively without prefix argument. Hide all actions
1474 excluding arguments in brackets if ARG is 2 or higher. Unhide all
1475 actions if ARG is 0 or negative. See `antlr-action-visibility'.
1477 Display a message unless optional argument SILENT is non-nil."
1479 (save-buffer-state-x
1481 (let ((regexp (if (= arg 1) "[]}]" "}"))
1482 (diff (and antlr-action-visibility
1483 (+ (max antlr-action-visibility 0) 2))))
1484 (antlr-hide-actions 0 t)
1486 (goto-char (point-min))
1487 (antlr-with-syntax-table antlr-action-syntax-table
1488 (antlr-invalidate-context-cache)
1489 (while (antlr-re-search-forward regexp nil)
1490 (let ((beg (ignore-errors-x (scan-sexps (point) -1))))
1492 (if diff ; braces are visible
1493 (if (> (point) (+ beg diff))
1494 (add-text-properties (1+ beg) (1- (point))
1495 '(invisible t intangible t)))
1496 ;; if actions is on line(s) of its own, hide WS
1497 (and (looking-at "[ \t]*$")
1500 (skip-chars-backward " \t")
1501 (and (bolp) (setq beg (point))))
1502 (beginning-of-line 2)) ; beginning of next line
1503 (add-text-properties beg (point)
1504 '(invisible t intangible t))))))))
1506 (message "Hide all actions (%s arguments)...done"
1507 (if (= arg 1) "including" "excluding"))))
1508 (remove-text-properties (point-min) (point-max)
1509 '(invisible nil intangible nil))
1511 (message "Unhide all actions (including arguments)...done")))))
1514 ;;;===========================================================================
1515 ;;; Insert option: command
1516 ;;;===========================================================================
1518 (defun antlr-insert-option (level option &optional location)
1519 "Insert file/grammar/rule/subrule option near point.
1520 LEVEL determines option kind to insert: 1=file, 2=grammar, 3=rule,
1521 4=subrule. OPTION is a string with the name of the option to insert.
1522 LOCATION can be specified for not calling `antlr-option-kind' twice.
1524 Inserting an option with this command works as follows:
1526 1. When called interactively, LEVEL is determined by the prefix
1527 argument or automatically deduced without prefix argument.
1528 2. Signal an error if no option of that level could be inserted, e.g.,
1529 if the buffer is read-only, the option area is outside the visible
1530 part of the buffer or a subrule/rule option should be inserted with
1531 point outside a subrule/rule.
1532 3. When called interactively, OPTION is read from the minibuffer with
1533 completion over the known options of the given LEVEL.
1534 4. Ask user for confirmation if the given OPTION does not seem to be a
1535 valid option to insert into the current file.
1536 5. Find a correct position to insert the option.
1537 6. Depending on the option, insert it the following way \(inserting an
1538 option also means inserting the option section if necessary\):
1539 - Insert the option and let user insert the value at point.
1540 - Read a value (with completion) from the minibuffer, using a
1541 previous value as initial contents, and insert option with value.
1542 7. Final action depending on the option. For example, set the language
1543 according to a newly inserted language option.
1545 The name of all options with a specification for their values are stored
1546 in `antlr-options-alists'. The used specification also depends on the
1547 value of `antlr-tool-version', i.e., step 4 will warn you if you use an
1548 option that has been introduced in newer version of ANTLR, and step 5
1549 will offer completion using version-correct values.
1551 If the option already exists inside the visible part of the buffer, this
1552 command can be used to change the value of that option. Otherwise, find
1553 a correct position where the option can be inserted near point.
1555 The search for a correct position is as follows:
1557 * If search is within an area where options can be inserted, use the
1558 position of point. Inside the options section and if point is in
1559 the middle of a option definition, skip the rest of it.
1560 * If an options section already exists, insert the options at the end.
1561 If only the beginning of the area is visible, insert at the
1563 * Otherwise, find the position where an options section can be
1564 inserted and insert a new section before any comments. If the
1565 position before the comments is not visible, insert the new section
1568 This function also inserts \"options {...}\" and the \":\" if necessary,
1569 see `antlr-options-auto-colon'. See also `antlr-options-assign-string'.
1571 This command might also set the mark like \\[set-mark-command] does, see
1572 `antlr-options-push-mark'."
1573 (interactive (antlr-insert-option-interactive current-prefix-arg))
1574 (barf-if-buffer-read-only)
1575 (or location (setq location (cdr (antlr-option-kind level))))
1577 (error "Cannot deduce what kind of option to insert"))
1579 (error "Cannot insert any %s options around here"
1580 (elt antlr-options-headings (1- level)))))
1581 (let ((area (car location))
1582 (place (cdr location)))
1583 (cond ((null place) ; invisible
1585 "Invisible %s options, use %s to make them visible"
1586 "Invisible area for %s options, use %s to make it visible")
1587 (elt antlr-options-headings (1- level))
1588 (substitute-command-keys "\\[widen]")))
1589 ((null area) ; without option part
1590 (antlr-insert-option-do level option nil
1593 ((save-excursion ; with option part, option visible
1594 (goto-char (max (point-min) (car area)))
1595 (re-search-forward (concat "\\(^\\|;\\)[ \t]*\\(\\<"
1596 (regexp-quote option)
1597 "\\>\\)[ \t\n]*\\(\\(=[ \t]?\\)[ \t]*\\(\\(\\sw\\|\\s_\\)+\\|\"\\([^\n\"\\]\\|[\\][^\n]\\)*\"\\)?\\)?")
1598 ;; 2=name, 3=4+5, 4="=", 5=value
1599 (min (point-max) (cdr area))
1601 (antlr-insert-option-do level option
1602 (cons (or (match-beginning 5)
1603 (match-beginning 3))
1605 (and (null (cdr place)) area)
1606 (or (match-beginning 5)
1609 (t ; with option part, option not yet
1610 (antlr-insert-option-do level option t
1611 (and (null (cdr place)) area)
1614 (defun antlr-insert-option-interactive (arg)
1615 "Interactive specification for `antlr-insert-option'.
1616 Return \(LEVEL OPTION LOCATION)."
1617 (barf-if-buffer-read-only)
1618 (if arg (setq arg (prefix-numeric-value arg)))
1619 (unless (memq arg '(nil 1 2 3 4))
1620 (error "Valid prefix args: no=auto, 1=file, 2=grammar, 3=rule, 4=subrule"))
1621 (let* ((kind (antlr-option-kind arg))
1623 (if (atom (cdr kind))
1624 (list level nil (cdr kind))
1625 (let* ((table (elt antlr-options-alists (1- level)))
1626 (completion-ignore-case t) ;dynamic
1627 (input (completing-read (format "Insert %s option: "
1628 (elt antlr-options-headings
1631 (list level input (cdr kind))))))
1633 (defun antlr-options-menu-filter (level menu-items)
1634 "Return items for options submenu of level LEVEL."
1635 ;; checkdoc-params: (menu-items)
1636 (let ((active (if buffer-read-only
1638 (consp (cdr-safe (cdr (antlr-option-kind level)))))))
1639 (mapcar (lambda (option)
1641 (list 'antlr-insert-option level option)
1643 (sort (mapcar 'car (elt antlr-options-alists (1- level)))
1647 ;;;===========================================================================
1648 ;;; Insert option: determine section-kind
1649 ;;;===========================================================================
1651 (defun antlr-option-kind (requested)
1652 "Return level and location for option to insert near point.
1653 Call function `antlr-option-level' with argument REQUESTED. If the
1654 result is nil, return \(REQUESTED \. error). If the result has the
1655 non-nil value LEVEL, return \(LEVEL \. LOCATION) where LOCATION looks
1656 like \(AREA \. PLACE), see `antlr-option-location'."
1659 (let ((min0 (point-min)) ; before `widen'!
1662 (level (antlr-option-level requested)) ; calls `widen'!
1665 (setq level requested))
1666 ((eq level 1) ; file options
1667 (goto-char (point-min))
1668 (setq pos (antlr-skip-file-prelude 'header-only)))
1669 ((not (eq level 3)) ; grammar or subrule options
1671 (antlr-c-forward-sws))
1672 ((looking-at "^\\(private[ \t\n]\\|public[ \t\n]\\|protected[ \t\n]\\)?[ \t\n]*\\(\\(\\sw\\|\\s_\\)+\\)[ \t\n]*\\(!\\)?[ \t\n]*\\(\\[\\)?")
1673 ;; rule options, with complete rule header
1674 (goto-char (or (match-end 4) (match-end 3)))
1675 (setq pos (antlr-skip-sexps (if (match-end 5) 1 0)))
1676 (when (looking-at "returns[ \t\n]*\\[")
1677 (goto-char (1- (match-end 0)))
1678 (setq pos (antlr-skip-sexps 1)))))
1680 (cond ((null pos) 'error)
1681 ((looking-at "options[ \t\n]*{")
1682 (goto-char (match-end 0))
1683 (setq pos (ignore-errors-x (scan-lists (point) 1 1)))
1684 (antlr-option-location orig min0 max0
1686 (if pos (1- pos) (point-max))
1689 (antlr-option-location orig min0 max0
1693 (defun antlr-option-level (requested)
1694 "Return level for option to insert near point.
1695 Remove any restrictions from current buffer and return level for the
1696 option to insert near point, i.e., 1, 2, 3, 4, or nil if no such option
1697 can be inserted. If REQUESTED is non-nil, it is the only possible value
1698 to return except nil. If REQUESTED is nil, return level for the nearest
1699 option kind, i.e., the highest number possible.
1701 If the result is 2, point is at the beginning of the class after the
1702 class definition. If the result is 3 or 4, point is at the beginning of
1703 the rule/subrule after the init action. Otherwise, the point position
1706 (if (eq requested 1)
1708 (antlr-with-syntax-table antlr-action-syntax-table
1709 (antlr-invalidate-context-cache)
1710 (let* ((orig (point))
1711 (outsidep (antlr-outside-rule-p))
1713 (if (eq (char-after) ?\{) (antlr-skip-sexps 1))
1714 (setq bor (point)) ; beginning of rule (after init action)
1715 (cond ((eq requested 2) ; grammar options required?
1716 (let (boc) ; beginning of class
1717 (goto-char (point-min))
1718 (while (and (<= (point) bor)
1719 (antlr-re-search-forward antlr-class-header-regexp
1721 (if (<= (match-beginning 0) bor)
1722 (setq boc (match-end 0))))
1726 ((save-excursion ; in region of file options?
1727 (goto-char (point-min))
1728 (antlr-skip-file-prelude t) ; ws/comment after: OK
1730 (and (null requested) 1))
1731 (outsidep ; outside rule not OK
1733 ((looking-at antlr-class-header-regexp) ; rule = class def?
1734 (goto-char (match-end 0))
1735 (and (null requested) 2))
1736 ((eq requested 3) ; rule options required?
1739 ((setq depth (antlr-syntactic-grammar-depth orig bor))
1740 (if (> depth 0) ; move out of actions
1741 (goto-char (scan-lists (point) -1 depth)))
1742 (set-syntax-table antlr-mode-syntax-table)
1743 (antlr-invalidate-context-cache)
1744 (if (eq (antlr-syntactic-context) 0) ; not in subrule?
1745 (unless (eq requested 4)
1748 (goto-char (1+ (scan-lists (point) -1 1)))
1751 (defun antlr-option-location (orig min-vis max-vis min-area max-area withp)
1752 "Return location for the options area.
1753 ORIG is the original position of `point', MIN-VIS is `point-min' and
1754 MAX-VIS is `point-max'. If WITHP is non-nil, there exists an option
1755 specification and it starts after the brace at MIN-AREA and stops at
1756 MAX-AREA. If WITHP is nil, there is no area and the region where it
1757 could be inserted starts at MIN-AREA and stops at MAX-AREA.
1759 The result has the form (AREA . PLACE). AREA is (MIN-AREA . MAX-AREA)
1760 if WITHP is non-nil, and nil otherwise. PLACE is nil if the area is
1761 invisible, (ORIG) if ORIG is inside the area, (MIN-AREA . beginning) for
1762 a visible start position and (MAX-AREA . end) for a visible end position
1763 where the beginning is preferred if WITHP is nil and the end if WITHP is
1765 (cons (and withp (cons min-area max-area))
1766 (cond ((and (<= min-area orig) (<= orig max-area)
1769 (not (memq (antlr-syntactic-context)
1770 '(comment block-comment)))))
1771 ;; point in options area and not in comment
1773 ((and (null withp) (<= min-vis min-area) (<= min-area max-vis))
1774 ;; use start of options area (only if not `withp')
1775 (cons min-area 'beginning))
1776 ((and (<= min-vis max-area) (<= max-area max-vis))
1777 ;; use end of options area
1778 (cons max-area 'end))
1779 ((and withp (<= min-vis min-area) (<= min-area max-vis))
1780 ;; use start of options area (only if `withp')
1781 (cons min-area 'beginning)))))
1783 (defun antlr-syntactic-grammar-depth (pos beg)
1784 "Return syntactic context depth at POS.
1785 Move to POS and from there on to the beginning of the string or comment
1786 if POS is inside such a construct. Then, return the syntactic context
1787 depth at point if the point position is smaller than BEG.
1788 WARNING: this may alter `match-data'."
1790 (let ((context (or (antlr-syntactic-context) 0)))
1791 (while (and context (not (integerp context)))
1792 (cond ((eq context 'string)
1794 (and (search-backward "\"" nil t)
1796 (or (antlr-syntactic-context) 0))))
1797 ((memq context '(comment block-comment))
1799 (and (re-search-backward "/[/*]" nil t)
1801 (or (antlr-syntactic-context) 0))))))
1805 ;;;===========================================================================
1806 ;;; Insert options: do the insertion
1807 ;;;===========================================================================
1809 (defun antlr-insert-option-do (level option old area pos)
1810 "Insert option into buffer at position POS.
1811 Insert option of level LEVEL and name OPTION. If OLD is non-nil, an
1812 options area is already exists. If OLD looks like \(BEG \. END), the
1813 option already exists. Then, BEG is the start position of the option
1814 value, the position of the `=' or nil, and END is the end position of
1815 the option value or nil.
1817 If the original point position was outside an options area, AREA is nil.
1818 Otherwise, and if an option specification already exists, AREA is a cons
1819 cell where the two values determine the area inside the braces."
1820 (let* ((spec (cdr (assoc option (elt antlr-options-alists (1- level)))))
1821 (value (antlr-option-spec level option (cdr spec) (consp old))))
1822 (if (fboundp (car spec)) (funcall (car spec) 'before-input option))
1823 ;; set mark (unless point was inside options area before)
1824 (if (cond (area (eq antlr-options-push-mark t))
1825 ((numberp antlr-options-push-mark)
1826 (> (count-lines (min (point) pos) (max (point) pos))
1827 antlr-options-push-mark))
1828 (antlr-options-push-mark))
1830 ;; read option value -----------------------------------------------------
1833 ;; no option specification found
1834 (if (y-or-n-p (format "Insert unknown %s option %s? "
1835 (elt antlr-options-headings (1- level))
1837 (message "Insert value for %s option %s"
1838 (elt antlr-options-headings (1- level))
1840 (error "Didn't insert unknown %s option %s"
1841 (elt antlr-options-headings (1- level))
1843 ;; option specification found
1844 (setq value (cdr value))
1846 (let ((initial (and (consp old) (cdr old)
1847 (buffer-substring (car old) (cdr old)))))
1848 (setq value (apply (car value)
1850 (if (eq (aref initial 0) ?\")
1854 (message (cadr value))
1856 ;; insert value ----------------------------------------------------------
1858 (antlr-insert-option-existing old value)
1860 ;; Move outside string/comment if point is inside option spec
1861 (antlr-syntactic-grammar-depth (point) (car area)))
1862 (antlr-insert-option-space area old)
1863 (or old (antlr-insert-option-area level))
1864 (insert option " = ;")
1866 (if value (insert value)))
1867 ;; final -----------------------------------------------------------------
1868 (if (fboundp (car spec)) (funcall (car spec) 'after-insertion option))))
1870 (defun antlr-option-spec (level option specs existsp)
1871 "Return version correct option value specification.
1872 Return specification for option OPTION of kind level LEVEL. SPECS
1873 should correspond to the VALUE-SPEC... in `antlr-option-alists'.
1874 EXISTSP determines whether the option already exists."
1876 (while (and specs (>= antlr-tool-version (caar specs)))
1877 (setq value (pop specs)))
1878 (cond (value) ; found correct spec
1879 ((null specs) nil) ; didn't find any specs
1880 (existsp (car specs)) ; wrong version, but already present
1881 ((y-or-n-p (format "Insert v%s %s option %s in v%s? "
1882 (antlr-version-string (caar specs))
1883 (elt antlr-options-headings (1- level))
1885 (antlr-version-string antlr-tool-version)))
1888 (error "Didn't insert v%s %s option %s in v%s"
1889 (antlr-version-string (caar specs))
1890 (elt antlr-options-headings (1- level))
1892 (antlr-version-string antlr-tool-version))))))
1894 (defun antlr-version-string (version)
1895 "Format the Antlr version number VERSION, see `antlr-tool-version'."
1896 (let ((version100 (/ version 100)))
1898 (/ version100 100) (mod version100 100) (mod version 100))))
1901 ;;;===========================================================================
1902 ;;; Insert options: the details (used by `antlr-insert-option-do')
1903 ;;;===========================================================================
1905 (defun antlr-insert-option-existing (old value)
1906 "Insert option value VALUE at point for existing option.
1907 For OLD, see `antlr-insert-option-do'."
1909 (unless (car old) (insert antlr-options-assign-string))
1910 ;; with user input => insert if necessary
1912 (if (cdr old) ; with value
1913 (if (string-equal value (buffer-substring (car old) (cdr old)))
1914 (goto-char (cdr old))
1915 (delete-region (car old) (cdr old))
1918 (unless (looking-at "\\([^\n=;{}/'\"]\\|'\\([^\n'\\]\\|\\\\.\\)*'\\|\"\\([^\n\"\\]\\|\\\\.\\)*\"\\)*;")
1919 ;; stuff (no =, {, } or /) at point is not followed by ";"
1923 (defun antlr-insert-option-space (area old)
1924 "Find appropriate place to insert option, insert newlines/spaces.
1925 For AREA and OLD, see `antlr-insert-option-do'."
1926 (let ((orig (point))
1928 (skip-chars-backward " \t")
1930 (let ((before (char-after (1- (point)))))
1932 (and old ; with existing options area
1933 (consp area) ; if point inside existing area
1934 (not (eq before ?\;)) ; if not at beginning of option
1935 ; => skip to end of option
1936 (if (and (search-forward ";" (cdr area) t)
1937 (let ((context (antlr-syntactic-context)))
1938 (or (null context) (numberp context))))
1941 (skip-chars-forward " \t")
1943 (if (looking-at "$\\|//")
1944 ;; just comment after point => skip (+ lines w/ same col comment)
1945 (let ((same (if (> (match-end 0) (match-beginning 0))
1947 (beginning-of-line 2)
1948 (or (bolp) (insert "\n"))
1949 (when (and same (null area)) ; or (consp area)?
1950 (while (and (looking-at "[ \t]*\\(//\\)")
1951 (goto-char (match-beginning 1))
1952 (= (current-column) same))
1953 (beginning-of-line 2)
1954 (or (bolp) (insert "\n")))))
1957 (progn (insert "\n") (antlr-indent-line))
1958 (unless (eq (char-after (1- (point))) ?\ )
1960 (unless (eq (char-after (point)) ?\ )
1965 (beginning-of-line 1)
1968 (antlr-indent-line))))
1970 (defun antlr-insert-option-area (level)
1971 "Insert new options area for options of level LEVEL.
1972 Used by `antlr-insert-option-do'."
1973 (insert "options {\n\n}")
1974 (when (and antlr-options-auto-colon
1977 (antlr-c-forward-sws)
1978 (if (eq (char-after (point)) ?\{) (antlr-skip-sexps 1))
1979 (not (eq (char-after (point)) ?\:))))
1985 (beginning-of-line 0)
1986 (antlr-indent-line))
1989 ;;;===========================================================================
1990 ;;; Insert options: in `antlr-options-alists'
1991 ;;;===========================================================================
1993 (defun antlr-read-value (initial-contents prompt
1994 &optional as-string table table-x)
1995 "Read a string from the minibuffer, possibly with completion.
1996 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
1997 PROMPT is a string to prompt with, normally it ends in a colon and a
1998 space. If AS-STRING is t or is a member \(comparison done with `eq') of
1999 `antlr-options-style', return printed representation of the user input,
2000 otherwise return the user input directly.
2002 If TABLE or TABLE-X is non-nil, read with completion. The completion
2003 table is the resulting alist of TABLE-X concatenated with TABLE where
2004 TABLE can also be a function evaluation to an alist.
2006 Used inside `antlr-options-alists'."
2007 (let* ((completion-ignore-case t) ; dynamic
2008 (table0 (and (or table table-x)
2010 (if (functionp table) (funcall table) table))))
2012 (completing-read prompt table0 nil nil initial-contents)
2013 (read-from-minibuffer prompt initial-contents))))
2015 (or (eq as-string t)
2016 (cdr (assq as-string antlr-options-style))))
2020 (defun antlr-read-boolean (initial-contents prompt &optional table)
2021 "Read a boolean value from the minibuffer, with completion.
2022 If INITIAL-CONTENTS is non-nil, insert it in the minibuffer initially.
2023 PROMPT is a string to prompt with, normally it ends in a question mark
2024 and a space. \"(true or false) \" is appended if TABLE is nil.
2026 Read with completion over \"true\", \"false\" and the keys in TABLE, see
2027 also `antlr-read-value'.
2029 Used inside `antlr-options-alists'."
2030 (antlr-read-value initial-contents
2031 (if table prompt (concat prompt "(true or false) "))
2033 table '(("false") ("true"))))
2035 (defun antlr-language-option-extra (phase &rest dummies)
2036 ;; checkdoc-params: (dummies)
2037 "Change language according to the new value of the \"language\" option.
2038 Call `antlr-mode' if the new language would be different from the value
2039 of `antlr-language', keeping the value of variable `font-lock-mode'.
2041 Called in PHASE `after-insertion', see `antlr-options-alists'."
2042 (when (eq phase 'after-insertion)
2043 (let ((new-language (antlr-language-option t)))
2044 (or (null new-language)
2045 (eq new-language antlr-language)
2046 (let ((font-lock (and (boundp 'font-lock-mode) font-lock-mode)))
2047 (if font-lock (font-lock-mode 0))
2049 (and font-lock (null font-lock-mode) (font-lock-mode 1)))))))
2051 (defun antlr-c++-mode-extra (phase option &rest dummies)
2052 ;; checkdoc-params: (option dummies)
2053 "Warn if C++ option is used with the wrong language.
2054 Ask user \(\"y or n\"), if a C++ only option is going to be inserted but
2055 `antlr-language' has not the value `c++-mode'.
2057 Called in PHASE `before-input', see `antlr-options-alists'."
2058 (and (eq phase 'before-input)
2059 (not (eq antlr-language 'c++-mode))
2060 (not (y-or-n-p (format "Insert C++ %s option? " option)))
2061 (error "Didn't insert C++ %s option with language %s"
2062 option (cadr (assq antlr-language antlr-language-alist)))))
2065 ;;;===========================================================================
2066 ;;; Compute dependencies
2067 ;;;===========================================================================
2069 (defun antlr-file-dependencies ()
2070 "Return dependencies for grammar in current buffer.
2071 The result looks like \(FILE \(CLASSES \. SUPERS) VOCABS \. LANGUAGE)
2072 where CLASSES = ((CLASS . CLASS-EVOCAB) ...),
2073 SUPERS = ((SUPER . USE-EVOCAB-P) ...), and
2074 VOCABS = ((EVOCAB ...) . (IVOCAB ...))
2076 FILE is the current buffer's file-name without directory part and
2077 LANGUAGE is the value of `antlr-language' in the current buffer. Each
2078 EVOCAB is an export vocabulary and each IVOCAB is an import vocabulary.
2080 Each CLASS is a grammar class with its export vocabulary CLASS-EVOCAB.
2081 Each SUPER is a super-grammar class where USE-EVOCAB-P indicates whether
2082 its export vocabulary is used as an import vocabulary."
2083 (unless buffer-file-name
2084 (error "Grammar buffer does not visit a file"))
2085 (let (classes export-vocabs import-vocabs superclasses default-vocab)
2086 (antlr-with-syntax-table antlr-action-syntax-table
2087 (goto-char (point-min))
2088 (while (antlr-re-search-forward antlr-class-header-regexp nil)
2089 ;; parse class definition --------------------------------------------
2090 (let* ((class (match-string 2))
2091 (sclass (match-string 4))
2092 ;; export vocab defaults to class name (first grammar in file)
2093 ;; or to the export vocab of the first grammar in file:
2094 (evocab (or default-vocab class))
2096 (goto-char (match-end 0))
2097 (antlr-c-forward-sws)
2098 (while (looking-at "options\\>\\|\\(tokens\\)\\>")
2099 (if (match-beginning 1)
2100 (antlr-skip-sexps 2)
2101 (goto-char (match-end 0))
2102 (antlr-c-forward-sws)
2103 ;; parse grammar option sections -------------------------------
2104 (when (eq (char-after (point)) ?\{)
2105 (let* ((beg (1+ (point)))
2106 (end (1- (antlr-skip-sexps 1)))
2109 (if (re-search-forward "\\<exportVocab[ \t]*=[ \t]*\\([A-Za-z\300-\326\330-\337]\\sw*\\)" end t)
2110 (setq evocab (match-string 1)))
2112 (if (re-search-forward "\\<importVocab[ \t]*=[ \t]*\\([A-Za-z\300-\326\330-\337]\\sw*\\)" end t)
2113 (setq ivocab (match-string 1)))
2114 (goto-char cont)))))
2115 (unless (member sclass '("Parser" "Lexer" "TreeParser"))
2116 (let ((super (assoc sclass superclasses)))
2118 (or ivocab (setcdr super t))
2119 (push (cons sclass (null ivocab)) superclasses))))
2120 ;; remember class with export vocabulary:
2121 (push (cons class evocab) classes)
2122 ;; default export vocab is export vocab of first grammar in file:
2123 (or default-vocab (setq default-vocab evocab))
2124 (or (member evocab export-vocabs) (push evocab export-vocabs))
2126 (member ivocab import-vocabs) (push ivocab import-vocabs)))))
2128 (list* (file-name-nondirectory buffer-file-name)
2129 (cons (nreverse classes) (nreverse superclasses))
2130 (cons (nreverse export-vocabs) (nreverse import-vocabs))
2133 (defun antlr-directory-dependencies (dirname)
2134 "Return dependencies for all grammar files in directory DIRNAME.
2135 The result looks like \((CLASS-SPEC ...) \. \(FILE-DEP ...))
2136 where CLASS-SPEC = (CLASS (FILE \. EVOCAB) ...).
2138 FILE-DEP are the dependencies for each grammar file in DIRNAME, see
2139 `antlr-file-dependencies'. For each grammar class CLASS, FILE is a
2140 grammar file in which CLASS is defined and EVOCAB is the name of the
2141 export vocabulary specified in that file."
2142 (let ((grammar (directory-files dirname t "\\.g\\'")))
2144 (let ((temp-buffer (get-buffer-create
2145 (generate-new-buffer-name " *temp*")))
2146 (antlr-imenu-name nil) ; dynamic-let: no imenu
2147 (expanded-regexp (concat (format (regexp-quote
2148 (cadr antlr-special-file-formats))
2151 classes dependencies)
2154 (set-buffer temp-buffer)
2155 (widen) ; just in case...
2156 (dolist (file grammar)
2157 (when (and (file-regular-p file)
2158 (null (string-match expanded-regexp file)))
2159 (insert-file-contents file t nil nil t)
2160 (normal-mode t) ; necessary for major-mode, syntax
2161 ; table and `antlr-language'
2162 (when (eq major-mode 'antlr-mode)
2163 (let* ((file-deps (antlr-file-dependencies))
2164 (file (car file-deps)))
2166 (dolist (class-def (caadr file-deps))
2167 (let ((file-evocab (cons file (cdr class-def)))
2168 (class-spec (assoc (car class-def) classes)))
2170 (nconc (cdr class-spec) (list file-evocab))
2171 (push (list (car class-def) file-evocab)
2173 (push file-deps dependencies)))))))
2174 (kill-buffer temp-buffer))
2175 (cons (nreverse classes) (nreverse dependencies))))))
2178 ;;;===========================================================================
2179 ;;; Compilation: run ANTLR tool
2180 ;;;===========================================================================
2182 (defun antlr-superclasses-glibs (supers classes)
2183 "Compute the grammar lib option for the super grammars SUPERS.
2184 Look in CLASSES for the right grammar lib files for SUPERS. SUPERS is
2185 part SUPER in the result of `antlr-file-dependencies'. CLASSES is the
2186 part \(CLASS-SPEC ...) in the result of `antlr-directory-dependencies'.
2188 The result looks like \(OPTION WITH-UNKNOWN GLIB ...). OPTION is the
2189 complete \"-glib\" option. WITH-UNKNOWN has value t iff there is none
2190 or more than one grammar file for at least one super grammar.
2192 Each GLIB looks like \(GRAMMAR-FILE \. EVOCAB). GRAMMAR-FILE is a file
2193 in which a super-grammar is defined. EVOCAB is the value of the export
2194 vocabulary of the super-grammar or nil if it is not needed."
2195 ;; If the superclass is defined in the same file, that file will be included
2196 ;; with -glib again. This will lead to a redefinition. But defining a
2197 ;; analyzer of the same class twice in a file will lead to an error anyway...
2198 (let (glibs unknown)
2200 (let* ((super (pop supers))
2201 (sup-files (cdr (assoc (car super) classes)))
2202 (file (and sup-files (null (cdr sup-files)) (car sup-files))))
2203 (or file (setq unknown t)) ; not exactly one file
2204 (push (cons (or (car file)
2205 (format (car antlr-unknown-file-formats)
2209 (format (cadr antlr-unknown-file-formats)
2212 (cons (if glibs (concat " -glib " (mapconcat 'car glibs ";")) "")
2213 (cons unknown glibs))))
2215 (defun antlr-run-tool (command file &optional saved)
2216 "Run Antlr took COMMAND on grammar FILE.
2217 When called interactively, COMMAND is read from the minibuffer and
2218 defaults to `antlr-tool-command' with a computed \"-glib\" option if
2221 Save all buffers first unless optional value SAVED is non-nil. When
2222 called interactively, the buffers are always saved, see also variable
2223 `antlr-ask-about-save'."
2224 (interactive (antlr-run-tool-interactive))
2225 (or saved (save-some-buffers (not antlr-ask-about-save)))
2226 (let ((default-directory (file-name-directory file)))
2227 (require 'compile) ; only `compile' autoload
2228 (compile-internal (concat command " " (file-name-nondirectory file))
2229 "No more errors" "Antlr-Run")))
2231 (defun antlr-run-tool-interactive ()
2232 ;; code in `interactive' is not compiled
2233 "Interactive specification for `antlr-run-tool'.
2234 Use prefix argument ARG to return \(COMMAND FILE SAVED)."
2235 (let* ((supers (cdadr (save-excursion
2238 (antlr-file-dependencies)))))
2241 (save-some-buffers (not antlr-ask-about-save) nil)
2242 (setq glibs (car (antlr-superclasses-glibs
2244 (car (antlr-directory-dependencies
2245 (antlr-default-directory)))))))
2246 (list (antlr-read-shell-command "Run Antlr on current file with: "
2247 (concat antlr-tool-command glibs " "))
2252 ;;;===========================================================================
2253 ;;; Makefile creation
2254 ;;;===========================================================================
2256 (defun antlr-makefile-insert-variable (number pre post)
2257 "Insert Makefile variable numbered NUMBER according to specification.
2258 Also insert strings PRE and POST before and after the variable."
2259 (let ((spec (cadr antlr-makefile-specification)))
2262 (if number (format (cadr spec) number) (car spec))
2265 (defun antlr-insert-makefile-rules (&optional in-makefile)
2266 "Insert Makefile rules in the current buffer at point.
2267 IN-MAKEFILE is non-nil, if the current buffer is the Makefile. See
2268 command `antlr-show-makefile-rules' for detail."
2269 (let* ((dirname (antlr-default-directory))
2270 (deps0 (antlr-directory-dependencies dirname))
2271 (classes (car deps0)) ; CLASS -> (FILE . EVOCAB) ...
2272 (deps (cdr deps0)) ; FILE -> (c . s) (ev . iv) . LANGUAGE
2274 (gen-sep (or (caddr (cadr antlr-makefile-specification)) " "))
2275 (n (and (cdr deps) (cadr antlr-makefile-specification) 0)))
2276 (or in-makefile (set-buffer standard-output))
2278 (let ((supers (cdadr dep))
2279 (lang (cdr (assoc (cdddr dep) antlr-file-formats-alist))))
2281 (antlr-makefile-insert-variable n "" " =")
2284 (format (cadr antlr-special-file-formats)
2285 (file-name-sans-extension (car dep)))))
2286 (dolist (class-def (caadr dep))
2287 (let ((sep gen-sep))
2288 (dolist (class-file (cadr lang))
2289 (insert sep (format class-file (car class-def)))
2291 (dolist (evocab (caaddr dep))
2292 (let ((sep gen-sep))
2293 (dolist (vocab-file (cons (car antlr-special-file-formats)
2295 (insert sep (format vocab-file evocab))
2297 (antlr-makefile-insert-variable n "\n$(" ")")
2298 (insert ": " (car dep))
2299 (dolist (ivocab (cdaddr dep))
2300 (insert " " (format (car antlr-special-file-formats) ivocab)))
2301 (let ((glibs (antlr-superclasses-glibs supers classes)))
2302 (if (cadr glibs) (setq with-error t))
2303 (dolist (super (cddr glibs))
2304 (insert " " (car super))
2306 (insert " " (format (car antlr-special-file-formats)
2309 (caddr antlr-makefile-specification)
2312 (car antlr-makefile-specification)))))
2315 (antlr-makefile-insert-variable nil "" " =")
2316 (while (<= (incf i) n)
2317 (antlr-makefile-insert-variable i " $(" ")"))
2318 (insert "\n" (car antlr-makefile-specification))))
2319 (if (string-equal (car antlr-makefile-specification) "\n")
2320 (backward-delete-char 1))
2322 (goto-char (point-min))
2323 (insert antlr-help-unknown-file-text))
2325 (copy-region-as-kill (point-min) (point-max))
2326 (goto-char (point-min))
2327 (insert (format antlr-help-rules-intro dirname)))))
2330 (defun antlr-show-makefile-rules ()
2331 "Show Makefile rules for all grammar files in the current directory.
2332 If the `major-mode' of the current buffer has the value `makefile-mode',
2333 the rules are directory inserted at point. Otherwise, a *Help* buffer
2334 is shown with the rules which are also put into the `kill-ring' for
2337 This command considers import/export vocabularies and grammar
2338 inheritance and provides a value for the \"-glib\" option if necessary.
2339 Customize variable `antlr-makefile-specification' for the appearance of
2342 If the file for a super-grammar cannot be determined, special file names
2343 are used according to variable `antlr-unknown-file-formats' and a
2344 commentary with value `antlr-help-unknown-file-text' is added. The
2345 *Help* buffer always starts with the text in `antlr-help-rules-intro'."
2347 (if (null (eq major-mode 'makefile-mode))
2348 (antlr-with-displaying-help-buffer 'antlr-insert-makefile-rules)
2350 (antlr-insert-makefile-rules t)))
2353 ;;;===========================================================================
2355 ;;;===========================================================================
2357 (defun antlr-indent-line ()
2358 "Indent the current line as ANTLR grammar code.
2359 The indentation of grammar lines are calculated by `c-basic-offset',
2361 - the level of the paren/brace/bracket depth,
2362 - plus 0/2/1, depending on the position inside the rule: header, body,
2364 - minus 1 if `antlr-indent-item-regexp' matches the beginning of the
2365 line starting from the first non-whitespace.
2367 Lines inside block comments are indented by `c-indent-line' according to
2368 `antlr-indent-comment'.
2370 Lines in actions except top-level actions in a header part or an option
2371 area are indented by `c-indent-line'.
2373 Lines in header actions are indented at column 0 if `antlr-language'
2374 equals to a key in `antlr-indent-at-bol-alist' and the line starting at
2375 the first non-whitespace is matched by the corresponding value.
2377 For the initialization of `c-basic-offset', see `antlr-indent-style' and,
2378 to a lesser extent, `antlr-tab-offset-alist'."
2380 (let ((orig (point))
2382 bol boi indent syntax cc-syntax)
2387 (error "Beginning of current line not visible"))
2388 (skip-chars-forward " \t")
2390 ;; check syntax at beginning of indentation ----------------------------
2391 (antlr-with-syntax-table antlr-action-syntax-table
2392 (antlr-invalidate-context-cache)
2393 (setq syntax (antlr-syntactic-context))
2394 (cond ((symbolp syntax)
2395 (setq indent nil)) ; block-comments, strings, (comments)
2397 (antlr-next-rule -1 t)
2398 (if (antlr-search-forward ":") (< boi (1- (point))) t))
2399 (setq indent 0)) ; in rule header
2400 ((if (antlr-search-forward ";") (< boi (point)) t)
2401 (setq indent 2)) ; in rule body
2404 (antlr-skip-exception-part nil)
2405 (setq indent (if (> (point) boi) 1 0))))) ; in exception part?
2406 ;; check whether to use indentation engine of cc-mode ------------------
2407 (antlr-invalidate-context-cache)
2409 (when (and indent (> syntax 0))
2410 (cond ((> syntax 1) ; block in action => use cc-mode
2413 (assq antlr-language antlr-indent-at-bol-alist)
2414 (looking-at (cdr (assq antlr-language
2415 antlr-indent-at-bol-alist))))
2417 ((setq cc-syntax (c-guess-basic-syntax))
2418 (let ((cc cc-syntax) symbol)
2419 (while (setq symbol (pop cc))
2421 (or (memq (car symbol)
2422 antlr-disabling-cc-syntactic-symbols)
2425 ;;; ((= indent 1) ; exception part => use cc-mode
2426 ;;; (setq indent nil))
2427 ;;; ((save-restriction ; not in option part => cc-mode
2428 ;;; (goto-char (scan-lists (point) -1 1))
2429 ;;; (skip-chars-backward " \t\n")
2430 ;;; (narrow-to-region (point-min) (point))
2431 ;;; (not (re-search-backward "\\<options\\'" nil t)))
2432 ;;; (setq indent nil)))))
2433 ;; compute the corresponding indentation and indent --------------------
2435 ;; Use the indentation engine of cc-mode
2438 (if (or (numberp syntax)
2439 (if (eq syntax 'string) nil (eq antlr-indent-comment t)))
2440 (c-indent-line cc-syntax)))
2443 (unless (symbolp syntax) ; direct indentation
2444 ;;(antlr-invalidate-context-cache)
2445 (incf indent (antlr-syntactic-context))
2446 (and (> indent 0) (looking-at antlr-indent-item-regexp) (decf indent))
2447 (setq indent (* indent c-basic-offset)))
2448 ;; the usual major-mode indent stuff ---------------------------------
2449 (setq orig (- (point-max) orig))
2450 (unless (= (current-column) indent)
2451 (delete-region bol boi)
2454 ;; If initial point was within line's indentation,
2455 ;; position after the indentation. Else stay at same point in text.
2456 (if (> (- (point-max) orig) (point))
2457 (goto-char (- (point-max) orig)))))))
2459 (defun antlr-indent-command (&optional arg)
2460 "Indent the current line or insert tabs/spaces.
2461 With optional prefix argument ARG or if the previous command was this
2462 command, insert ARG tabs or spaces according to `indent-tabs-mode'.
2463 Otherwise, indent the current line with `antlr-indent-line'."
2465 (if (or arg (eq last-command 'antlr-indent-command))
2467 (let ((antlr-indent-comment (and antlr-indent-comment t))) ; dynamic
2468 (antlr-indent-line))))
2470 (defun antlr-electric-character (&optional arg)
2471 "Insert the character you type and indent the current line.
2472 Insert the character like `self-insert-command' and indent the current
2473 line as `antlr-indent-command' does. Do not indent the line if
2475 * this command is called with a prefix argument ARG,
2476 * there are characters except whitespaces between point and the
2477 beginning of the line, or
2478 * point is not inside a normal grammar code, { and } are also OK in
2481 This command is useful for a character which has some special meaning in
2482 ANTLR's syntax and influences the auto indentation, see
2483 `antlr-indent-item-regexp'."
2486 (save-excursion (skip-chars-backward " \t") (not (bolp)))
2487 (antlr-with-syntax-table antlr-action-syntax-table
2488 (antlr-invalidate-context-cache)
2489 (let ((context (antlr-syntactic-context)))
2490 (not (and (numberp context)
2492 (memq last-command-char '(?\{ ?\}))))))))
2493 (self-insert-command (prefix-numeric-value arg))
2494 (self-insert-command (prefix-numeric-value arg))
2495 (antlr-indent-line)))
2498 ;;;===========================================================================
2500 ;;;===========================================================================
2502 (defun antlr-c-init-language-vars ()
2503 "Like `c-init-language-vars-for' when using cc-mode before v5.29."
2504 (let ((settings ; (cdr '(setq...)) will be optimized
2505 (if (eq antlr-language 'c++-mode)
2506 (cdr '(setq ;' from `c++-mode' v5.20, v5.28
2507 c-keywords (c-identifier-re c-C++-keywords)
2508 c-conditional-key c-C++-conditional-key
2509 c-comment-start-regexp c-C++-comment-start-regexp
2510 c-class-key c-C++-class-key
2511 c-extra-toplevel-key c-C++-extra-toplevel-key
2512 c-access-key c-C++-access-key
2513 c-recognize-knr-p nil
2514 c-bitfield-key c-C-bitfield-key ; v5.28
2516 (cdr '(setq ; from `java-mode' v5.20, v5.28
2517 c-keywords (c-identifier-re c-Java-keywords)
2518 c-conditional-key c-Java-conditional-key
2519 c-comment-start-regexp c-Java-comment-start-regexp
2520 c-class-key c-Java-class-key
2523 c-recognize-knr-p nil
2524 c-access-key c-Java-access-key ; v5.20
2525 c-inexpr-class-key c-Java-inexpr-class-key ; v5.28
2528 (when (boundp (car settings))
2530 (set (car settings) (eval (cadr settings)))))
2531 (setq settings (cddr settings)))))
2533 (defun antlr-language-option (search)
2534 "Find language in `antlr-language-alist' for language option.
2535 If SEARCH is non-nil, find element for language option. Otherwise, find
2536 the default language."
2537 (let ((value (and search
2539 (goto-char (point-min))
2540 (re-search-forward (cdr antlr-language-limit-n-regexp)
2541 (car antlr-language-limit-n-regexp)
2544 (seq antlr-language-alist)
2546 ;; Like (find VALUE antlr-language-alist :key 'cddr :test 'member)
2549 (if (member value (cddr r))
2550 (setq seq nil) ; stop
2551 (setq r nil))) ; no result yet
2555 (defun antlr-mode ()
2556 "Major mode for editing ANTLR grammar files.
2559 (kill-all-local-variables)
2560 (c-initialize-cc-mode) ; cc-mode is required
2561 (unless (fboundp 'c-forward-sws) ; see above
2562 (fset 'antlr-c-forward-sws 'c-forward-syntactic-ws))
2563 ;; ANTLR specific ----------------------------------------------------------
2564 (setq major-mode 'antlr-mode
2566 (setq local-abbrev-table antlr-mode-abbrev-table)
2567 (unless antlr-mode-syntax-table
2568 (setq antlr-mode-syntax-table (make-syntax-table))
2569 (c-populate-syntax-table antlr-mode-syntax-table))
2570 (set-syntax-table antlr-mode-syntax-table)
2571 (unless antlr-action-syntax-table
2572 (let ((slist (nth 3 antlr-font-lock-defaults)))
2573 (setq antlr-action-syntax-table
2574 (copy-syntax-table antlr-mode-syntax-table))
2576 (modify-syntax-entry (caar slist) (cdar slist)
2577 antlr-action-syntax-table)
2578 (setq slist (cdr slist)))))
2579 (use-local-map antlr-mode-map)
2580 (make-local-variable 'antlr-language)
2581 (unless antlr-language
2582 (setq antlr-language
2583 (or (antlr-language-option t) (antlr-language-option nil))))
2584 (if (stringp (cadr (assq antlr-language antlr-language-alist)))
2587 (cadr (assq antlr-language antlr-language-alist)))))
2588 ;; indentation, for the C engine -------------------------------------------
2589 (setq c-buffer-is-cc-mode antlr-language)
2590 (cond ((fboundp 'c-init-language-vars-for) ; cc-mode 5.30.5+
2591 (c-init-language-vars-for antlr-language))
2592 ((fboundp 'c-init-c-language-vars) ; cc-mode 5.30 to 5.30.4
2593 (c-init-c-language-vars) ; not perfect, but OK
2594 (setq c-recognize-knr-p nil))
2595 ((fboundp 'c-init-language-vars) ; cc-mode 5.29
2596 (let ((init-fn 'c-init-language-vars))
2597 (funcall init-fn))) ; is a function in v5.29
2598 (t ; cc-mode upto 5.28
2599 (antlr-c-init-language-vars))) ; do it myself
2600 (c-basic-common-init antlr-language (or antlr-indent-style "gnu"))
2601 (make-local-variable 'outline-regexp)
2602 (make-local-variable 'outline-level)
2603 (make-local-variable 'require-final-newline)
2604 (make-local-variable 'indent-line-function)
2605 (make-local-variable 'indent-region-function)
2606 (setq outline-regexp "[^#\n\^M]"
2607 outline-level 'c-outline-level) ; TODO: define own
2608 (setq require-final-newline mode-require-final-newline)
2609 (setq indent-line-function 'antlr-indent-line
2610 indent-region-function nil) ; too lazy
2611 (setq comment-start "// "
2613 comment-start-skip "/\\*+ *\\|// *")
2614 ;; various -----------------------------------------------------------------
2615 (make-local-variable 'font-lock-defaults)
2616 (setq font-lock-defaults antlr-font-lock-defaults)
2617 (easy-menu-add antlr-mode-menu)
2618 (make-local-variable 'imenu-create-index-function)
2619 (setq imenu-create-index-function 'antlr-imenu-create-index-function)
2620 (make-local-variable 'imenu-generic-expression)
2621 (setq imenu-generic-expression t) ; fool stupid test
2622 (and antlr-imenu-name ; there should be a global variable...
2623 (fboundp 'imenu-add-to-menubar)
2624 (imenu-add-to-menubar
2625 (if (stringp antlr-imenu-name) antlr-imenu-name "Index")))
2627 (run-mode-hooks 'antlr-mode-hook))
2629 ;; A smarter version of `group-buffers-menu-by-mode-then-alphabetically' (in
2630 ;; XEmacs) could use the following property. The header of the submenu would
2631 ;; be "Antlr" instead of "Antlr.C++" or (not and!) "Antlr.Java".
2632 (put 'antlr-mode 'mode-name "Antlr")
2635 (defun antlr-set-tabs ()
2636 "Use ANTLR's convention for TABs according to `antlr-tab-offset-alist'.
2637 Used in `antlr-mode'. Also a useful function in `java-mode-hook'."
2638 (if buffer-file-name
2639 (let ((alist antlr-tab-offset-alist) elem)
2641 (setq elem (pop alist))
2642 (and (or (null (car elem)) (eq (car elem) major-mode))
2643 (or (null (cadr elem))
2644 (string-match (cadr elem) buffer-file-name))
2645 (setq tab-width (caddr elem)
2646 indent-tabs-mode (cadddr elem)
2649 ;;; Local IspellPersDict: .ispell_antlr
2651 ;;; arch-tag: 5de2be79-3d13-4560-8fbc-f7d0234dcb5c
2652 ;;; antlr-mode.el ends here