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