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