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