Avoid kill-emacs-hook errors hanging batch mode
[emacs.git] / lisp / progmodes / cc-defs.el
blob02b96517eb882a054fc6147c5c331a94c24b986f
1 ;;; cc-defs.el --- compile time definitions for CC Mode
3 ;; Copyright (C) 1985, 1987, 1992-2018 Free Software Foundation, Inc.
5 ;; Authors: 2003- Alan Mackenzie
6 ;; 1998- Martin Stjernholm
7 ;; 1992-1999 Barry A. Warsaw
8 ;; 1987 Dave Detlefs
9 ;; 1987 Stewart Clamen
10 ;; 1985 Richard M. Stallman
11 ;; Maintainer: bug-cc-mode@gnu.org
12 ;; Created: 22-Apr-1997 (split from cc-mode.el)
13 ;; Keywords: c languages
14 ;; Package: cc-mode
16 ;; This file is part of GNU Emacs.
18 ;; GNU Emacs is free software: you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation, either version 3 of the License, or
21 ;; (at your option) any later version.
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 ;; GNU General Public License for more details.
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs. If not, see <https://www.gnu.org/licenses/>.
31 ;;; Commentary:
33 ;; This file contains macros, defsubsts, and various other things that
34 ;; must be loaded early both during compilation and at runtime.
36 ;;; Code:
38 (eval-when-compile
39 (let ((load-path
40 (if (and (boundp 'byte-compile-dest-file)
41 (stringp byte-compile-dest-file))
42 (cons (file-name-directory byte-compile-dest-file) load-path)
43 load-path)))
44 (load "cc-bytecomp" nil t)))
46 (eval-and-compile
47 (defvar c--cl-library
48 (if (locate-library "cl-lib")
49 'cl-lib
50 'cl)))
52 (cc-external-require c--cl-library)
53 ; was (cc-external-require 'cl). ACM 2005/11/29.
54 ; Changed from (eval-when-compile (require 'cl)) back to
55 ; cc-external-require, 2015-08-12.
56 (cc-external-require 'regexp-opt)
58 ;; Silence the compiler.
59 (cc-bytecomp-defvar c-enable-xemacs-performance-kludge-p) ; In cc-vars.el
60 (cc-bytecomp-defun region-active-p) ; XEmacs
61 (cc-bytecomp-defvar mark-active) ; Emacs
62 (cc-bytecomp-defvar deactivate-mark) ; Emacs
63 (cc-bytecomp-defvar inhibit-point-motion-hooks) ; Emacs
64 (cc-bytecomp-defvar parse-sexp-lookup-properties) ; Emacs
65 (cc-bytecomp-defvar text-property-default-nonsticky) ; Emacs 21
66 (cc-bytecomp-defun string-to-syntax) ; Emacs 21
69 ;; cc-fix.el contains compatibility macros that should be used if
70 ;; needed.
71 (cc-conditional-require
72 'cc-fix (or (/= (regexp-opt-depth "\\(\\(\\)\\)") 2)
73 (not (fboundp 'push))
74 ;; XEmacs 21.4 doesn't have `delete-dups'.
75 (not (fboundp 'delete-dups))))
77 (cc-conditional-require-after-load
78 'cc-fix "font-lock"
79 (and
80 (featurep 'xemacs)
81 (progn
82 (require 'font-lock)
83 (let (font-lock-keywords)
84 (font-lock-compile-keywords '("\\<\\>"))
85 font-lock-keywords))))
88 ;;; Variables also used at compile time.
90 (defconst c-version "5.33.1"
91 "CC Mode version number.")
93 (defconst c-version-sym (intern c-version))
94 ;; A little more compact and faster in comparisons.
96 (defvar c-buffer-is-cc-mode nil
97 "Non-nil for all buffers with a major mode derived from CC Mode.
98 Otherwise, this variable is nil. I.e. this variable is non-nil for
99 `c-mode', `c++-mode', `objc-mode', `java-mode', `idl-mode',
100 `pike-mode', `awk-mode', and any other non-CC Mode mode that calls
101 `c-initialize-cc-mode'. The value is the mode symbol itself
102 \(i.e. `c-mode' etc) of the original CC Mode mode, or just t if it's
103 not known.")
104 (make-variable-buffer-local 'c-buffer-is-cc-mode)
106 ;; Have to make `c-buffer-is-cc-mode' permanently local so that it
107 ;; survives the initialization of the derived mode.
108 (put 'c-buffer-is-cc-mode 'permanent-local t)
111 ;; The following is used below during compilation.
112 (eval-and-compile
113 (defvar c-inside-eval-when-compile nil)
115 (defmacro cc-eval-when-compile (&rest body)
116 "Like `progn', but evaluates the body at compile time.
117 The result of the body appears to the compiler as a quoted constant.
119 This variant works around bugs in `eval-when-compile' in various
120 \(X)Emacs versions. See cc-defs.el for details."
122 (if c-inside-eval-when-compile
123 ;; XEmacs 21.4.6 has a bug in `eval-when-compile' in that it
124 ;; evaluates its body at macro expansion time if it's nested
125 ;; inside another `eval-when-compile'. So we use a dynamically
126 ;; bound variable to avoid nesting them.
127 `(progn ,@body)
129 `(eval-when-compile
130 ;; In all (X)Emacsen so far, `eval-when-compile' byte compiles
131 ;; its contents before evaluating it. That can cause forms to
132 ;; be compiled in situations they aren't intended to be
133 ;; compiled.
135 ;; Example: It's not possible to defsubst a primitive, e.g. the
136 ;; following will produce an error (in any emacs flavor), since
137 ;; `nthcdr' is a primitive function that's handled specially by
138 ;; the byte compiler and thus can't be redefined:
140 ;; (defsubst nthcdr (val) val)
142 ;; `defsubst', like `defmacro', needs to be evaluated at
143 ;; compile time, so this will produce an error during byte
144 ;; compilation.
146 ;; CC Mode occasionally needs to do things like this for
147 ;; cross-emacs compatibility. It therefore uses the following
148 ;; to conditionally do a `defsubst':
150 ;; (eval-when-compile
151 ;; (if (not (fboundp 'foo))
152 ;; (defsubst foo ...)))
154 ;; But `eval-when-compile' byte compiles its contents and
155 ;; _then_ evaluates it (in all current emacs versions, up to
156 ;; and including Emacs 20.6 and XEmacs 21.1 as of this
157 ;; writing). So this will still produce an error, since the
158 ;; byte compiler will get to the defsubst anyway. That's
159 ;; arguably a bug because the point with `eval-when-compile' is
160 ;; that it should evaluate rather than compile its contents.
162 ;; We get around it by expanding the body to a quoted
163 ;; constant that we eval. That otoh introduce a problem in
164 ;; that a returned lambda expression doesn't get byte
165 ;; compiled (even if `function' is used).
166 (eval '(let ((c-inside-eval-when-compile t)) ,@body)))))
168 (put 'cc-eval-when-compile 'lisp-indent-hook 0))
171 ;;; Macros.
172 (defmacro c--mapcan (fun liszt)
173 ;; CC Mode equivalent of `mapcan' which bridges the difference
174 ;; between the host [X]Emacsen."
175 ;; The motivation for this macro is to avoid the irritating message
176 ;; "function `mapcan' from cl package called at runtime" produced by Emacs.
177 (cond
178 ((and (fboundp 'mapcan)
179 (subrp (symbol-function 'mapcan)))
180 ;; XEmacs and Emacs >= 26.
181 `(mapcan ,fun ,liszt))
182 ((eq c--cl-library 'cl-lib)
183 ;; Emacs >= 24.3, < 26.
184 `(cl-mapcan ,fun ,liszt))
186 ;; Emacs <= 24.2. It would be nice to be able to distinguish between
187 ;; compile-time and run-time use here.
188 `(apply 'nconc (mapcar ,fun ,liszt)))))
190 (defmacro c--set-difference (liszt1 liszt2 &rest other-args)
191 ;; Macro to smooth out the renaming of `set-difference' in Emacs 24.3.
192 (if (eq c--cl-library 'cl-lib)
193 `(cl-set-difference ,liszt1 ,liszt2 ,@other-args)
194 `(set-difference ,liszt1 ,liszt2 ,@other-args)))
196 (defmacro c--intersection (liszt1 liszt2 &rest other-args)
197 ;; Macro to smooth out the renaming of `intersection' in Emacs 24.3.
198 (if (eq c--cl-library 'cl-lib)
199 `(cl-intersection ,liszt1 ,liszt2 ,@other-args)
200 `(intersection ,liszt1 ,liszt2 ,@other-args)))
202 (eval-and-compile
203 (defmacro c--macroexpand-all (form &optional environment)
204 ;; Macro to smooth out the renaming of `cl-macroexpand-all' in Emacs 24.3.
205 (if (fboundp 'macroexpand-all)
206 `(macroexpand-all ,form ,environment)
207 `(cl-macroexpand-all ,form ,environment)))
209 (defmacro c--delete-duplicates (cl-seq &rest cl-keys)
210 ;; Macro to smooth out the renaming of `delete-duplicates' in Emacs 24.3.
211 (if (eq c--cl-library 'cl-lib)
212 `(cl-delete-duplicates ,cl-seq ,@cl-keys)
213 `(delete-duplicates ,cl-seq ,@cl-keys))))
215 (defmacro c-point (position &optional point)
216 "Return the value of certain commonly referenced POSITIONs relative to POINT.
217 The current point is used if POINT isn't specified. POSITION can be
218 one of the following symbols:
220 `bol' -- beginning of line
221 `eol' -- end of line
222 `bod' -- beginning of defun
223 `eod' -- end of defun
224 `boi' -- beginning of indentation
225 `ionl' -- indentation of next line
226 `iopl' -- indentation of previous line
227 `bonl' -- beginning of next line
228 `eonl' -- end of next line
229 `bopl' -- beginning of previous line
230 `eopl' -- end of previous line
231 `bosws' -- beginning of syntactic whitespace
232 `eosws' -- end of syntactic whitespace
234 If the referenced position doesn't exist, the closest accessible point
235 to it is returned. This function does not modify the point or the mark."
237 (if (eq (car-safe position) 'quote)
238 (let ((position (eval position)))
239 (cond
241 ((eq position 'bol)
242 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
243 `(line-beginning-position)
244 `(save-excursion
245 ,@(if point `((goto-char ,point)))
246 (beginning-of-line)
247 (point))))
249 ((eq position 'eol)
250 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
251 `(line-end-position)
252 `(save-excursion
253 ,@(if point `((goto-char ,point)))
254 (end-of-line)
255 (point))))
257 ((eq position 'boi)
258 `(save-excursion
259 ,@(if point `((goto-char ,point)))
260 (back-to-indentation)
261 (point)))
263 ((eq position 'bod)
264 `(save-excursion
265 ,@(if point `((goto-char ,point)))
266 (c-beginning-of-defun-1)
267 (point)))
269 ((eq position 'eod)
270 `(save-excursion
271 ,@(if point `((goto-char ,point)))
272 (c-end-of-defun-1)
273 (point)))
275 ((eq position 'bopl)
276 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
277 `(line-beginning-position 0)
278 `(save-excursion
279 ,@(if point `((goto-char ,point)))
280 (forward-line -1)
281 (point))))
283 ((eq position 'bonl)
284 (if (and (cc-bytecomp-fboundp 'line-beginning-position) (not point))
285 `(line-beginning-position 2)
286 `(save-excursion
287 ,@(if point `((goto-char ,point)))
288 (forward-line 1)
289 (point))))
291 ((eq position 'eopl)
292 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
293 `(line-end-position 0)
294 `(save-excursion
295 ,@(if point `((goto-char ,point)))
296 (beginning-of-line)
297 (or (bobp) (backward-char))
298 (point))))
300 ((eq position 'eonl)
301 (if (and (cc-bytecomp-fboundp 'line-end-position) (not point))
302 `(line-end-position 2)
303 `(save-excursion
304 ,@(if point `((goto-char ,point)))
305 (forward-line 1)
306 (end-of-line)
307 (point))))
309 ((eq position 'iopl)
310 `(save-excursion
311 ,@(if point `((goto-char ,point)))
312 (forward-line -1)
313 (back-to-indentation)
314 (point)))
316 ((eq position 'ionl)
317 `(save-excursion
318 ,@(if point `((goto-char ,point)))
319 (forward-line 1)
320 (back-to-indentation)
321 (point)))
323 ((eq position 'bosws)
324 `(save-excursion
325 ,@(if point `((goto-char ,point)))
326 (c-backward-syntactic-ws)
327 (point)))
329 ((eq position 'eosws)
330 `(save-excursion
331 ,@(if point `((goto-char ,point)))
332 (c-forward-syntactic-ws)
333 (point)))
335 (t (error "Unknown buffer position requested: %s" position))))
337 ;; The bulk of this should perhaps be in a function to avoid large
338 ;; expansions, but this case is not used anywhere in CC Mode (and
339 ;; probably not anywhere else either) so we only have it to be on
340 ;; the safe side.
341 (message "Warning: c-point long expansion")
342 `(save-excursion
343 ,@(if point `((goto-char ,point)))
344 (let ((position ,position))
345 (cond
346 ((eq position 'bol) (beginning-of-line))
347 ((eq position 'eol) (end-of-line))
348 ((eq position 'boi) (back-to-indentation))
349 ((eq position 'bod) (c-beginning-of-defun-1))
350 ((eq position 'eod) (c-end-of-defun-1))
351 ((eq position 'bopl) (forward-line -1))
352 ((eq position 'bonl) (forward-line 1))
353 ((eq position 'eopl) (progn
354 (beginning-of-line)
355 (or (bobp) (backward-char))))
356 ((eq position 'eonl) (progn
357 (forward-line 1)
358 (end-of-line)))
359 ((eq position 'iopl) (progn
360 (forward-line -1)
361 (back-to-indentation)))
362 ((eq position 'ionl) (progn
363 (forward-line 1)
364 (back-to-indentation)))
365 ((eq position 'bosws) (c-backward-syntactic-ws))
366 ((eq position 'eosws) (c-forward-syntactic-ws))
367 (t (error "Unknown buffer position requested: %s" position))))
368 (point))))
370 (defvar lookup-syntax-properties) ;XEmacs.
372 (eval-and-compile
373 ;; Constant to decide at compilation time whether to use category
374 ;; properties. Currently (2010-03) they're available only on GNU Emacs.
375 (defconst c-use-category
376 (with-temp-buffer
377 (let ((parse-sexp-lookup-properties t)
378 (lookup-syntax-properties t))
379 (set-syntax-table (make-syntax-table))
380 (insert "<()>")
381 (put-text-property (point-min) (1+ (point-min))
382 'category 'c-<-as-paren-syntax)
383 (put-text-property (+ 3 (point-min)) (+ 4 (point-min))
384 'category 'c->-as-paren-syntax)
385 (goto-char (point-min))
386 (forward-sexp)
387 (= (point) (+ 4 (point-min)))))))
389 (defvar c-use-extents)
391 (defmacro c-next-single-property-change (position prop &optional object limit)
392 ;; See the doc string for either of the defuns expanded to.
393 (if (and c-use-extents
394 (fboundp 'next-single-char-property-change))
395 ;; XEmacs >= 2005-01-25
396 `(next-single-char-property-change ,position ,prop ,object ,limit)
397 ;; Emacs and earlier XEmacs
398 `(next-single-property-change ,position ,prop ,object ,limit)))
400 (defmacro c-region-is-active-p ()
401 ;; Return t when the region is active. The determination of region
402 ;; activeness is different in both Emacs and XEmacs.
403 (if (cc-bytecomp-fboundp 'region-active-p)
404 ;; XEmacs.
405 '(region-active-p)
406 ;; Old Emacs.
407 'mark-active))
409 (defmacro c-set-region-active (activate)
410 ;; Activate the region if ACTIVE is non-nil, deactivate it
411 ;; otherwise. Covers the differences between Emacs and XEmacs.
412 (if (fboundp 'zmacs-activate-region)
413 ;; XEmacs.
414 `(if ,activate
415 (zmacs-activate-region)
416 (zmacs-deactivate-region))
417 ;; Emacs.
418 `(setq mark-active ,activate)))
420 (defmacro c-set-keymap-parent (map parent)
421 (cond
422 ;; XEmacs
423 ((cc-bytecomp-fboundp 'set-keymap-parents)
424 `(set-keymap-parents ,map ,parent))
425 ;; Emacs
426 ((cc-bytecomp-fboundp 'set-keymap-parent)
427 `(set-keymap-parent ,map ,parent))
428 ;; incompatible
429 (t (error "CC Mode is incompatible with this version of Emacs"))))
431 (defmacro c-delete-and-extract-region (start end)
432 "Delete the text between START and END and return it."
433 (if (cc-bytecomp-fboundp 'delete-and-extract-region)
434 ;; Emacs 21.1 and later
435 `(delete-and-extract-region ,start ,end)
436 ;; XEmacs and Emacs 20.x
437 `(prog1
438 (buffer-substring ,start ,end)
439 (delete-region ,start ,end))))
441 (defmacro c-safe (&rest body)
442 ;; safely execute BODY, return nil if an error occurred
443 `(condition-case nil
444 (progn ,@body)
445 (error nil)))
446 (put 'c-safe 'lisp-indent-function 0)
448 (defmacro c-int-to-char (integer)
449 ;; In Emacs, a character is an integer. In XEmacs, a character is a
450 ;; type distinct from an integer. Sometimes we need to convert integers to
451 ;; characters. `c-int-to-char' makes this conversion, if necessary.
452 (if (fboundp 'int-to-char)
453 `(int-to-char ,integer)
454 integer))
456 (defmacro c-last-command-char ()
457 ;; The last character just typed. Note that `last-command-event' exists in
458 ;; both Emacs and XEmacs, but with confusingly different meanings.
459 (if (featurep 'xemacs)
460 'last-command-char
461 'last-command-event))
463 (defmacro c-sentence-end ()
464 ;; Get the regular expression `sentence-end'.
465 (if (cc-bytecomp-fboundp 'sentence-end)
466 ;; Emacs 22:
467 `(sentence-end)
468 ;; Emacs <22 + XEmacs
469 `sentence-end))
471 (defmacro c-default-value-sentence-end ()
472 ;; Get the default value of the variable sentence end.
473 (if (cc-bytecomp-fboundp 'sentence-end)
474 ;; Emacs 22:
475 `(let (sentence-end) (sentence-end))
476 ;; Emacs <22 + XEmacs
477 `(default-value 'sentence-end)))
479 ;; The following is essentially `save-buffer-state' from lazy-lock.el.
480 ;; It ought to be a standard macro.
481 (defmacro c-save-buffer-state (varlist &rest body)
482 "Bind variables according to VARLIST (in `let*' style) and eval BODY,
483 then restore the buffer state under the assumption that no significant
484 modification has been made in BODY. A change is considered
485 significant if it affects the buffer text in any way that isn't
486 completely restored again. Changes in text properties like `face' or
487 `syntax-table' are considered insignificant. This macro allows text
488 properties to be changed, even in a read-only buffer.
490 This macro should be placed around all calculations which set
491 \"insignificant\" text properties in a buffer, even when the buffer is
492 known to be writable. That way, these text properties remain set
493 even if the user undoes the command which set them.
495 This macro should ALWAYS be placed around \"temporary\" internal buffer
496 changes \(like adding a newline to calculate a text-property then
497 deleting it again), so that the user never sees them on his
498 `buffer-undo-list'. See also `c-tentative-buffer-changes'.
500 However, any user-visible changes to the buffer \(like auto-newlines)
501 must not be within a `c-save-buffer-state', since the user then
502 wouldn't be able to undo them.
504 The return value is the value of the last form in BODY."
505 (declare (debug t) (indent 1))
506 (if (fboundp 'with-silent-modifications)
507 `(with-silent-modifications (let* ,varlist ,@body))
508 `(let* ((modified (buffer-modified-p)) (buffer-undo-list t)
509 (inhibit-read-only t) (inhibit-point-motion-hooks t)
510 before-change-functions after-change-functions
511 deactivate-mark
512 buffer-file-name buffer-file-truename ; Prevent primitives checking
513 ; for file modification
514 ,@varlist)
515 (unwind-protect
516 (progn ,@body)
517 (and (not modified)
518 (buffer-modified-p)
519 (set-buffer-modified-p nil))))))
521 (defmacro c-tentative-buffer-changes (&rest body)
522 "Eval BODY and optionally restore the buffer contents to the state it
523 was in before BODY. Any changes are kept if the last form in BODY
524 returns non-nil. Otherwise it's undone using the undo facility, and
525 various other buffer state that might be affected by the changes is
526 restored. That includes the current buffer, point, mark, mark
527 activation \(similar to `save-excursion'), and the modified state.
528 The state is also restored if BODY exits nonlocally.
530 If BODY makes a change that unconditionally is undone then wrap this
531 macro inside `c-save-buffer-state'. That way the change can be done
532 even when the buffer is read-only, and without interference from
533 various buffer change hooks."
534 `(let (-tnt-chng-keep
535 -tnt-chng-state)
536 (unwind-protect
537 ;; Insert an undo boundary for use with `undo-more'. We
538 ;; don't use `undo-boundary' since it doesn't insert one
539 ;; unconditionally.
540 (setq buffer-undo-list (cons nil buffer-undo-list)
541 -tnt-chng-state (c-tnt-chng-record-state)
542 -tnt-chng-keep (progn ,@body))
543 (c-tnt-chng-cleanup -tnt-chng-keep -tnt-chng-state))))
544 (put 'c-tentative-buffer-changes 'lisp-indent-function 0)
546 (defun c-tnt-chng-record-state ()
547 ;; Used internally in `c-tentative-buffer-changes'.
548 (vector buffer-undo-list ; 0
549 (current-buffer) ; 1
550 ;; No need to use markers for the point and mark; if the
551 ;; undo got out of synch we're hosed anyway.
552 (point) ; 2
553 (mark t) ; 3
554 (c-region-is-active-p) ; 4
555 (buffer-modified-p))) ; 5
557 (defun c-tnt-chng-cleanup (keep saved-state)
558 ;; Used internally in `c-tentative-buffer-changes'.
560 (let ((saved-undo-list (elt saved-state 0)))
561 (if (eq buffer-undo-list saved-undo-list)
562 ;; No change was done after all.
563 (setq buffer-undo-list (cdr saved-undo-list))
565 (if keep
566 ;; Find and remove the undo boundary.
567 (let ((p buffer-undo-list))
568 (while (not (eq (cdr p) saved-undo-list))
569 (setq p (cdr p)))
570 (setcdr p (cdr saved-undo-list)))
572 ;; `primitive-undo' will remove the boundary.
573 (setq saved-undo-list (cdr saved-undo-list))
574 (let ((undo-in-progress t))
575 (while (not (eq (setq buffer-undo-list
576 (primitive-undo 1 buffer-undo-list))
577 saved-undo-list))))
579 (when (buffer-live-p (elt saved-state 1))
580 (set-buffer (elt saved-state 1))
581 (goto-char (elt saved-state 2))
582 (set-mark (elt saved-state 3))
583 (c-set-region-active (elt saved-state 4))
584 (and (not (elt saved-state 5))
585 (buffer-modified-p)
586 (set-buffer-modified-p nil)))))))
588 (defmacro c-forward-syntactic-ws (&optional limit)
589 "Forward skip over syntactic whitespace.
590 Syntactic whitespace is defined as whitespace characters, comments,
591 and preprocessor directives. However if point starts inside a comment
592 or preprocessor directive, the content of it is not treated as
593 whitespace.
595 LIMIT sets an upper limit of the forward movement, if specified. If
596 LIMIT or the end of the buffer is reached inside a comment or
597 preprocessor directive, the point will be left there.
599 Note that this function might do hidden buffer changes. See the
600 comment at the start of cc-engine.el for more info."
601 (if limit
602 `(save-restriction
603 (narrow-to-region (point-min) (or ,limit (point-max)))
604 (c-forward-sws))
605 '(c-forward-sws)))
607 (defmacro c-backward-syntactic-ws (&optional limit)
608 "Backward skip over syntactic whitespace.
609 Syntactic whitespace is defined as whitespace characters, comments,
610 and preprocessor directives. However if point starts inside a comment
611 or preprocessor directive, the content of it is not treated as
612 whitespace.
614 LIMIT sets a lower limit of the backward movement, if specified. If
615 LIMIT is reached inside a line comment or preprocessor directive then
616 the point is moved into it past the whitespace at the end.
618 Note that this function might do hidden buffer changes. See the
619 comment at the start of cc-engine.el for more info."
620 (if limit
621 `(save-restriction
622 (narrow-to-region (or ,limit (point-min)) (point-max))
623 (c-backward-sws))
624 '(c-backward-sws)))
626 (defmacro c-forward-sexp (&optional count)
627 "Move forward across COUNT balanced expressions.
628 A negative COUNT means move backward. Signal an error if the move
629 fails for any reason.
631 This is like `forward-sexp' except that it isn't interactive and does
632 not do any user friendly adjustments of the point and that it isn't
633 susceptible to user configurations such as disabling of signals in
634 certain situations."
635 (or count (setq count 1))
636 `(goto-char (scan-sexps (point) ,count)))
638 (defmacro c-backward-sexp (&optional count)
639 "See `c-forward-sexp' and reverse directions."
640 (or count (setq count 1))
641 `(c-forward-sexp ,(if (numberp count) (- count) `(- ,count))))
643 (defmacro c-safe-scan-lists (from count depth &optional limit)
644 "Like `scan-lists' but returns nil instead of signaling errors
645 for unbalanced parens.
647 A limit for the search may be given. FROM is assumed to be on the
648 right side of it."
649 (let ((res (if (featurep 'xemacs)
650 `(scan-lists ,from ,count ,depth nil t)
651 `(c-safe (scan-lists ,from ,count ,depth)))))
652 (if limit
653 `(save-restriction
654 (when ,limit
655 ,(if (numberp count)
656 (if (< count 0)
657 `(narrow-to-region ,limit (point-max))
658 `(narrow-to-region (point-min) ,limit))
659 `(if (< ,count 0)
660 (narrow-to-region ,limit (point-max))
661 (narrow-to-region (point-min) ,limit))))
662 ,res)
663 res)))
666 ;; Wrappers for common scan-lists cases, mainly because it's almost
667 ;; impossible to get a feel for how that function works.
669 (defmacro c-go-list-forward (&optional pos limit)
670 "Move forward across one balanced group of parentheses starting at POS or
671 point. Return POINT when we succeed, NIL when we fail. In the latter case,
672 leave point unmoved.
674 A LIMIT for the search may be given. The start position is assumed to be
675 before it."
676 `(let ((dest (c-safe-scan-lists ,(or pos `(point)) 1 0 ,limit)))
677 (when dest (goto-char dest) dest)))
679 (defmacro c-go-list-backward (&optional pos limit)
680 "Move backward across one balanced group of parentheses starting at POS or
681 point. Return POINT when we succeed, NIL when we fail. In the latter case,
682 leave point unmoved.
684 A LIMIT for the search may be given. The start position is assumed to be
685 after it."
686 `(let ((dest (c-safe-scan-lists ,(or pos `(point)) -1 0 ,limit)))
687 (when dest (goto-char dest) dest)))
689 (defmacro c-up-list-forward (&optional pos limit)
690 "Return the first position after the list sexp containing POS,
691 or nil if no such position exists. The point is used if POS is left out.
693 A limit for the search may be given. The start position is assumed to
694 be before it."
695 `(c-safe-scan-lists ,(or pos `(point)) 1 1 ,limit))
697 (defmacro c-up-list-backward (&optional pos limit)
698 "Return the position of the start of the list sexp containing POS,
699 or nil if no such position exists. The point is used if POS is left out.
701 A limit for the search may be given. The start position is assumed to
702 be after it."
703 `(c-safe-scan-lists ,(or pos `(point)) -1 1 ,limit))
705 (defmacro c-down-list-forward (&optional pos limit)
706 "Return the first position inside the first list sexp after POS,
707 or nil if no such position exists. The point is used if POS is left out.
709 A limit for the search may be given. The start position is assumed to
710 be before it."
711 `(c-safe-scan-lists ,(or pos `(point)) 1 -1 ,limit))
713 (defmacro c-down-list-backward (&optional pos limit)
714 "Return the last position inside the last list sexp before POS,
715 or nil if no such position exists. The point is used if POS is left out.
717 A limit for the search may be given. The start position is assumed to
718 be after it."
719 `(c-safe-scan-lists ,(or pos `(point)) -1 -1 ,limit))
721 (defmacro c-go-up-list-forward (&optional pos limit)
722 "Move the point to the first position after the list sexp containing POS,
723 or containing the point if POS is left out. Return t if such a
724 position exists, otherwise nil is returned and the point isn't moved.
726 A limit for the search may be given. The start position is assumed to
727 be before it."
728 `(let ((dest (c-up-list-forward ,pos ,limit)))
729 (when dest (goto-char dest) t)))
731 (defmacro c-go-up-list-backward (&optional pos limit)
732 "Move the point to the position of the start of the list sexp containing POS,
733 or containing the point if POS is left out. Return t if such a
734 position exists, otherwise nil is returned and the point isn't moved.
736 A limit for the search may be given. The start position is assumed to
737 be after it."
738 `(let ((dest (c-up-list-backward ,pos ,limit)))
739 (when dest (goto-char dest) t)))
741 (defmacro c-go-down-list-forward (&optional pos limit)
742 "Move the point to the first position inside the first list sexp after POS,
743 or before the point if POS is left out. Return t if such a position
744 exists, otherwise nil is returned and the point isn't moved.
746 A limit for the search may be given. The start position is assumed to
747 be before it."
748 `(let ((dest (c-down-list-forward ,pos ,limit)))
749 (when dest (goto-char dest) t)))
751 (defmacro c-go-down-list-backward (&optional pos limit)
752 "Move the point to the last position inside the last list sexp before POS,
753 or before the point if POS is left out. Return t if such a position
754 exists, otherwise nil is returned and the point isn't moved.
756 A limit for the search may be given. The start position is assumed to
757 be after it."
758 `(let ((dest (c-down-list-backward ,pos ,limit)))
759 (when dest (goto-char dest) t)))
761 (defmacro c-beginning-of-defun-1 ()
762 ;; Wrapper around beginning-of-defun.
764 ;; NOTE: This function should contain the only explicit use of
765 ;; beginning-of-defun in CC Mode. Eventually something better than
766 ;; b-o-d will be available and this should be the only place the
767 ;; code needs to change. Everything else should use
768 ;; (c-beginning-of-defun-1)
770 ;; This is really a bit too large to be a macro but that isn't a
771 ;; problem as long as it only is used in one place in
772 ;; `c-parse-state'.
774 `(progn
775 (if (and ,(fboundp 'buffer-syntactic-context-depth)
776 c-enable-xemacs-performance-kludge-p)
777 ,(when (fboundp 'buffer-syntactic-context-depth)
778 ;; XEmacs only. This can improve the performance of
779 ;; c-parse-state to between 3 and 60 times faster when
780 ;; braces are hung. It can also degrade performance by
781 ;; about as much when braces are not hung.
782 '(let (beginning-of-defun-function end-of-defun-function
783 pos)
784 (while (not pos)
785 (save-restriction
786 (widen)
787 (setq pos (c-safe-scan-lists
788 (point) -1 (buffer-syntactic-context-depth))))
789 (cond
790 ((bobp) (setq pos (point-min)))
791 ((not pos)
792 (let ((distance (skip-chars-backward "^{")))
793 ;; unbalanced parenthesis, while invalid C code,
794 ;; shouldn't cause an infloop! See unbal.c
795 (when (zerop distance)
796 ;; Punt!
797 (beginning-of-defun)
798 (setq pos (point)))))
799 ((= pos 0))
800 ((not (eq (char-after pos) ?{))
801 (goto-char pos)
802 (setq pos nil))
804 (goto-char pos)))
805 ;; Emacs, which doesn't have buffer-syntactic-context-depth
806 (let (beginning-of-defun-function end-of-defun-function)
807 (beginning-of-defun)))
808 ;; if defun-prompt-regexp is non-nil, b-o-d won't leave us at the
809 ;; open brace.
810 (and defun-prompt-regexp
811 (looking-at defun-prompt-regexp)
812 (goto-char (match-end 0)))))
815 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
816 ;; V i r t u a l S e m i c o l o n s
818 ;; In most CC Mode languages, statements are terminated explicitly by
819 ;; semicolons or closing braces. In some of the CC modes (currently AWK Mode
820 ;; and certain user-specified #define macros in C, C++, etc. (November 2008)),
821 ;; statements are (or can be) terminated by EOLs. Such a statement is said to
822 ;; be terminated by a "virtual semicolon" (VS). A statement terminated by an
823 ;; actual semicolon or brace is never considered to have a VS.
825 ;; The indentation engine (or whatever) tests for a VS at a specific position
826 ;; by invoking the macro `c-at-vsemi-p', which in its turn calls the mode
827 ;; specific function (if any) which is the value of the language variable
828 ;; `c-at-vsemi-p-fn'. This function should only use "low-level" features of
829 ;; CC Mode, i.e. features which won't trigger infinite recursion. ;-) The
830 ;; actual details of what constitutes a VS in a language are thus encapsulated
831 ;; in code specific to that language (e.g. cc-awk.el). `c-at-vsemi-p' returns
832 ;; non-nil if point (or the optional parameter POS) is at a VS, nil otherwise.
834 ;; The language specific function might well do extensive analysis of the
835 ;; source text, and may use a caching scheme to speed up repeated calls.
837 ;; The "virtual semicolon" lies just after the last non-ws token on the line.
838 ;; Like POINT, it is considered to lie between two characters. For example,
839 ;; at the place shown in the following AWK source line:
841 ;; kbyte = 1024 # 1000 if you're not picky
842 ;; ^
843 ;; |
844 ;; Virtual Semicolon
846 ;; In addition to `c-at-vsemi-p-fn', a mode may need to supply a function for
847 ;; `c-vsemi-status-unknown-p-fn'. The macro `c-vsemi-status-unknown-p' is a
848 ;; rather recondite kludge. It exists because the function
849 ;; `c-beginning-of-statement-1' sometimes tests for VSs as an optimization,
850 ;; but `c-at-vsemi-p' might well need to call `c-beginning-of-statement-1' in
851 ;; its calculations, thus potentially leading to infinite recursion.
853 ;; The macro `c-vsemi-status-unknown-p' resolves this problem; it may return
854 ;; non-nil at any time; returning nil is a guarantee that an immediate
855 ;; invocation of `c-at-vsemi-p' at point will NOT call
856 ;; `c-beginning-of-statement-1'. `c-vsemi-status-unknown-p' may not itself
857 ;; call `c-beginning-of-statement-1'.
859 ;; The macro `c-vsemi-status-unknown-p' will typically check the caching
860 ;; scheme used by the `c-at-vsemi-p-fn', hence the name - the status is
861 ;; "unknown" if there is no cache entry current for the line.
862 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
864 (defmacro c-at-vsemi-p (&optional pos)
865 ;; Is there a virtual semicolon (not a real one or a }) at POS (defaults to
866 ;; point)? Always returns nil for languages which don't have Virtual
867 ;; semicolons.
868 ;; This macro might do hidden buffer changes.
869 `(if c-at-vsemi-p-fn
870 (funcall c-at-vsemi-p-fn ,@(if pos `(,pos)))))
872 (defmacro c-vsemi-status-unknown-p ()
873 ;; Return NIL only if it can be guaranteed that an immediate
874 ;; (c-at-vsemi-p) will NOT call c-beginning-of-statement-1. Otherwise,
875 ;; return non-nil. (See comments above). The function invoked by this
876 ;; macro MUST NOT UNDER ANY CIRCUMSTANCES itself call
877 ;; c-beginning-of-statement-1.
878 ;; Languages which don't have EOL terminated statements always return NIL
879 ;; (they _know_ there's no vsemi ;-).
880 `(if c-vsemi-status-unknown-p-fn (funcall c-vsemi-status-unknown-p-fn)))
883 (defmacro c-benign-error (format &rest args)
884 ;; Formats an error message for the echo area and dings, i.e. like
885 ;; `error' but doesn't abort.
886 `(progn
887 (message ,format ,@args)
888 (ding)))
890 (defmacro c-with-syntax-table (table &rest code)
891 ;; Temporarily switches to the specified syntax table in a failsafe
892 ;; way to execute code.
893 ;; Maintainers' note: If TABLE is `c++-template-syntax-table', DON'T call
894 ;; any forms inside this that call `c-parse-state'. !!!!
895 `(let ((c-with-syntax-table-orig-table (syntax-table)))
896 (unwind-protect
897 (progn
898 (set-syntax-table ,table)
899 ,@code)
900 (set-syntax-table c-with-syntax-table-orig-table))))
901 (put 'c-with-syntax-table 'lisp-indent-function 1)
903 (defmacro c-skip-ws-forward (&optional limit)
904 "Skip over any whitespace following point.
905 This function skips over horizontal and vertical whitespace and line
906 continuations."
907 (if limit
908 `(let ((limit (or ,limit (point-max))))
909 (while (progn
910 ;; skip-syntax-* doesn't count \n as whitespace..
911 (skip-chars-forward " \t\n\r\f\v" limit)
912 (when (and (eq (char-after) ?\\)
913 (< (point) limit))
914 (forward-char)
915 (or (eolp)
916 (progn (backward-char) nil))))))
917 '(while (progn
918 (skip-chars-forward " \t\n\r\f\v")
919 (when (eq (char-after) ?\\)
920 (forward-char)
921 (or (eolp)
922 (progn (backward-char) nil)))))))
924 (defmacro c-skip-ws-backward (&optional limit)
925 "Skip over any whitespace preceding point.
926 This function skips over horizontal and vertical whitespace and line
927 continuations."
928 (if limit
929 `(let ((limit (or ,limit (point-min))))
930 (while (progn
931 ;; skip-syntax-* doesn't count \n as whitespace..
932 (skip-chars-backward " \t\n\r\f\v" limit)
933 (and (eolp)
934 (eq (char-before) ?\\)
935 (> (point) limit)))
936 (backward-char)))
937 '(while (progn
938 (skip-chars-backward " \t\n\r\f\v")
939 (and (eolp)
940 (eq (char-before) ?\\)))
941 (backward-char))))
943 (eval-and-compile
944 (defvar c-langs-are-parametric nil))
946 (defmacro c-major-mode-is (mode)
947 "Return non-nil if the current CC Mode major mode is MODE.
948 MODE is either a mode symbol or a list of mode symbols."
950 (if c-langs-are-parametric
951 ;; Inside a `c-lang-defconst'.
952 `(c-lang-major-mode-is ,mode)
954 (if (eq (car-safe mode) 'quote)
955 (let ((mode (eval mode)))
956 (if (listp mode)
957 `(memq c-buffer-is-cc-mode ',mode)
958 `(eq c-buffer-is-cc-mode ',mode)))
960 `(let ((mode ,mode))
961 (if (listp mode)
962 (memq c-buffer-is-cc-mode mode)
963 (eq c-buffer-is-cc-mode mode))))))
966 ;; Macros/functions to handle so-called "char properties", which are
967 ;; properties set on a single character and that never spread to any
968 ;; other characters.
970 (eval-and-compile
971 ;; Constant used at compile time to decide whether or not to use
972 ;; XEmacs extents. Check all the extent functions we'll use since
973 ;; some packages might add compatibility aliases for some of them in
974 ;; Emacs.
975 (defconst c-use-extents (and (cc-bytecomp-fboundp 'extent-at)
976 (cc-bytecomp-fboundp 'set-extent-property)
977 (cc-bytecomp-fboundp 'set-extent-properties)
978 (cc-bytecomp-fboundp 'make-extent)
979 (cc-bytecomp-fboundp 'extent-property)
980 (cc-bytecomp-fboundp 'delete-extent)
981 (cc-bytecomp-fboundp 'map-extents))))
983 (defconst c-<-as-paren-syntax '(4 . ?>))
984 (put 'c-<-as-paren-syntax 'syntax-table c-<-as-paren-syntax)
986 (defconst c->-as-paren-syntax '(5 . ?<))
987 (put 'c->-as-paren-syntax 'syntax-table c->-as-paren-syntax)
989 ;; `c-put-char-property' is complex enough in XEmacs and Emacs < 21 to
990 ;; make it a function.
991 (defalias 'c-put-char-property-fun
992 (cc-eval-when-compile
993 (cond (c-use-extents
994 ;; XEmacs.
995 (byte-compile
996 (lambda (pos property value)
997 (let ((ext (extent-at pos nil property)))
998 (if ext
999 (set-extent-property ext property value)
1000 (set-extent-properties (make-extent pos (1+ pos))
1001 (cons property
1002 (cons value
1003 '(start-open t
1004 end-open t)))))))))
1006 ((not (cc-bytecomp-boundp 'text-property-default-nonsticky))
1007 ;; In Emacs < 21 we have to mess with the `rear-nonsticky' property.
1008 (byte-compile
1009 (lambda (pos property value)
1010 (put-text-property pos (1+ pos) property value)
1011 (let ((prop (get-text-property pos 'rear-nonsticky)))
1012 (or (memq property prop)
1013 (put-text-property pos (1+ pos)
1014 'rear-nonsticky
1015 (cons property prop)))))))
1016 ;; This won't be used for anything.
1017 (t 'ignore))))
1018 (cc-bytecomp-defun c-put-char-property-fun) ; Make it known below.
1020 (defmacro c-put-char-property (pos property value)
1021 ;; Put the given property with the given value on the character at
1022 ;; POS and make it front and rear nonsticky, or start and end open
1023 ;; in XEmacs vocabulary. If the character already has the given
1024 ;; property then the value is replaced, and the behavior is
1025 ;; undefined if that property has been put by some other function.
1026 ;; PROPERTY is assumed to be constant.
1028 ;; If there's a `text-property-default-nonsticky' variable (Emacs
1029 ;; 21) then it's assumed that the property is present on it.
1031 ;; This macro does a hidden buffer change.
1032 (setq property (eval property))
1033 (if (or c-use-extents
1034 (not (cc-bytecomp-boundp 'text-property-default-nonsticky)))
1035 ;; XEmacs and Emacs < 21.
1036 `(c-put-char-property-fun ,pos ',property ,value)
1037 ;; In Emacs 21 we got the `rear-nonsticky' property covered
1038 ;; by `text-property-default-nonsticky'.
1039 `(let ((-pos- ,pos))
1040 (put-text-property -pos- (1+ -pos-) ',property ,value))))
1042 (defmacro c-get-char-property (pos property)
1043 ;; Get the value of the given property on the character at POS if
1044 ;; it's been put there by `c-put-char-property'. PROPERTY is
1045 ;; assumed to be constant.
1046 (setq property (eval property))
1047 (if c-use-extents
1048 ;; XEmacs.
1049 `(let ((ext (extent-at ,pos nil ',property)))
1050 (if ext (extent-property ext ',property)))
1051 ;; Emacs.
1052 `(get-text-property ,pos ',property)))
1054 ;; `c-clear-char-property' is complex enough in Emacs < 21 to make it
1055 ;; a function, since we have to mess with the `rear-nonsticky' property.
1056 (defalias 'c-clear-char-property-fun
1057 (cc-eval-when-compile
1058 (unless (or c-use-extents
1059 (cc-bytecomp-boundp 'text-property-default-nonsticky))
1060 (byte-compile
1061 (lambda (pos property)
1062 (when (get-text-property pos property)
1063 (remove-text-properties pos (1+ pos) (list property nil))
1064 (put-text-property pos (1+ pos)
1065 'rear-nonsticky
1066 (delq property (get-text-property
1067 pos 'rear-nonsticky)))))))))
1068 (cc-bytecomp-defun c-clear-char-property-fun) ; Make it known below.
1070 (defmacro c-clear-char-property (pos property)
1071 ;; Remove the given property on the character at POS if it's been put
1072 ;; there by `c-put-char-property'. PROPERTY is assumed to be
1073 ;; constant.
1075 ;; This macro does a hidden buffer change.
1076 (setq property (eval property))
1077 (cond (c-use-extents
1078 ;; XEmacs.
1079 `(let ((ext (extent-at ,pos nil ',property)))
1080 (if ext (delete-extent ext))))
1081 ((cc-bytecomp-boundp 'text-property-default-nonsticky)
1082 ;; In Emacs 21 we got the `rear-nonsticky' property covered
1083 ;; by `text-property-default-nonsticky'.
1084 `(let ((pos ,pos))
1085 (remove-text-properties pos (1+ pos)
1086 '(,property nil))))
1088 ;; Emacs < 21.
1089 `(c-clear-char-property-fun ,pos ',property))))
1091 (defmacro c-clear-char-properties (from to property)
1092 ;; Remove all the occurrences of the given property in the given
1093 ;; region that has been put with `c-put-char-property'. PROPERTY is
1094 ;; assumed to be constant.
1096 ;; Note that this function does not clean up the property from the
1097 ;; lists of the `rear-nonsticky' properties in the region, if such
1098 ;; are used. Thus it should not be used for common properties like
1099 ;; `syntax-table'.
1101 ;; This macro does hidden buffer changes.
1102 (setq property (eval property))
1103 (if c-use-extents
1104 ;; XEmacs.
1105 `(map-extents (lambda (ext ignored)
1106 (delete-extent ext))
1107 nil ,from ,to nil nil ',property)
1108 ;; Emacs.
1109 `(remove-text-properties ,from ,to '(,property nil))))
1111 (defmacro c-search-forward-char-property (property value &optional limit)
1112 "Search forward for a text-property PROPERTY having value VALUE.
1113 LIMIT bounds the search. The comparison is done with `equal'.
1115 Leave point just after the character, and set the match data on
1116 this character, and return point. If VALUE isn't found, Return
1117 nil; point is then left undefined."
1118 `(let ((place (point)))
1119 (while
1120 (and
1121 (< place ,(or limit '(point-max)))
1122 (not (equal (c-get-char-property place ,property) ,value)))
1123 (setq place (c-next-single-property-change
1124 place ,property nil ,(or limit '(point-max)))))
1125 (when (< place ,(or limit '(point-max)))
1126 (goto-char place)
1127 (search-forward-regexp ".") ; to set the match-data.
1128 (point))))
1130 (defmacro c-search-backward-char-property (property value &optional limit)
1131 "Search backward for a text-property PROPERTY having value VALUE.
1132 LIMIT bounds the search. The comparison is done with `equal'.
1134 Leave point just before the character, set the match data on this
1135 character, and return point. If VALUE isn't found, Return nil;
1136 point is then left undefined."
1137 `(let ((place (point)))
1138 (while
1139 (and
1140 (> place ,(or limit '(point-min)))
1141 (not (equal (c-get-char-property (1- place) ,property) ,value)))
1142 (setq place (,(if (and c-use-extents
1143 (fboundp 'previous-single-char-property-change))
1144 ;; XEmacs > 2005-01-25.
1145 'previous-single-char-property-change
1146 ;; Emacs and earlier XEmacs.
1147 'previous-single-property-change)
1148 place ,property nil ,(or limit '(point-min)))))
1149 (when (> place ,(or limit '(point-min)))
1150 (goto-char place)
1151 (search-backward-regexp ".") ; to set the match-data.
1152 (point))))
1154 (defun c-clear-char-property-with-value-function (from to property value)
1155 "Remove all text-properties PROPERTY from the region (FROM, TO)
1156 which have the value VALUE, as tested by `equal'. These
1157 properties are assumed to be over individual characters, having
1158 been put there by c-put-char-property. POINT remains unchanged."
1159 (let ((place from) end-place)
1160 (while ; loop round occurrences of (PROPERTY VALUE)
1161 (progn
1162 (while ; loop round changes in PROPERTY till we find VALUE
1163 (and
1164 (< place to)
1165 (not (equal (get-text-property place property) value)))
1166 (setq place (c-next-single-property-change place property nil to)))
1167 (< place to))
1168 (setq end-place (c-next-single-property-change place property nil to))
1169 (remove-text-properties place end-place (cons property nil))
1170 ;; Do we have to do anything with stickiness here?
1171 (setq place end-place))))
1173 (defmacro c-clear-char-property-with-value (from to property value)
1174 "Remove all text-properties PROPERTY from the region [FROM, TO)
1175 which have the value VALUE, as tested by `equal'. These
1176 properties are assumed to be over individual characters, having
1177 been put there by c-put-char-property. POINT remains unchanged."
1178 (if c-use-extents
1179 ;; XEmacs
1180 `(let ((-property- ,property))
1181 (map-extents (lambda (ext val)
1182 (if (equal (extent-property ext -property-) val)
1183 (delete-extent ext)))
1184 nil ,from ,to ,value nil -property-))
1185 ;; GNU Emacs
1186 `(c-clear-char-property-with-value-function ,from ,to ,property ,value)))
1188 (defmacro c-search-forward-char-property-with-value-on-char
1189 (property value char &optional limit)
1190 "Search forward for a text-property PROPERTY having value VALUE on a
1191 character with value CHAR.
1192 LIMIT bounds the search. The value comparison is done with `equal'.
1193 PROPERTY must be a constant.
1195 Leave point just after the character, and set the match data on
1196 this character, and return point. If the search fails, return
1197 nil; point is then left undefined."
1198 `(let ((char-skip (concat "^" (char-to-string ,char)))
1199 (-limit- ,limit)
1200 (-value- ,value))
1201 (while
1202 (and
1203 (progn (skip-chars-forward char-skip -limit-)
1204 (< (point) -limit-))
1205 (not (equal (c-get-char-property (point) ,property) -value-)))
1206 (forward-char))
1207 (when (< (point) -limit-)
1208 (search-forward-regexp ".") ; to set the match-data.
1209 (point))))
1211 (defun c-clear-char-property-with-value-on-char-function (from to property
1212 value char)
1213 "Remove all text-properties PROPERTY with value VALUE on
1214 characters with value CHAR from the region [FROM, TO), as tested
1215 by `equal'. These properties are assumed to be over individual
1216 characters, having been put there by c-put-char-property. POINT
1217 remains unchanged."
1218 (let ((place from)
1220 (while ; loop round occurrences of (PROPERTY VALUE)
1221 (progn
1222 (while ; loop round changes in PROPERTY till we find VALUE
1223 (and
1224 (< place to)
1225 (not (equal (get-text-property place property) value)))
1226 (setq place (c-next-single-property-change place property nil to)))
1227 (< place to))
1228 (if (eq (char-after place) char)
1229 (remove-text-properties place (1+ place) (cons property nil)))
1230 ;; Do we have to do anything with stickiness here?
1231 (setq place (1+ place)))))
1233 (defmacro c-clear-char-property-with-value-on-char (from to property value char)
1234 "Remove all text-properties PROPERTY with value VALUE on
1235 characters with value CHAR from the region [FROM, TO), as tested
1236 by `equal'. These properties are assumed to be over individual
1237 characters, having been put there by c-put-char-property. POINT
1238 remains unchanged."
1239 (if c-use-extents
1240 ;; XEmacs
1241 `(let ((-property- ,property)
1242 (-char- ,char))
1243 (map-extents (lambda (ext val)
1244 (if (and (equal (extent-property ext -property-) val)
1245 (eq (char-after
1246 (extent-start-position ext))
1247 -char-))
1248 (delete-extent ext)))
1249 nil ,from ,to ,value nil -property-))
1250 ;; Gnu Emacs
1251 `(c-clear-char-property-with-value-on-char-function ,from ,to ,property
1252 ,value ,char)))
1254 (defmacro c-put-char-properties-on-char (from to property value char)
1255 ;; This needs to be a macro because `property' passed to
1256 ;; `c-put-char-property' must be a constant.
1257 "Put the text property PROPERTY with value VALUE on characters
1258 with value CHAR in the region [FROM to)."
1259 `(let ((skip-string (concat "^" (list ,char)))
1260 (-to- ,to))
1261 (save-excursion
1262 (goto-char ,from)
1263 (while (progn (skip-chars-forward skip-string -to-)
1264 (< (point) -to-))
1265 (c-put-char-property (point) ,property ,value)
1266 (forward-char)))))
1268 ;; Macros to put overlays (Emacs) or extents (XEmacs) on buffer text.
1269 ;; For our purposes, these are characterized by being possible to
1270 ;; remove again without affecting the other text properties in the
1271 ;; buffer that got overridden when they were put.
1273 (defmacro c-put-overlay (from to property value)
1274 ;; Put an overlay/extent covering the given range in the current
1275 ;; buffer. It's currently undefined whether it's front/end sticky
1276 ;; or not. The overlay/extent object is returned.
1277 (if (cc-bytecomp-fboundp 'make-overlay)
1278 ;; Emacs.
1279 `(let ((ol (make-overlay ,from ,to)))
1280 (overlay-put ol ,property ,value)
1282 ;; XEmacs.
1283 `(let ((ext (make-extent ,from ,to)))
1284 (set-extent-property ext ,property ,value)
1285 ext)))
1287 (defmacro c-delete-overlay (overlay)
1288 ;; Deletes an overlay/extent object previously retrieved using
1289 ;; `c-put-overlay'.
1290 (if (cc-bytecomp-fboundp 'make-overlay)
1291 ;; Emacs.
1292 `(delete-overlay ,overlay)
1293 ;; XEmacs.
1294 `(delete-extent ,overlay)))
1297 ;; Make edebug understand the macros.
1298 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
1299 ; '(progn
1300 (def-edebug-spec cc-eval-when-compile (&rest def-form))
1301 (def-edebug-spec c-point t)
1302 (def-edebug-spec c-set-region-active t)
1303 (def-edebug-spec c-set-keymap-parent t)
1304 (def-edebug-spec c-safe t)
1305 (def-edebug-spec c-save-buffer-state let*)
1306 (def-edebug-spec c-tentative-buffer-changes t)
1307 (def-edebug-spec c-forward-syntactic-ws t)
1308 (def-edebug-spec c-backward-syntactic-ws t)
1309 (def-edebug-spec c-forward-sexp t)
1310 (def-edebug-spec c-backward-sexp t)
1311 (def-edebug-spec c-up-list-forward t)
1312 (def-edebug-spec c-up-list-backward t)
1313 (def-edebug-spec c-down-list-forward t)
1314 (def-edebug-spec c-down-list-backward t)
1315 (def-edebug-spec c-add-syntax t)
1316 (def-edebug-spec c-add-class-syntax t)
1317 (def-edebug-spec c-benign-error t)
1318 (def-edebug-spec c-with-syntax-table t)
1319 (def-edebug-spec c-skip-ws-forward t)
1320 (def-edebug-spec c-skip-ws-backward t)
1321 (def-edebug-spec c-major-mode-is t)
1322 (def-edebug-spec c-put-char-property t)
1323 (def-edebug-spec c-get-char-property t)
1324 (def-edebug-spec c-clear-char-property t)
1325 (def-edebug-spec c-clear-char-property-with-value-on-char t)
1326 (def-edebug-spec c-put-char-properties-on-char t)
1327 (def-edebug-spec c-clear-char-properties t)
1328 (def-edebug-spec c-put-overlay t)
1329 (def-edebug-spec c-delete-overlay t)
1330 (def-edebug-spec c-self-bind-state-cache t);))
1333 ;;; Functions.
1335 ;; Note: All these after the macros, to be on safe side in avoiding
1336 ;; bugs where macros are defined too late. These bugs often only show
1337 ;; when the files are compiled in a certain order within the same
1338 ;; session.
1340 (defsubst c-end-of-defun-1 ()
1341 ;; Replacement for end-of-defun that use c-beginning-of-defun-1.
1342 (let ((start (point)))
1343 ;; Skip forward into the next defun block. Don't bother to avoid
1344 ;; comments, literals etc, since beginning-of-defun doesn't do that
1345 ;; anyway.
1346 (skip-chars-forward "^}")
1347 (c-beginning-of-defun-1)
1348 (if (eq (char-after) ?{)
1349 (c-forward-sexp))
1350 (if (< (point) start)
1351 (goto-char (point-max)))))
1353 (defmacro c-mark-<-as-paren (pos)
1354 ;; Mark the "<" character at POS as a template opener using the
1355 ;; `syntax-table' property either directly (XEmacs) or via a `category'
1356 ;; property (GNU Emacs).
1358 ;; This function does a hidden buffer change. Note that we use
1359 ;; indirection through the `category' text property. This allows us to
1360 ;; toggle the property in all template brackets simultaneously and
1361 ;; cheaply. We use this, for instance, in `c-parse-state'.
1362 (if c-use-category
1363 `(c-put-char-property ,pos 'category 'c-<-as-paren-syntax)
1364 `(c-put-char-property ,pos 'syntax-table c-<-as-paren-syntax)))
1367 (defmacro c-mark->-as-paren (pos)
1368 ;; Mark the ">" character at POS as an sexp list closer using the
1369 ;; `syntax-table' property either directly (XEmacs) or via a `category'
1370 ;; property (GNU Emacs).
1372 ;; This function does a hidden buffer change. Note that we use
1373 ;; indirection through the `category' text property. This allows us to
1374 ;; toggle the property in all template brackets simultaneously and
1375 ;; cheaply. We use this, for instance, in `c-parse-state'.
1376 (if c-use-category
1377 `(c-put-char-property ,pos 'category 'c->-as-paren-syntax)
1378 `(c-put-char-property ,pos 'syntax-table c->-as-paren-syntax)))
1380 (defmacro c-unmark-<->-as-paren (pos)
1381 ;; Unmark the "<" or "<" character at POS as an sexp list opener using the
1382 ;; `syntax-table' property either directly or indirectly through a
1383 ;; `category' text property.
1385 ;; This function does a hidden buffer change. Note that we try to use
1386 ;; indirection through the `category' text property. This allows us to
1387 ;; toggle the property in all template brackets simultaneously and
1388 ;; cheaply. We use this, for instance, in `c-parse-state'.
1389 `(c-clear-char-property ,pos ,(if c-use-category ''category ''syntax-table)))
1391 (defsubst c-suppress-<->-as-parens ()
1392 ;; Suppress the syntactic effect of all marked < and > as parens. Note
1393 ;; that this effect is NOT buffer local. You should probably not use
1394 ;; this directly, but only through the macro
1395 ;; `c-with-<->-as-parens-suppressed'
1396 (put 'c-<-as-paren-syntax 'syntax-table nil)
1397 (put 'c->-as-paren-syntax 'syntax-table nil))
1399 (defsubst c-restore-<->-as-parens ()
1400 ;; Restore the syntactic effect of all marked <s and >s as parens. This
1401 ;; has no effect on unmarked <s and >s
1402 (put 'c-<-as-paren-syntax 'syntax-table c-<-as-paren-syntax)
1403 (put 'c->-as-paren-syntax 'syntax-table c->-as-paren-syntax))
1405 (defmacro c-with-<->-as-parens-suppressed (&rest forms)
1406 ;; Like progn, except that the paren property is suppressed on all
1407 ;; template brackets whilst they are running. This macro does a hidden
1408 ;; buffer change.
1409 `(unwind-protect
1410 (progn
1411 (c-suppress-<->-as-parens)
1412 ,@forms)
1413 (c-restore-<->-as-parens)))
1415 ;;;;;;;;;;;;;;;
1417 (defmacro c-self-bind-state-cache (&rest forms)
1418 ;; Bind the state cache to itself and execute the FORMS. Return the result
1419 ;; of the last FORM executed. It is assumed that no buffer changes will
1420 ;; happen in FORMS, and no hidden buffer changes which could affect the
1421 ;; parsing will be made by FORMS.
1422 `(let* ((c-state-cache (copy-tree c-state-cache))
1423 (c-state-cache-good-pos c-state-cache-good-pos)
1424 ;(c-state-nonlit-pos-cache (copy-tree c-state-nonlit-pos-cache))
1425 ;(c-state-nonlit-pos-cache-limit c-state-nonlit-pos-cache-limit)
1426 ;(c-state-semi-nonlit-pos-cache (copy-tree c-state-semi-nonlit-pos-cache))
1427 ;(c-state-semi-nonlit-pos-cache-limit c-state-semi-nonlit-pos-cache)
1428 (c-state-brace-pair-desert (copy-tree c-state-brace-pair-desert))
1429 (c-state-point-min c-state-point-min)
1430 (c-state-point-min-lit-type c-state-point-min-lit-type)
1431 (c-state-point-min-lit-start c-state-point-min-lit-start)
1432 (c-state-min-scan-pos c-state-min-scan-pos)
1433 (c-state-old-cpp-beg-marker (if (markerp c-state-old-cpp-beg-marker)
1434 (copy-marker c-state-old-cpp-beg-marker)
1435 c-state-old-cpp-beg-marker))
1436 (c-state-old-cpp-beg (if (markerp c-state-old-cpp-beg)
1437 c-state-old-cpp-beg-marker
1438 c-state-old-cpp-beg))
1439 (c-state-old-cpp-end-marker (if (markerp c-state-old-cpp-end-marker)
1440 (copy-marker c-state-old-cpp-end-marker)
1441 c-state-old-cpp-end-marker))
1442 (c-state-old-cpp-end (if (markerp c-state-old-cpp-end)
1443 c-state-old-cpp-end-marker
1444 c-state-old-cpp-end))
1445 (c-parse-state-state c-parse-state-state))
1446 (prog1
1447 (progn ,@forms)
1448 (if (markerp c-state-old-cpp-beg-marker)
1449 (move-marker c-state-old-cpp-beg-marker nil))
1450 (if (markerp c-state-old-cpp-end-marker)
1451 (move-marker c-state-old-cpp-end-marker nil)))))
1453 ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
1454 ;; The following macros are to be used only in `c-parse-state' and its
1455 ;; subroutines. Their main purpose is to simplify the handling of C++/Java
1456 ;; template delimiters and CPP macros. In GNU Emacs, this is done slickly by
1457 ;; the judicious use of 'category properties. These don't exist in XEmacs.
1459 ;; Note: in the following macros, there is no special handling for parentheses
1460 ;; inside CPP constructs. That is because CPPs are always syntactically
1461 ;; balanced, thanks to `c-neutralize-CPP-line' in cc-mode.el.
1462 (defmacro c-sc-scan-lists-no-category+1+1 (from)
1463 ;; Do a (scan-lists FROM 1 1). Any finishing position which either (i) is
1464 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1465 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1466 `(let ((here (point))
1467 (pos (scan-lists ,from 1 1)))
1468 (while (eq (char-before pos) ?>)
1469 (setq pos (scan-lists pos 1 1)))
1470 pos))
1472 (defmacro c-sc-scan-lists-no-category+1-1 (from)
1473 ;; Do a (scan-lists FROM 1 -1). Any finishing position which either (i) is
1474 ;; determined by an angle bracket; or (ii) is inside a macro whose start
1475 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1476 `(let ((here (point))
1477 (pos (scan-lists ,from 1 -1)))
1478 (while (eq (char-before pos) ?<)
1479 (setq pos (scan-lists pos 1 1))
1480 (setq pos (scan-lists pos 1 -1)))
1481 pos))
1483 (defmacro c-sc-scan-lists-no-category-1+1 (from)
1484 ;; Do a (scan-lists FROM -1 1). Any finishing position which either (i) is
1485 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1486 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1487 `(let ((here (point))
1488 (pos (scan-lists ,from -1 1)))
1489 (while (eq (char-after pos) ?<)
1490 (setq pos (scan-lists pos -1 1)))
1491 pos))
1493 (defmacro c-sc-scan-lists-no-category-1-1 (from)
1494 ;; Do a (scan-lists FROM -1 -1). Any finishing position which either (i) is
1495 ;; determined by and angle bracket; or (ii) is inside a macro whose start
1496 ;; isn't POINT-MACRO-START doesn't count as a finishing position.
1497 `(let ((here (point))
1498 (pos (scan-lists ,from -1 -1)))
1499 (while (eq (char-after pos) ?>)
1500 (setq pos (scan-lists pos -1 1))
1501 (setq pos (scan-lists pos -1 -1)))
1502 pos))
1504 (defmacro c-sc-scan-lists (from count depth)
1505 (if c-use-category
1506 `(scan-lists ,from ,count ,depth)
1507 (cond
1508 ((and (eq count 1) (eq depth 1))
1509 `(c-sc-scan-lists-no-category+1+1 ,from))
1510 ((and (eq count 1) (eq depth -1))
1511 `(c-sc-scan-lists-no-category+1-1 ,from))
1512 ((and (eq count -1) (eq depth 1))
1513 `(c-sc-scan-lists-no-category-1+1 ,from))
1514 ((and (eq count -1) (eq depth -1))
1515 `(c-sc-scan-lists-no-category-1-1 ,from))
1516 (t (error "Invalid parameter(s) to c-sc-scan-lists")))))
1519 (defun c-sc-parse-partial-sexp-no-category (from to targetdepth stopbefore
1520 oldstate)
1521 ;; Do a parse-partial-sexp using the supplied arguments, disregarding
1522 ;; template/generic delimiters < > and disregarding macros other than the
1523 ;; one at POINT-MACRO-START.
1525 ;; NOTE that STOPBEFORE must be nil. TARGETDEPTH should be one less than
1526 ;; the depth in OLDSTATE. This function is thus a SPECIAL PURPOSE variation
1527 ;; on parse-partial-sexp, designed for calling from
1528 ;; `c-remove-stale-state-cache'.
1530 ;; Any finishing position which is determined by an angle bracket delimiter
1531 ;; doesn't count as a finishing position.
1533 ;; Note there is no special handling of CPP constructs here, since these are
1534 ;; always syntactically balanced (thanks to `c-neutralize-CPP-line').
1535 (let ((state
1536 (parse-partial-sexp from to targetdepth stopbefore oldstate)))
1537 (while
1538 (and (< (point) to)
1539 ;; We must have hit targetdepth.
1540 (or (eq (char-before) ?<)
1541 (eq (char-before) ?>)))
1542 (setcar state
1543 (if (memq (char-before) '(?> ?\) ?\} ?\]))
1544 (1+ (car state))
1545 (1- (car state))))
1546 (setq state
1547 (parse-partial-sexp (point) to targetdepth stopbefore oldstate)))
1548 state))
1550 (defmacro c-sc-parse-partial-sexp (from to &optional targetdepth stopbefore
1551 oldstate)
1552 (if c-use-category
1553 `(parse-partial-sexp ,from ,to ,targetdepth ,stopbefore ,oldstate)
1554 `(c-sc-parse-partial-sexp-no-category ,from ,to ,targetdepth ,stopbefore
1555 ,oldstate)))
1558 (defvar c-emacs-features)
1560 (defmacro c-looking-at-non-alphnumspace ()
1561 "Are we looking at a character which isn't alphanumeric or space?"
1562 (if (memq 'gen-comment-delim c-emacs-features)
1563 `(looking-at
1564 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\|\\s!\\)")
1565 `(or (looking-at
1566 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\)"
1567 (let ((prop (c-get-char-property (point) 'syntax-table)))
1568 (eq prop '(14))))))) ; '(14) is generic comment delimiter.
1571 (defsubst c-intersect-lists (list alist)
1572 ;; return the element of ALIST that matches the first element found
1573 ;; in LIST. Uses assq.
1574 (let (match)
1575 (while (and list
1576 (not (setq match (assq (car list) alist))))
1577 (setq list (cdr list)))
1578 match))
1580 (defsubst c-lookup-lists (list alist1 alist2)
1581 ;; first, find the first entry from LIST that is present in ALIST1,
1582 ;; then find the entry in ALIST2 for that entry.
1583 (assq (car (c-intersect-lists list alist1)) alist2))
1585 (defsubst c-langelem-sym (langelem)
1586 "Return the syntactic symbol in LANGELEM.
1588 LANGELEM is either a cons cell on the \"old\" form given as the first
1589 argument to lineup functions or a syntactic element on the \"new\"
1590 form as used in `c-syntactic-element'."
1591 (car langelem))
1593 (defsubst c-langelem-pos (langelem)
1594 "Return the anchor position in LANGELEM, or nil if there is none.
1596 LANGELEM is either a cons cell on the \"old\" form given as the first
1597 argument to lineup functions or a syntactic element on the \"new\"
1598 form as used in `c-syntactic-element'."
1599 (if (consp (cdr langelem))
1600 (car-safe (cdr langelem))
1601 (cdr langelem)))
1603 (defun c-langelem-col (langelem &optional preserve-point)
1604 "Return the column of the anchor position in LANGELEM.
1605 Also move the point to that position unless PRESERVE-POINT is non-nil.
1607 LANGELEM is either a cons cell on the \"old\" form given as the first
1608 argument to lineup functions or a syntactic element on the \"new\"
1609 form as used in `c-syntactic-element'."
1610 (let ((pos (c-langelem-pos langelem))
1611 (here (point)))
1612 (if pos
1613 (progn
1614 (goto-char pos)
1615 (prog1 (current-column)
1616 (if preserve-point
1617 (goto-char here))))
1618 0)))
1620 (defsubst c-langelem-2nd-pos (langelem)
1621 "Return the secondary position in LANGELEM, or nil if there is none.
1623 LANGELEM is typically a syntactic element on the \"new\" form as used
1624 in `c-syntactic-element'. It may also be a cons cell as passed in the
1625 first argument to lineup functions, but then the returned value always
1626 will be nil."
1627 (car-safe (cdr-safe (cdr-safe langelem))))
1629 (defsubst c-keep-region-active ()
1630 ;; Do whatever is necessary to keep the region active in XEmacs.
1631 ;; This is not needed for Emacs.
1632 (and (boundp 'zmacs-region-stays)
1633 (setq zmacs-region-stays t)))
1635 (put 'c-mode 'c-mode-prefix "c-")
1636 (put 'c++-mode 'c-mode-prefix "c++-")
1637 (put 'objc-mode 'c-mode-prefix "objc-")
1638 (put 'java-mode 'c-mode-prefix "java-")
1639 (put 'idl-mode 'c-mode-prefix "idl-")
1640 (put 'pike-mode 'c-mode-prefix "pike-")
1641 (put 'awk-mode 'c-mode-prefix "awk-")
1643 (defsubst c-mode-symbol (suffix)
1644 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1645 the corresponding symbol."
1646 (or c-buffer-is-cc-mode
1647 (error "Not inside a CC Mode based mode"))
1648 (let ((mode-prefix (get c-buffer-is-cc-mode 'c-mode-prefix)))
1649 (or mode-prefix
1650 (error "%S has no mode prefix known to `c-mode-symbol'"
1651 c-buffer-is-cc-mode))
1652 (intern (concat mode-prefix suffix))))
1654 (defsubst c-mode-var (suffix)
1655 "Prefix the current mode prefix (e.g. \"c-\") to SUFFIX and return
1656 the value of the variable with that name."
1657 (symbol-value (c-mode-symbol suffix)))
1659 (defsubst c-got-face-at (pos faces)
1660 "Return non-nil if position POS in the current buffer has any of the
1661 faces in the list FACES."
1662 (let ((pos-faces (get-text-property pos 'face)))
1663 (if (consp pos-faces)
1664 (progn
1665 (while (and pos-faces
1666 (not (memq (car pos-faces) faces)))
1667 (setq pos-faces (cdr pos-faces)))
1668 pos-faces)
1669 (memq pos-faces faces))))
1671 (defsubst c-face-name-p (facename)
1672 ;; Return t if FACENAME is the name of a face. This method is
1673 ;; necessary since facep in XEmacs only returns t for the actual
1674 ;; face objects (while it's only their names that are used just
1675 ;; about anywhere else) without providing a predicate that tests
1676 ;; face names.
1677 (memq facename (face-list)))
1679 (defun c-concat-separated (list separator)
1680 "Like `concat' on LIST, but separate each element with SEPARATOR.
1681 Notably, null elements in LIST are ignored."
1682 (mapconcat 'identity (delete nil (append list nil)) separator))
1684 (defun c-make-keywords-re (adorn list &optional mode)
1685 "Make a regexp that matches all the strings the list.
1686 Duplicates and nil elements in the list are removed. The
1687 resulting regexp may contain zero or more submatch expressions.
1689 If ADORN is t there will be at least one submatch and the first
1690 surrounds the matched alternative, and the regexp will also not match
1691 a prefix of any identifier. Adorned regexps cannot be appended. The
1692 language variable `c-nonsymbol-key' is used to make the adornment.
1694 A value `appendable' for ADORN is like above, but all alternatives in
1695 the list that end with a word constituent char will have \\> appended
1696 instead, so that the regexp remains appendable. Note that this
1697 variant doesn't always guarantee that an identifier prefix isn't
1698 matched since the symbol constituent `_' is normally considered a
1699 nonword token by \\>.
1701 The optional MODE specifies the language to get `c-nonsymbol-key' from
1702 when it's needed. The default is the current language taken from
1703 `c-buffer-is-cc-mode'."
1705 (setq list (delete nil (delete-dups list)))
1706 (if list
1707 (let (re)
1709 (if (eq adorn 'appendable)
1710 ;; This is kludgy but it works: Search for a string that
1711 ;; doesn't occur in any word in LIST. Append it to all
1712 ;; the alternatives where we want to add \>. Run through
1713 ;; `regexp-opt' and then replace it with \>.
1714 (let ((unique "") pos)
1715 (while (let (found)
1716 (setq unique (concat unique "@")
1717 pos list)
1718 (while (and pos
1719 (if (string-match unique (car pos))
1720 (progn (setq found t)
1721 nil)
1723 (setq pos (cdr pos)))
1724 found))
1725 (setq pos list)
1726 (while pos
1727 (if (string-match "\\w\\'" (car pos))
1728 (setcar pos (concat (car pos) unique)))
1729 (setq pos (cdr pos)))
1730 (setq re (regexp-opt list))
1731 (setq pos 0)
1732 (while (string-match unique re pos)
1733 (setq pos (+ (match-beginning 0) 2)
1734 re (replace-match "\\>" t t re))))
1736 (setq re (regexp-opt list)))
1738 ;; Emacs 20 and XEmacs (all versions so far) has a buggy
1739 ;; regexp-opt that doesn't always cope with strings containing
1740 ;; newlines. This kludge doesn't handle shy parens correctly
1741 ;; so we can't advice regexp-opt directly with it.
1742 (let (fail-list)
1743 (while list
1744 (and (string-match "\n" (car list)) ; To speed it up a little.
1745 (not (string-match (concat "\\`\\(" re "\\)\\'")
1746 (car list)))
1747 (setq fail-list (cons (car list) fail-list)))
1748 (setq list (cdr list)))
1749 (when fail-list
1750 (setq re (concat re
1751 "\\|"
1752 (mapconcat
1753 (if (eq adorn 'appendable)
1754 (lambda (str)
1755 (if (string-match "\\w\\'" str)
1756 (concat (regexp-quote str)
1757 "\\>")
1758 (regexp-quote str)))
1759 'regexp-quote)
1760 (sort fail-list
1761 (lambda (a b)
1762 (> (length a) (length b))))
1763 "\\|")))))
1765 ;; Add our own grouping parenthesis around re instead of
1766 ;; passing adorn to `regexp-opt', since in XEmacs it makes the
1767 ;; top level grouping "shy".
1768 (cond ((eq adorn 'appendable)
1769 (concat "\\(" re "\\)"))
1770 (adorn
1771 (concat "\\(" re "\\)"
1772 "\\("
1773 (c-get-lang-constant 'c-nonsymbol-key nil mode)
1774 "\\|$\\)"))
1776 re)))
1778 ;; Produce a regexp that matches nothing.
1779 (if adorn
1780 "\\(\\<\\>\\)"
1781 "\\<\\>")))
1783 (put 'c-make-keywords-re 'lisp-indent-function 1)
1785 (defun c-make-bare-char-alt (chars &optional inverted)
1786 "Make a character alternative string from the list of characters CHARS.
1787 The returned string is of the type that can be used with
1788 `skip-chars-forward' and `skip-chars-backward'. If INVERTED is
1789 non-nil, a caret is prepended to invert the set."
1790 ;; This function ought to be in the elisp core somewhere.
1791 (let ((str (if inverted "^" "")) char char2)
1792 (setq chars (sort (append chars nil) `<))
1793 (while chars
1794 (setq char (pop chars))
1795 (if (memq char '(?\\ ?^ ?-))
1796 ;; Quoting necessary (this method only works in the skip
1797 ;; functions).
1798 (setq str (format "%s\\%c" str char))
1799 (setq str (format "%s%c" str char)))
1800 ;; Check for range.
1801 (setq char2 char)
1802 (while (and chars (>= (1+ char2) (car chars)))
1803 (setq char2 (pop chars)))
1804 (unless (= char char2)
1805 (if (< (1+ char) char2)
1806 (setq str (format "%s-%c" str char2))
1807 (push char2 chars))))
1808 str))
1810 ;; Leftovers from (X)Emacs 19 compatibility.
1811 (defalias 'c-regexp-opt 'regexp-opt)
1812 (defalias 'c-regexp-opt-depth 'regexp-opt-depth)
1815 ;; Figure out what features this Emacs has
1817 (cc-bytecomp-defvar open-paren-in-column-0-is-defun-start)
1819 (defconst c-emacs-features
1820 (let (list)
1822 (if (boundp 'infodock-version)
1823 ;; I've no idea what this actually is, but it's legacy. /mast
1824 (setq list (cons 'infodock list)))
1826 ;; XEmacs uses 8-bit modify-syntax-entry flags.
1827 ;; Emacs uses a 1-bit flag. We will have to set up our
1828 ;; syntax tables differently to handle this.
1829 (let ((table (copy-syntax-table))
1830 entry)
1831 (modify-syntax-entry ?a ". 12345678" table)
1832 (cond
1833 ;; Emacs
1834 ((arrayp table)
1835 (setq entry (aref table ?a))
1836 ;; In Emacs, table entries are cons cells
1837 (if (consp entry) (setq entry (car entry))))
1838 ;; XEmacs
1839 ((fboundp 'get-char-table)
1840 (setq entry (get-char-table ?a table)))
1841 ;; incompatible
1842 (t (error "CC Mode is incompatible with this version of Emacs")))
1843 (setq list (cons (if (= (logand (lsh entry -16) 255) 255)
1844 '8-bit
1845 '1-bit)
1846 list)))
1848 ;; Check whether beginning/end-of-defun call
1849 ;; beginning/end-of-defun-function nicely, passing through the
1850 ;; argument and respecting the return code.
1851 (let* (mark-ring
1852 (bod-param 'foo) (eod-param 'foo)
1853 (beginning-of-defun-function
1854 (lambda (&optional arg)
1855 (or (eq bod-param 'foo) (setq bod-param 'bar))
1856 (and (eq bod-param 'foo)
1857 (setq bod-param arg)
1858 (eq arg 3))))
1859 (end-of-defun-function
1860 (lambda (&optional arg)
1861 (and (eq eod-param 'foo)
1862 (setq eod-param arg)
1863 (eq arg 3)))))
1864 (if (save-excursion (and (beginning-of-defun 3) (eq bod-param 3)
1865 (not (beginning-of-defun))
1866 (end-of-defun 3) (eq eod-param 3)
1867 (not (end-of-defun))))
1868 (setq list (cons 'argumentative-bod-function list))))
1870 ;; Record whether the `category' text property works.
1871 (if c-use-category (setq list (cons 'category-properties list)))
1873 (let ((buf (generate-new-buffer " test"))
1874 parse-sexp-lookup-properties
1875 parse-sexp-ignore-comments
1876 lookup-syntax-properties) ; XEmacs
1877 (with-current-buffer buf
1878 (set-syntax-table (make-syntax-table))
1880 ;; For some reason we have to set some of these after the
1881 ;; buffer has been made current. (Specifically,
1882 ;; `parse-sexp-ignore-comments' in Emacs 21.)
1883 (setq parse-sexp-lookup-properties t
1884 parse-sexp-ignore-comments t
1885 lookup-syntax-properties t)
1887 ;; Find out if the `syntax-table' text property works.
1888 (modify-syntax-entry ?< ".")
1889 (modify-syntax-entry ?> ".")
1890 (insert "<()>")
1891 (c-mark-<-as-paren (point-min))
1892 (c-mark->-as-paren (+ 3 (point-min)))
1893 (goto-char (point-min))
1894 (c-forward-sexp)
1895 (if (= (point) (+ 4 (point-min)))
1896 (setq list (cons 'syntax-properties list))
1897 (error (concat
1898 "CC Mode is incompatible with this version of Emacs - "
1899 "support for the `syntax-table' text property "
1900 "is required.")))
1902 ;; Find out if "\\s!" (generic comment delimiters) work.
1903 (c-safe
1904 (modify-syntax-entry ?x "!")
1905 (if (string-match "\\s!" "x")
1906 (setq list (cons 'gen-comment-delim list))))
1908 ;; Find out if "\\s|" (generic string delimiters) work.
1909 (c-safe
1910 (modify-syntax-entry ?x "|")
1911 (if (string-match "\\s|" "x")
1912 (setq list (cons 'gen-string-delim list))))
1914 ;; See if POSIX char classes work.
1915 (when (and (string-match "[[:alpha:]]" "a")
1916 ;; All versions of Emacs 21 so far haven't fixed
1917 ;; char classes in `skip-chars-forward' and
1918 ;; `skip-chars-backward'.
1919 (progn
1920 (delete-region (point-min) (point-max))
1921 (insert "foo123")
1922 (skip-chars-backward "[:alnum:]")
1923 (bobp))
1924 (= (skip-chars-forward "[:alpha:]") 3))
1925 (setq list (cons 'posix-char-classes list)))
1927 ;; See if `open-paren-in-column-0-is-defun-start' exists and
1928 ;; isn't buggy (Emacs >= 21.4).
1929 (when (boundp 'open-paren-in-column-0-is-defun-start)
1930 (let ((open-paren-in-column-0-is-defun-start nil)
1931 (parse-sexp-ignore-comments t))
1932 (delete-region (point-min) (point-max))
1933 (set-syntax-table (make-syntax-table))
1934 (modify-syntax-entry ?\' "\"")
1935 (cond
1936 ;; XEmacs. Afaik this is currently an Emacs-only
1937 ;; feature, but it's good to be prepared.
1938 ((memq '8-bit list)
1939 (modify-syntax-entry ?/ ". 1456")
1940 (modify-syntax-entry ?* ". 23"))
1941 ;; Emacs
1942 ((memq '1-bit list)
1943 (modify-syntax-entry ?/ ". 124b")
1944 (modify-syntax-entry ?* ". 23")))
1945 (modify-syntax-entry ?\n "> b")
1946 (insert "/* '\n () */")
1947 (backward-sexp)
1948 (if (bobp)
1949 (setq list (cons 'col-0-paren list)))))
1951 (set-buffer-modified-p nil))
1952 (kill-buffer buf))
1954 ;; Check how many elements `parse-partial-sexp' returns.
1955 (let ((ppss-size (or (c-safe (length
1956 (save-excursion
1957 (parse-partial-sexp (point) (point)))))
1958 0)))
1959 (cond
1960 ((>= ppss-size 11) (setq list (cons 'pps-extended-state list)))
1961 ((>= ppss-size 10))
1962 (t (error
1963 (concat
1964 "CC Mode is incompatible with this version of Emacs - "
1965 "`parse-partial-sexp' has to return at least 10 elements.")))))
1967 ;;(message "c-emacs-features: %S" list)
1968 list)
1969 "A list of certain features in the (X)Emacs you are using.
1970 There are many flavors of Emacs out there, each with different
1971 features supporting those needed by CC Mode. The following values
1972 might be present:
1974 `8-bit' 8 bit syntax entry flags (XEmacs style).
1975 `1-bit' 1 bit syntax entry flags (Emacs style).
1976 `argumentative-bod-function' beginning-of-defun and end-of-defun pass
1977 ARG through to beginning/end-of-defun-function.
1978 `syntax-properties' It works to override the syntax for specific characters
1979 in the buffer with the `syntax-table' property. It's
1980 always set - CC Mode no longer works in emacsen without
1981 this feature.
1982 `category-properties' Syntax routines can add a level of indirection to text
1983 properties using the `category' property.
1984 `gen-comment-delim' Generic comment delimiters work
1985 (i.e. the syntax class `!').
1986 `gen-string-delim' Generic string delimiters work
1987 (i.e. the syntax class `|').
1988 `pps-extended-state' `parse-partial-sexp' returns a list with at least 11
1989 elements, i.e. it indicates having stopped after the
1990 first character of a potential two-char construct.
1991 `posix-char-classes' The regexp engine understands POSIX character classes.
1992 `col-0-paren' It's possible to turn off the ad-hoc rule that a paren
1993 in column zero is the start of a defun.
1994 `infodock' This is Infodock (based on XEmacs).
1996 `8-bit' and `1-bit' are mutually exclusive.")
1999 ;;; Some helper constants.
2001 ;; If the regexp engine supports POSIX char classes then we can use
2002 ;; them to handle extended charsets correctly.
2003 (if (memq 'posix-char-classes c-emacs-features)
2004 (progn
2005 (defconst c-alpha "[:alpha:]")
2006 (defconst c-alnum "[:alnum:]")
2007 (defconst c-digit "[:digit:]")
2008 (defconst c-upper "[:upper:]")
2009 (defconst c-lower "[:lower:]"))
2010 (defconst c-alpha "a-zA-Z")
2011 (defconst c-alnum "a-zA-Z0-9")
2012 (defconst c-digit "0-9")
2013 (defconst c-upper "A-Z")
2014 (defconst c-lower "a-z"))
2017 ;;; System for handling language dependent constants.
2019 ;; This is used to set various language dependent data in a flexible
2020 ;; way: Language constants can be built from the values of other
2021 ;; language constants, also those for other languages. They can also
2022 ;; process the values of other language constants uniformly across all
2023 ;; the languages. E.g. one language constant can list all the type
2024 ;; keywords in each language, and another can build a regexp for each
2025 ;; language from those lists without code duplication.
2027 ;; Language constants are defined with `c-lang-defconst', and their
2028 ;; value forms (referred to as source definitions) are evaluated only
2029 ;; on demand when requested for a particular language with
2030 ;; `c-lang-const'. It's therefore possible to refer to the values of
2031 ;; constants defined later in the file, or in another file, just as
2032 ;; long as all the relevant `c-lang-defconst' have been loaded when
2033 ;; `c-lang-const' is actually evaluated from somewhere else.
2035 ;; `c-lang-const' forms are also evaluated at compile time and
2036 ;; replaced with the values they produce. Thus there's no overhead
2037 ;; for this system when compiled code is used - only the values
2038 ;; actually used in the code are present, and the file(s) containing
2039 ;; the `c-lang-defconst' forms don't need to be loaded at all then.
2040 ;; There are however safeguards to make sure that they can be loaded
2041 ;; to get the source definitions for the values if there's a mismatch
2042 ;; in compiled versions, or if `c-lang-const' is used uncompiled.
2044 ;; Note that the source definitions in a `c-lang-defconst' form are
2045 ;; compiled into the .elc file where it stands; there's no need to
2046 ;; load the source file to get it.
2048 ;; See cc-langs.el for more details about how this system is deployed
2049 ;; in CC Mode, and how the associated language variable system
2050 ;; (`c-lang-defvar') works. That file also contains a lot of
2051 ;; examples.
2053 (defun c-add-language (mode base-mode)
2054 "Declare a new language in the language dependent variable system.
2055 This is intended to be used by modes that inherit CC Mode to add new
2056 languages. It should be used at the top level before any calls to
2057 `c-lang-defconst'. MODE is the mode name symbol for the new language,
2058 and BASE-MODE is the mode name symbol for the language in CC Mode that
2059 is to be the template for the new mode.
2061 The exact effect of BASE-MODE is to make all language constants that
2062 haven't got a setting in the new language fall back to their values in
2063 BASE-MODE. It does not have any effect outside the language constant
2064 system."
2065 (unless (string-match "\\`\\(.*-\\)mode\\'" (symbol-name mode))
2066 (error "The mode name symbol `%s' must end with \"-mode\"" mode))
2067 (put mode 'c-mode-prefix (match-string 1 (symbol-name mode)))
2068 (unless (get base-mode 'c-mode-prefix)
2069 (error "Unknown base mode `%s'" base-mode))
2070 (put mode 'c-fallback-mode base-mode))
2072 (defvar c-lang-constants (make-vector 151 0))
2073 ;; Obarray used as a cache to keep track of the language constants.
2074 ;; The constants stored are those defined by `c-lang-defconst' and the values
2075 ;; computed by `c-lang-const'. It's mostly used at compile time but it's not
2076 ;; stored in compiled files.
2078 ;; The obarray contains all the language constants as symbols. The
2079 ;; value cells hold the evaluated values as alists where each car is
2080 ;; the mode name symbol and the corresponding cdr is the evaluated
2081 ;; value in that mode. The property lists hold the source definitions
2082 ;; and other miscellaneous data. The obarray might also contain
2083 ;; various other symbols, but those don't have any variable bindings.
2085 (defvar c-lang-const-expansion nil)
2087 ;; Ugly hack to pull in the definition of `cc-bytecomp-compiling-or-loading'
2088 ;; from cc-bytecomp to make it available at loadtime. This is the same
2089 ;; mechanism used in cc-mode.el for `c-populate-syntax-table'.
2090 (defalias 'cc-bytecomp-compiling-or-loading
2091 (cc-eval-when-compile
2092 (let ((f (symbol-function 'cc-bytecomp-compiling-or-loading)))
2093 (if (byte-code-function-p f) f (byte-compile f)))))
2095 (defsubst c-get-current-file ()
2096 ;; Return the base name of the current file.
2097 (let* ((c-or-l (cc-bytecomp-compiling-or-loading))
2098 (file
2099 (cond
2100 ((eq c-or-l 'loading) load-file-name)
2101 ((eq c-or-l 'compiling) byte-compile-dest-file)
2102 ((null c-or-l) (buffer-file-name)))))
2103 (and file
2104 (file-name-sans-extension
2105 (file-name-nondirectory file)))))
2107 (defmacro c-lang-defconst-eval-immediately (form)
2108 "Can be used inside a VAL in `c-lang-defconst' to evaluate FORM
2109 immediately, i.e. at the same time as the `c-lang-defconst' form
2110 itself is evaluated."
2111 ;; Evaluate at macro expansion time, i.e. in the
2112 ;; `c--macroexpand-all' inside `c-lang-defconst'.
2113 (eval form))
2115 (defmacro c-lang-defconst (name &rest args)
2116 "Set the language specific values of the language constant NAME.
2117 The second argument can optionally be a docstring. The rest of the
2118 arguments are one or more repetitions of LANG VAL where LANG specifies
2119 the language(s) that VAL applies to. LANG is the name of the
2120 language, i.e. the mode name without the \"-mode\" suffix, or a list
2121 of such language names, or t for all languages. VAL is a form to
2122 evaluate to get the value.
2124 If LANG isn't t or one of the core languages in CC Mode, it must
2125 have been declared with `c-add-language'.
2127 Neither NAME, LANG nor VAL are evaluated directly - they should not be
2128 quoted. `c-lang-defconst-eval-immediately' can however be used inside
2129 VAL to evaluate parts of it directly.
2131 When VAL is evaluated for some language, that language is temporarily
2132 made current so that `c-lang-const' without an explicit language can
2133 be used inside VAL to refer to the value of a language constant in the
2134 same language. That is particularly useful if LANG is t.
2136 VAL is not evaluated right away but rather when the value is requested
2137 with `c-lang-const'. Thus it's possible to use `c-lang-const' inside
2138 VAL to refer to language constants that haven't been defined yet.
2139 However, if the definition of a language constant is in another file
2140 then that file must be loaded \(at compile time) before it's safe to
2141 reference the constant.
2143 The assignments in ARGS are processed in sequence like `setq', so
2144 \(c-lang-const NAME) may be used inside a VAL to refer to the last
2145 assigned value to this language constant, or a value that it has
2146 gotten in another earlier loaded file.
2148 To work well with repeated loads and interactive reevaluation, only
2149 one `c-lang-defconst' for each NAME is permitted per file. If there
2150 already is one it will be completely replaced; the value in the
2151 earlier definition will not affect `c-lang-const' on the same
2152 constant. A file is identified by its base name."
2154 (let* ((sym (intern (symbol-name name) c-lang-constants))
2155 ;; Make `c-lang-const' expand to a straightforward call to
2156 ;; `c-get-lang-constant' in `c--macroexpand-all' below.
2158 ;; (The default behavior, i.e. to expand to a call inside
2159 ;; `eval-when-compile' should be equivalent, since that macro
2160 ;; should only expand to its content if it's used inside a
2161 ;; form that's already evaluated at compile time. It's
2162 ;; however necessary to use our cover macro
2163 ;; `cc-eval-when-compile' due to bugs in `eval-when-compile',
2164 ;; and it expands to a bulkier form that in this case only is
2165 ;; unnecessary garbage that we don't want to store in the
2166 ;; language constant source definitions.)
2167 (c-lang-const-expansion 'call)
2168 (c-langs-are-parametric t)
2169 (file (intern
2170 (or (c-get-current-file)
2171 (error "`c-lang-defconst' can only be used in a file"))))
2172 bindings
2173 pre-files)
2175 (or (symbolp name)
2176 (error "Not a symbol: %S" name))
2178 (when (stringp (car-safe args))
2179 ;; The docstring is hardly used anywhere since there's no normal
2180 ;; symbol to attach it to. It's primarily for getting the right
2181 ;; format in the source.
2182 (put sym 'variable-documentation (car args))
2183 (setq args (cdr args)))
2185 (or args
2186 (error "No assignments in `c-lang-defconst' for %S" name))
2188 ;; Rework ARGS to an association list to make it easier to handle.
2189 ;; It's reversed at the same time to make it easier to implement
2190 ;; the demand-driven (i.e. reversed) evaluation in `c-lang-const'.
2191 (while args
2192 (let ((assigned-mode
2193 (cond ((eq (car args) t) t)
2194 ((symbolp (car args))
2195 (list (intern (concat (symbol-name (car args))
2196 "-mode"))))
2197 ((listp (car args))
2198 (mapcar (lambda (lang)
2199 (or (symbolp lang)
2200 (error "Not a list of symbols: %S"
2201 (car args)))
2202 (intern (concat (symbol-name lang)
2203 "-mode")))
2204 (car args)))
2205 (t (error "Not a symbol or a list of symbols: %S"
2206 (car args)))))
2207 val)
2209 (or (cdr args)
2210 (error "No value for %S" (car args)))
2211 (setq args (cdr args)
2212 val (car args))
2214 ;; Emacs has a weird bug where it seems to fail to read
2215 ;; backquote lists from byte compiled files correctly (,@
2216 ;; forms, to be specific), so make sure the bindings in the
2217 ;; expansion below don't contain any backquote stuff.
2218 ;; (XEmacs handles it correctly and doesn't need this for that
2219 ;; reason, but we also use this expansion handle
2220 ;; `c-lang-defconst-eval-immediately' and to register
2221 ;; dependencies on the `c-lang-const's in VAL.)
2222 (setq val (c--macroexpand-all val))
2224 (setq bindings `(cons (cons ',assigned-mode (lambda () ,val)) ,bindings)
2225 args (cdr args))))
2227 ;; Compile in the other files that have provided source
2228 ;; definitions for this symbol, to make sure the order in the
2229 ;; `source' property is correct even when files are loaded out of
2230 ;; order.
2231 (setq pre-files (mapcar 'car (get sym 'source)))
2232 (if (memq file pre-files)
2233 ;; This can happen when the source file (e.g. cc-langs.el) is first
2234 ;; loaded as source, setting a 'source property entry, and then itself
2235 ;; being compiled.
2236 (setq pre-files (cdr (memq file pre-files))))
2237 ;; Reverse to get the right load order.
2238 (setq pre-files (nreverse pre-files))
2240 `(eval-and-compile
2241 (c-define-lang-constant ',name ,bindings
2242 ,@(and pre-files `(',pre-files))))))
2244 (put 'c-lang-defconst 'lisp-indent-function 1)
2245 ;(eval-after-load "edebug" ; 2006-07-09: def-edebug-spec is now in subr.el.
2247 (def-edebug-spec c-lang-defconst
2248 (&define name [&optional stringp] [&rest sexp def-form]))
2250 (defun c-define-lang-constant (name bindings &optional pre-files)
2251 ;; Used by `c-lang-defconst'.
2253 (let* ((sym (intern (symbol-name name) c-lang-constants))
2254 (source (get sym 'source))
2255 (file (intern
2256 (or (c-get-current-file)
2257 (error "`c-lang-defconst' must be used in a file"))))
2258 (elem (assq file source)))
2260 ;;(when (cdr-safe elem)
2261 ;; (message "Language constant %s redefined in %S" name file))
2263 ;; Note that the order in the source alist is relevant. Like how
2264 ;; `c-lang-defconst' reverses the bindings, this reverses the
2265 ;; order between files so that the last to evaluate comes first.
2266 (unless elem
2267 (while pre-files
2268 (unless (assq (car pre-files) source)
2269 (setq source (cons (list (car pre-files)) source)))
2270 (setq pre-files (cdr pre-files)))
2271 (put sym 'source (cons (setq elem (list file)) source)))
2273 (setcdr elem bindings)
2275 ;; Bind the symbol as a variable, or clear any earlier evaluated
2276 ;; value it has.
2277 (set sym nil)
2279 ;; Clear the evaluated values that depend on this source.
2280 (let ((agenda (get sym 'dependents))
2281 (visited (make-vector 101 0))
2282 ptr)
2283 (while agenda
2284 (setq sym (car agenda)
2285 agenda (cdr agenda))
2286 (intern (symbol-name sym) visited)
2287 (set sym nil)
2288 (setq ptr (get sym 'dependents))
2289 (while ptr
2290 (setq sym (car ptr)
2291 ptr (cdr ptr))
2292 (unless (intern-soft (symbol-name sym) visited)
2293 (setq agenda (cons sym agenda))))))
2295 name))
2297 (defmacro c-lang-const (name &optional lang)
2298 "Get the mode specific value of the language constant NAME in language LANG.
2299 LANG is the name of the language, i.e. the mode name without the
2300 \"-mode\" suffix. If used inside `c-lang-defconst' or
2301 `c-lang-defvar', LANG may be left out to refer to the current
2302 language. NAME and LANG are not evaluated so they should not be
2303 quoted."
2305 (or (symbolp name)
2306 (error "Not a symbol: %S" name))
2307 (or (symbolp lang)
2308 (error "Not a symbol: %S" lang))
2310 (let ((sym (intern (symbol-name name) c-lang-constants))
2311 (mode (when lang (intern (concat (symbol-name lang) "-mode")))))
2313 (or (get mode 'c-mode-prefix) (null mode)
2314 (error "Unknown language %S: no `c-mode-prefix' property"
2315 lang))
2317 (if (eq c-lang-const-expansion 'immediate)
2318 ;; No need to find out the source file(s) when we evaluate
2319 ;; immediately since all the info is already there in the
2320 ;; `source' property.
2321 `',(c-get-lang-constant name nil mode)
2323 (let ((source-files
2324 (let ((file (c-get-current-file)))
2325 (if file (setq file (intern file)))
2326 ;; Get the source file(s) that must be loaded to get the value
2327 ;; of the constant. If the symbol isn't defined yet we assume
2328 ;; that its definition will come later in this file, and thus
2329 ;; are no file dependencies needed.
2330 (nreverse
2331 ;; Reverse to get the right load order.
2332 (c--mapcan (lambda (elem)
2333 (if (eq file (car elem))
2334 nil ; Exclude our own file.
2335 (list (car elem))))
2336 (get sym 'source)))))
2338 ;; Make some effort to do a compact call to
2339 ;; `c-get-lang-constant' since it will be compiled in.
2340 (args (and mode `(',mode))))
2342 (if (or source-files args)
2343 (push (and source-files `',source-files) args))
2345 (if (or (eq c-lang-const-expansion 'call)
2346 (and (not c-lang-const-expansion)
2347 (not mode))
2348 (not (cc-bytecomp-is-compiling)))
2349 ;; Either a straight call is requested in the context, or
2350 ;; we're in an "uncontrolled" context and got no language,
2351 ;; or we're not being byte compiled so the compile time
2352 ;; stuff below is unnecessary.
2353 `(c-get-lang-constant ',name ,@args)
2355 ;; Being compiled. If the loading and compiling version is
2356 ;; the same we use a value that is evaluated at compile time,
2357 ;; otherwise it's evaluated at runtime.
2358 `(if (eq c-version-sym ',c-version-sym)
2359 (cc-eval-when-compile
2360 (c-get-lang-constant ',name ,@args))
2361 (c-get-lang-constant ',name ,@args)))))))
2363 (defvar c-lang-constants-under-evaluation nil
2364 "Alist of constants in the process of being evaluated.
2365 The `cdr' of each entry indicates how far we've looked in the list
2366 of definitions, so that the def for var FOO in c-mode can be defined in
2367 terms of the def for that same var FOO (which will then rely on the
2368 fallback definition for all modes, to break the cycle).")
2370 (defconst c-lang--novalue "novalue")
2372 (defun c-get-lang-constant (name &optional source-files mode)
2373 ;; Used by `c-lang-const'.
2375 (or mode
2376 (setq mode c-buffer-is-cc-mode)
2377 (error "No current language"))
2379 (let* ((sym (intern (symbol-name name) c-lang-constants))
2380 (source (get sym 'source))
2381 elem
2382 (eval-in-sym (and c-lang-constants-under-evaluation
2383 (caar c-lang-constants-under-evaluation))))
2385 ;; Record the dependencies between this symbol and the one we're
2386 ;; being evaluated in.
2387 (when eval-in-sym
2388 (or (memq eval-in-sym (get sym 'dependents))
2389 (put sym 'dependents (cons eval-in-sym (get sym 'dependents)))))
2391 ;; Make sure the source files have entries on the `source'
2392 ;; property so that loading will take place when necessary.
2393 (while source-files
2394 (unless (assq (car source-files) source)
2395 (put sym 'source
2396 (setq source (cons (list (car source-files)) source)))
2397 ;; Might pull in more definitions which affect the value. The
2398 ;; clearing of dependent values etc is done when the
2399 ;; definition is encountered during the load; this is just to
2400 ;; jump past the check for a cached value below.
2401 (set sym nil))
2402 (setq source-files (cdr source-files)))
2404 (if (and (boundp sym)
2405 (setq elem (assq mode (symbol-value sym))))
2406 (cdr elem)
2408 ;; Check if an evaluation of this symbol is already underway.
2409 ;; In that case we just continue with the "assignment" before
2410 ;; the one currently being evaluated, thereby creating the
2411 ;; illusion if a `setq'-like sequence of assignments.
2412 (let* ((c-buffer-is-cc-mode mode)
2413 (source-pos
2414 (or (assq sym c-lang-constants-under-evaluation)
2415 (cons sym (vector source nil))))
2416 ;; Append `c-lang-constants-under-evaluation' even if an
2417 ;; earlier entry is found. It's only necessary to get
2418 ;; the recording of dependencies above correct.
2419 (c-lang-constants-under-evaluation
2420 (cons source-pos c-lang-constants-under-evaluation))
2421 (fallback (get mode 'c-fallback-mode))
2422 value
2423 ;; Make sure the recursion limits aren't very low
2424 ;; since the `c-lang-const' dependencies can go deep.
2425 (max-specpdl-size (max max-specpdl-size 3000))
2426 (max-lisp-eval-depth (max max-lisp-eval-depth 1000)))
2428 (if (if fallback
2429 (let ((backup-source-pos (copy-sequence (cdr source-pos))))
2430 (and
2431 ;; First try the original mode but don't accept an
2432 ;; entry matching all languages since the fallback
2433 ;; mode might have an explicit entry before that.
2434 (eq (setq value (c-find-assignment-for-mode
2435 (cdr source-pos) mode nil name))
2436 c-lang--novalue)
2437 ;; Try again with the fallback mode from the
2438 ;; original position. Note that
2439 ;; `c-buffer-is-cc-mode' still is the real mode if
2440 ;; language parameterization takes place.
2441 (eq (setq value (c-find-assignment-for-mode
2442 (setcdr source-pos backup-source-pos)
2443 fallback t name))
2444 c-lang--novalue)))
2445 ;; A simple lookup with no fallback mode.
2446 (eq (setq value (c-find-assignment-for-mode
2447 (cdr source-pos) mode t name))
2448 c-lang--novalue))
2449 (error
2450 "`%s' got no (prior) value in %S (might be a cyclic reference)"
2451 name mode))
2453 (condition-case err
2454 (setq value (funcall value))
2455 (error
2456 ;; Print a message to aid in locating the error. We don't
2457 ;; print the error itself since that will be done later by
2458 ;; some caller higher up.
2459 (message "Eval error in the `c-lang-defconst' for `%S' in %s:"
2460 sym mode)
2461 (makunbound sym)
2462 (signal (car err) (cdr err))))
2464 (set sym (cons (cons mode value) (symbol-value sym)))
2465 value))))
2467 (defun c-find-assignment-for-mode (source-pos mode match-any-lang _name)
2468 ;; Find the first assignment entry that applies to MODE at or after
2469 ;; SOURCE-POS. If MATCH-ANY-LANG is non-nil, entries with t as
2470 ;; the language list are considered to match, otherwise they don't.
2471 ;; On return SOURCE-POS is updated to point to the next assignment
2472 ;; after the returned one. If no assignment is found,
2473 ;; `c-lang--novalue' is returned as a magic value.
2475 ;; SOURCE-POS is a vector that points out a specific assignment in
2476 ;; the double alist that's used in the `source' property. The first
2477 ;; element is the position in the top alist which is indexed with
2478 ;; the source files, and the second element is the position in the
2479 ;; nested bindings alist.
2481 ;; NAME is only used for error messages.
2483 (catch 'found
2484 (let ((file-entry (elt source-pos 0))
2485 (assignment-entry (elt source-pos 1))
2486 assignment)
2488 (while (if assignment-entry
2490 ;; Handled the last assignment from one file, begin on the
2491 ;; next. Due to the check in `c-lang-defconst', we know
2492 ;; there's at least one.
2493 (when file-entry
2495 (unless (aset source-pos 1
2496 (setq assignment-entry (cdar file-entry)))
2497 ;; The file containing the source definitions has not
2498 ;; been loaded.
2499 (let ((file (symbol-name (caar file-entry)))
2500 (c-lang-constants-under-evaluation nil))
2501 ;;(message (concat "Loading %s to get the source "
2502 ;; "value for language constant %s")
2503 ;; file name)
2504 (load file nil t))
2506 (unless (setq assignment-entry (cdar file-entry))
2507 ;; The load didn't fill in the source for the
2508 ;; constant as expected. The situation is
2509 ;; probably that a derived mode was written for
2510 ;; and compiled with another version of CC Mode,
2511 ;; and the requested constant isn't in the
2512 ;; currently loaded one. Put in a dummy
2513 ;; assignment that matches no language.
2514 (setcdr (car file-entry)
2515 (setq assignment-entry (list (list nil))))))
2517 (aset source-pos 0 (setq file-entry (cdr file-entry)))
2520 (setq assignment (car assignment-entry))
2521 (aset source-pos 1
2522 (setq assignment-entry (cdr assignment-entry)))
2524 (when (if (listp (car assignment))
2525 (memq mode (car assignment))
2526 match-any-lang)
2527 (throw 'found (cdr assignment))))
2529 c-lang--novalue)))
2531 (defun c-lang-major-mode-is (mode)
2532 ;; `c-major-mode-is' expands to a call to this function inside
2533 ;; `c-lang-defconst'. Here we also match the mode(s) against any
2534 ;; fallback modes for the one in `c-buffer-is-cc-mode', so that
2535 ;; e.g. (c-major-mode-is 'c++-mode) is true in a derived language
2536 ;; that has c++-mode as base mode.
2537 (unless (listp mode)
2538 (setq mode (list mode)))
2539 (let (match (buf-mode c-buffer-is-cc-mode))
2540 (while (if (memq buf-mode mode)
2541 (progn
2542 (setq match t)
2543 nil)
2544 (setq buf-mode (get buf-mode 'c-fallback-mode))))
2545 match))
2548 (cc-provide 'cc-defs)
2550 ;; Local Variables:
2551 ;; indent-tabs-mode: t
2552 ;; tab-width: 8
2553 ;; End:
2554 ;;; cc-defs.el ends here