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