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