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