]> code.delx.au - gnu-emacs/blob - lisp/progmodes/cc-mode.el
80ac08fb9e01687519a5b7373959195b6dc9c590
[gnu-emacs] / lisp / progmodes / cc-mode.el
1 ;;; cc-mode.el --- major mode for editing C and similar languages
2
3 ;; Copyright (C) 1985, 1987, 1992-2016 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: a long, long, time ago. adapted from the original c-mode.el
13 ;; Keywords: c languages
14
15 ;; This file is part of GNU Emacs.
16
17 ;; GNU Emacs is free software: you can redistribute it and/or modify
18 ;; it under the terms of the GNU General Public License as published by
19 ;; the Free Software Foundation, either version 3 of the License, or
20 ;; (at your option) any later version.
21
22 ;; GNU Emacs is distributed in the hope that it will be useful,
23 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
24 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
25 ;; GNU General Public License for more details.
26
27 ;; You should have received a copy of the GNU General Public License
28 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
29
30 ;;; Commentary:
31
32 ;; NOTE: Read the commentary below for the right way to submit bug reports!
33 ;; NOTE: See the accompanying texinfo manual for details on using this mode!
34 ;; Note: The version string is in cc-defs.
35
36 ;; This package provides GNU Emacs major modes for editing C, C++,
37 ;; Objective-C, Java, CORBA's IDL, Pike and AWK code. As of the
38 ;; latest Emacs and XEmacs releases, it is the default package for
39 ;; editing these languages. This package is called "CC Mode", and
40 ;; should be spelled exactly this way.
41
42 ;; CC Mode supports K&R and ANSI C, ANSI C++, Objective-C, Java,
43 ;; CORBA's IDL, Pike and AWK with a consistent indentation model
44 ;; across all modes. This indentation model is intuitive and very
45 ;; flexible, so that almost any desired style of indentation can be
46 ;; supported. Installation, usage, and programming details are
47 ;; contained in an accompanying texinfo manual.
48
49 ;; CC Mode's immediate ancestors were, c++-mode.el, cplus-md.el, and
50 ;; cplus-md1.el..
51
52 ;; To submit bug reports, type "C-c C-b". These will be sent to
53 ;; bug-gnu-emacs@gnu.org (mirrored as the Usenet newsgroup
54 ;; gnu.emacs.bug) as well as bug-cc-mode@gnu.org, which directly
55 ;; contacts the CC Mode maintainers. Questions can sent to
56 ;; help-gnu-emacs@gnu.org (mirrored as gnu.emacs.help) and/or
57 ;; bug-cc-mode@gnu.org. Please do not send bugs or questions to our
58 ;; personal accounts; we reserve the right to ignore such email!
59
60 ;; Many, many thanks go out to all the folks on the beta test list.
61 ;; Without their patience, testing, insight, code contributions, and
62 ;; encouragement CC Mode would be a far inferior package.
63
64 ;; You can get the latest version of CC Mode, including PostScript
65 ;; documentation and separate individual files from:
66 ;;
67 ;; http://cc-mode.sourceforge.net/
68 ;;
69 ;; You can join a moderated CC Mode announcement-only mailing list by
70 ;; visiting
71 ;;
72 ;; http://lists.sourceforge.net/mailman/listinfo/cc-mode-announce
73
74 ;; Externally maintained major modes which use CC-mode's engine include:
75 ;; - cuda-mode
76 ;; - csharp-mode (https://github.com/josteink/csharp-mode)
77 ;; - haxe-mode
78 ;; - d-mode
79 ;; - dart-mode
80 ;; - cc-php-js-cs.el
81 ;; - php-mode
82 ;; - yang-mode
83 ;; - math-mode (mathematica)
84 ;; - unrealscript-mode
85 ;; - groovy-mode
86
87 ;;; Code:
88
89 ;; For Emacs < 22.2.
90 (eval-and-compile
91 (unless (fboundp 'declare-function) (defmacro declare-function (&rest _r))))
92
93 (eval-when-compile
94 (let ((load-path
95 (if (and (boundp 'byte-compile-dest-file)
96 (stringp byte-compile-dest-file))
97 (cons (file-name-directory byte-compile-dest-file) load-path)
98 load-path)))
99 (load "cc-bytecomp" nil t)))
100
101 (cc-require 'cc-defs)
102 (cc-require 'cc-vars)
103 (cc-require-when-compile 'cc-langs)
104 (cc-require 'cc-engine)
105 (cc-require 'cc-styles)
106 (cc-require 'cc-cmds)
107 (cc-require 'cc-align)
108 (cc-require 'cc-menus)
109 (cc-require 'cc-guess)
110
111 ;; Silence the compiler.
112 (cc-bytecomp-defvar adaptive-fill-first-line-regexp) ; Emacs
113 (cc-bytecomp-defun run-mode-hooks) ; Emacs 21.1
114
115 ;; We set this variable during mode init, yet we don't require
116 ;; font-lock.
117 (cc-bytecomp-defvar font-lock-defaults)
118
119 ;; Menu support for both XEmacs and Emacs. If you don't have easymenu
120 ;; with your version of Emacs, you are incompatible!
121 (cc-external-require 'easymenu)
122
123 ;; Load cc-fonts first after font-lock is loaded, since it isn't
124 ;; necessary until font locking is requested.
125 ; (eval-after-load "font-lock" ; 2006-07-09: font-lock is now preloaded.
126 ; '
127 (require 'cc-fonts) ;)
128
129 \f
130 ;; Other modes and packages which depend on CC Mode should do the
131 ;; following to make sure everything is loaded and available for their
132 ;; use:
133 ;;
134 ;; (require 'cc-mode)
135 ;;
136 ;; And in the major mode function:
137 ;;
138 ;; (c-initialize-cc-mode t)
139 ;; (c-init-language-vars some-mode)
140 ;; (c-common-init 'some-mode) ; Or perhaps (c-basic-common-init 'some-mode)
141 ;;
142 ;; If you're not writing a derived mode using the language variable
143 ;; system, then some-mode is one of the language modes directly
144 ;; supported by CC Mode. You can then use (c-init-language-vars-for
145 ;; 'some-mode) instead of `c-init-language-vars'.
146 ;; `c-init-language-vars-for' is a function that avoids the rather
147 ;; large expansion of `c-init-language-vars'.
148 ;;
149 ;; If you use `c-basic-common-init' then you might want to call
150 ;; `c-font-lock-init' too to set up CC Mode's font lock support.
151 ;;
152 ;; See cc-langs.el for further info. A small example of a derived mode
153 ;; is also available at <http://cc-mode.sourceforge.net/
154 ;; derived-mode-ex.el>.
155
156 (defun c-leave-cc-mode-mode ()
157 (when c-buffer-is-cc-mode
158 (save-restriction
159 (widen)
160 (c-save-buffer-state ()
161 (c-clear-char-properties (point-min) (point-max) 'category)
162 (c-clear-char-properties (point-min) (point-max) 'syntax-table)
163 (c-clear-char-properties (point-min) (point-max) 'c-is-sws)
164 (c-clear-char-properties (point-min) (point-max) 'c-in-sws)
165 (c-clear-char-properties (point-min) (point-max) 'c-type)
166 (if (c-major-mode-is 'awk-mode)
167 (c-clear-char-properties (point-min) (point-max) 'c-awk-NL-prop))))
168 (setq c-buffer-is-cc-mode nil)))
169
170 (defun c-init-language-vars-for (mode)
171 "Initialize the language variables for one of the language modes
172 directly supported by CC Mode. This can be used instead of the
173 `c-init-language-vars' macro if the language you want to use is one of
174 those, rather than a derived language defined through the language
175 variable system (see \"cc-langs.el\")."
176 (cond ((eq mode 'c-mode) (c-init-language-vars c-mode))
177 ((eq mode 'c++-mode) (c-init-language-vars c++-mode))
178 ((eq mode 'objc-mode) (c-init-language-vars objc-mode))
179 ((eq mode 'java-mode) (c-init-language-vars java-mode))
180 ((eq mode 'idl-mode) (c-init-language-vars idl-mode))
181 ((eq mode 'pike-mode) (c-init-language-vars pike-mode))
182 ((eq mode 'awk-mode) (c-init-language-vars awk-mode))
183 (t (error "Unsupported mode %s" mode))))
184
185 ;;;###autoload
186 (defun c-initialize-cc-mode (&optional new-style-init)
187 "Initialize CC Mode for use in the current buffer.
188 If the optional NEW-STYLE-INIT is nil or left out then all necessary
189 initialization to run CC Mode for the C language is done. Otherwise
190 only some basic setup is done, and a call to `c-init-language-vars' or
191 `c-init-language-vars-for' is necessary too (which gives more
192 control). See \"cc-mode.el\" for more info."
193
194 (setq c-buffer-is-cc-mode t)
195
196 (let ((initprop 'cc-mode-is-initialized)
197 c-initialization-ok)
198 (unless (get 'c-initialize-cc-mode initprop)
199 (unwind-protect
200 (progn
201 (put 'c-initialize-cc-mode initprop t)
202 (c-initialize-builtin-style)
203 (run-hooks 'c-initialization-hook)
204 ;; Fix obsolete variables.
205 (if (boundp 'c-comment-continuation-stars)
206 (setq c-block-comment-prefix c-comment-continuation-stars))
207 (add-hook 'change-major-mode-hook 'c-leave-cc-mode-mode)
208 (setq c-initialization-ok t)
209 ;; Connect up with Emacs's electric-indent-mode, for >= Emacs 24.4
210 (when (fboundp 'electric-indent-local-mode)
211 (add-hook 'electric-indent-mode-hook 'c-electric-indent-mode-hook)
212 (add-hook 'electric-indent-local-mode-hook
213 'c-electric-indent-local-mode-hook)))
214 ;; Will try initialization hooks again if they failed.
215 (put 'c-initialize-cc-mode initprop c-initialization-ok))))
216
217 (unless new-style-init
218 (c-init-language-vars-for 'c-mode)))
219
220 \f
221 ;;; Common routines.
222
223 (defvar c-mode-base-map ()
224 "Keymap shared by all CC Mode related modes.")
225
226 (defun c-make-inherited-keymap ()
227 (let ((map (make-sparse-keymap)))
228 ;; Necessary to use `cc-bytecomp-fboundp' below since this
229 ;; function is called from top-level forms that are evaluated
230 ;; while cc-bytecomp is active when one does M-x eval-buffer.
231 (cond
232 ;; Emacs
233 ((cc-bytecomp-fboundp 'set-keymap-parent)
234 (set-keymap-parent map c-mode-base-map))
235 ;; XEmacs
236 ((fboundp 'set-keymap-parents)
237 (set-keymap-parents map c-mode-base-map))
238 ;; incompatible
239 (t (error "CC Mode is incompatible with this version of Emacs")))
240 map))
241
242 (defun c-define-abbrev-table (name defs &optional doc)
243 ;; Compatibility wrapper for `define-abbrev' which passes a non-nil
244 ;; sixth argument for SYSTEM-FLAG in emacsen that support it
245 ;; (currently only Emacs >= 21.2).
246 (let ((table (or (and (boundp name) (symbol-value name))
247 (progn (condition-case nil
248 (define-abbrev-table name nil doc)
249 (wrong-number-of-arguments ;E.g. Emacs<23.
250 (eval `(defvar ,name nil ,doc))
251 (define-abbrev-table name nil)))
252 (symbol-value name)))))
253 (while defs
254 (condition-case nil
255 (apply 'define-abbrev table (append (car defs) '(t)))
256 (wrong-number-of-arguments
257 (apply 'define-abbrev table (car defs))))
258 (setq defs (cdr defs)))))
259 (put 'c-define-abbrev-table 'lisp-indent-function 1)
260
261 (defun c-bind-special-erase-keys ()
262 ;; Only used in Emacs to bind C-c C-<delete> and C-c C-<backspace>
263 ;; to the proper keys depending on `normal-erase-is-backspace'.
264 (if normal-erase-is-backspace
265 (progn
266 (define-key c-mode-base-map (kbd "C-c C-<delete>")
267 'c-hungry-delete-forward)
268 (define-key c-mode-base-map (kbd "C-c C-<backspace>")
269 'c-hungry-delete-backwards))
270 (define-key c-mode-base-map (kbd "C-c C-<delete>")
271 'c-hungry-delete-backwards)
272 (define-key c-mode-base-map (kbd "C-c C-<backspace>")
273 'c-hungry-delete-forward)))
274
275 (if c-mode-base-map
276 nil
277
278 (setq c-mode-base-map (make-sparse-keymap))
279
280 ;; Separate M-BS from C-M-h. The former should remain
281 ;; backward-kill-word.
282 (define-key c-mode-base-map [(control meta h)] 'c-mark-function)
283 (define-key c-mode-base-map "\e\C-q" 'c-indent-exp)
284 (substitute-key-definition 'backward-sentence
285 'c-beginning-of-statement
286 c-mode-base-map global-map)
287 (substitute-key-definition 'forward-sentence
288 'c-end-of-statement
289 c-mode-base-map global-map)
290 (substitute-key-definition 'indent-new-comment-line
291 'c-indent-new-comment-line
292 c-mode-base-map global-map)
293 (substitute-key-definition 'indent-for-tab-command
294 ;; XXX Is this the right thing to do
295 ;; here?
296 'c-indent-line-or-region
297 c-mode-base-map global-map)
298 (when (fboundp 'comment-indent-new-line)
299 ;; indent-new-comment-line has changed name to
300 ;; comment-indent-new-line in Emacs 21.
301 (substitute-key-definition 'comment-indent-new-line
302 'c-indent-new-comment-line
303 c-mode-base-map global-map))
304
305 ;; RMS says don't make these the default.
306 ;; (April 2006): RMS has now approved these commands as defaults.
307 (unless (memq 'argumentative-bod-function c-emacs-features)
308 (define-key c-mode-base-map "\e\C-a" 'c-beginning-of-defun)
309 (define-key c-mode-base-map "\e\C-e" 'c-end-of-defun))
310
311 (define-key c-mode-base-map "\C-c\C-n" 'c-forward-conditional)
312 (define-key c-mode-base-map "\C-c\C-p" 'c-backward-conditional)
313 (define-key c-mode-base-map "\C-c\C-u" 'c-up-conditional)
314
315 ;; It doesn't suffice to put `c-fill-paragraph' on
316 ;; `fill-paragraph-function' since `c-fill-paragraph' must be called
317 ;; before any fill prefix adaption is done. E.g. `filladapt-mode'
318 ;; replaces `fill-paragraph' and does the adaption before calling
319 ;; `fill-paragraph-function', and we have to mask comments etc
320 ;; before that. Also, `c-fill-paragraph' chains on to
321 ;; `fill-paragraph' and the value on `fill-paragraph-function' to
322 ;; do the actual filling work.
323 (substitute-key-definition 'fill-paragraph 'c-fill-paragraph
324 c-mode-base-map global-map)
325 ;; In XEmacs the default fill function is called
326 ;; fill-paragraph-or-region.
327 (substitute-key-definition 'fill-paragraph-or-region 'c-fill-paragraph
328 c-mode-base-map global-map)
329
330 ;; We bind the forward deletion key and (implicitly) C-d to
331 ;; `c-electric-delete-forward', and the backward deletion key to
332 ;; `c-electric-backspace'. The hungry variants are bound to the
333 ;; same keys but prefixed with C-c. This implies that C-c C-d is
334 ;; `c-hungry-delete-forward'. For consistency, we bind not only C-c
335 ;; <backspace> to `c-hungry-delete-backwards' but also
336 ;; C-c C-<backspace>, so that the Ctrl key can be held down during
337 ;; the whole sequence regardless of the direction. This in turn
338 ;; implies that we bind C-c C-<delete> to `c-hungry-delete-forward',
339 ;; for the same reason.
340
341 ;; Bind the electric deletion functions to C-d and DEL. Emacs 21
342 ;; automatically maps the [delete] and [backspace] keys to these two
343 ;; depending on window system and user preferences. (In earlier
344 ;; versions it's possible to do the same by using `function-key-map'.)
345 (define-key c-mode-base-map "\C-d" 'c-electric-delete-forward)
346 (define-key c-mode-base-map "\177" 'c-electric-backspace)
347 (define-key c-mode-base-map "\C-c\C-d" 'c-hungry-delete-forward)
348 (define-key c-mode-base-map [?\C-c ?\d] 'c-hungry-delete-backwards)
349 (define-key c-mode-base-map [?\C-c ?\C-\d] 'c-hungry-delete-backwards)
350 (define-key c-mode-base-map [?\C-c deletechar] 'c-hungry-delete-forward) ; C-c <delete> on a tty.
351 (define-key c-mode-base-map [?\C-c (control deletechar)] ; C-c C-<delete> on a tty.
352 'c-hungry-delete-forward)
353 (when (boundp 'normal-erase-is-backspace)
354 ;; The automatic C-d and DEL mapping functionality doesn't extend
355 ;; to special combinations like C-c C-<delete>, so we have to hook
356 ;; into the `normal-erase-is-backspace' system to bind it directly
357 ;; as appropriate.
358 (add-hook 'normal-erase-is-backspace-hook 'c-bind-special-erase-keys)
359 (c-bind-special-erase-keys))
360
361 (when (fboundp 'delete-forward-p)
362 ;; In XEmacs we fix the forward and backward deletion behavior by
363 ;; binding the keysyms for the [delete] and [backspace] keys
364 ;; directly, and use `delete-forward-p' to decide what [delete]
365 ;; should do. That's done in the XEmacs specific
366 ;; `c-electric-delete' and `c-hungry-delete' functions.
367 (define-key c-mode-base-map [delete] 'c-electric-delete)
368 (define-key c-mode-base-map [backspace] 'c-electric-backspace)
369 (define-key c-mode-base-map (kbd "C-c <delete>") 'c-hungry-delete)
370 (define-key c-mode-base-map (kbd "C-c C-<delete>") 'c-hungry-delete)
371 (define-key c-mode-base-map (kbd "C-c <backspace>")
372 'c-hungry-delete-backwards)
373 (define-key c-mode-base-map (kbd "C-c C-<backspace>")
374 'c-hungry-delete-backwards))
375
376 (define-key c-mode-base-map "#" 'c-electric-pound)
377 (define-key c-mode-base-map "{" 'c-electric-brace)
378 (define-key c-mode-base-map "}" 'c-electric-brace)
379 (define-key c-mode-base-map "/" 'c-electric-slash)
380 (define-key c-mode-base-map "*" 'c-electric-star)
381 (define-key c-mode-base-map ";" 'c-electric-semi&comma)
382 (define-key c-mode-base-map "," 'c-electric-semi&comma)
383 (define-key c-mode-base-map ":" 'c-electric-colon)
384 (define-key c-mode-base-map "(" 'c-electric-paren)
385 (define-key c-mode-base-map ")" 'c-electric-paren)
386
387 (define-key c-mode-base-map "\C-c\C-\\" 'c-backslash-region)
388 (define-key c-mode-base-map "\C-c\C-a" 'c-toggle-auto-newline)
389 (define-key c-mode-base-map "\C-c\C-b" 'c-submit-bug-report)
390 (define-key c-mode-base-map "\C-c\C-c" 'comment-region)
391 (define-key c-mode-base-map "\C-c\C-l" 'c-toggle-electric-state)
392 (define-key c-mode-base-map "\C-c\C-o" 'c-set-offset)
393 (define-key c-mode-base-map "\C-c\C-q" 'c-indent-defun)
394 (define-key c-mode-base-map "\C-c\C-s" 'c-show-syntactic-information)
395 ;; (define-key c-mode-base-map "\C-c\C-t" 'c-toggle-auto-hungry-state) Commented out by ACM, 2005-03-05.
396 (define-key c-mode-base-map "\C-c." 'c-set-style)
397 ;; conflicts with OOBR
398 ;;(define-key c-mode-base-map "\C-c\C-v" 'c-version)
399 ;; (define-key c-mode-base-map "\C-c\C-y" 'c-toggle-hungry-state) Commented out by ACM, 2005-11-22.
400 (define-key c-mode-base-map "\C-c\C-w" 'c-subword-mode)
401 )
402
403 ;; We don't require the outline package, but we configure it a bit anyway.
404 (cc-bytecomp-defvar outline-level)
405
406 (defun c-mode-menu (modestr)
407 "Return a menu spec suitable for `easy-menu-define' that is exactly
408 like the C mode menu except that the menu bar item name is MODESTR
409 instead of \"C\".
410
411 This function is provided for compatibility only; derived modes should
412 preferably use the `c-mode-menu' language constant directly."
413 (cons modestr (c-lang-const c-mode-menu c)))
414
415 ;; Ugly hack to pull in the definition of `c-populate-syntax-table'
416 ;; from cc-langs to make it available at runtime. It's either this or
417 ;; moving the definition for it to cc-defs, but that would mean to
418 ;; break up the syntax table setup over two files.
419 (defalias 'c-populate-syntax-table
420 (cc-eval-when-compile
421 (let ((f (symbol-function 'c-populate-syntax-table)))
422 (if (byte-code-function-p f) f (byte-compile f)))))
423
424 ;; CAUTION: Try to avoid installing things on
425 ;; `before-change-functions'. The macro `combine-after-change-calls'
426 ;; is used and it doesn't work if there are things on that hook. That
427 ;; can cause font lock functions to run in inconvenient places during
428 ;; temporary changes in some font lock support modes, causing extra
429 ;; unnecessary work and font lock glitches due to interactions between
430 ;; various text properties.
431 ;;
432 ;; (2007-02-12): The macro `combine-after-change-calls' ISN'T used any
433 ;; more.
434
435 (defun c-unfind-enclosing-token (pos)
436 ;; If POS is wholly inside a token, remove that id from
437 ;; `c-found-types', should it be present. Return t if we were in an
438 ;; id, else nil.
439 (save-excursion
440 (let ((tok-beg (progn (goto-char pos)
441 (and (c-beginning-of-current-token) (point))))
442 (tok-end (progn (goto-char pos)
443 (and (c-end-of-current-token) (point)))))
444 (when (and tok-beg tok-end)
445 (c-unfind-type (buffer-substring-no-properties tok-beg tok-end))
446 t))))
447
448 (defun c-unfind-coalesced-tokens (beg end)
449 ;; unless the non-empty region (beg end) is entirely WS and there's at
450 ;; least one character of WS just before or after this region, remove
451 ;; the tokens which touch the region from `c-found-types' should they
452 ;; be present.
453 (or (c-partial-ws-p beg end)
454 (save-excursion
455 (progn
456 (goto-char beg)
457 (or (eq beg (point-min))
458 (c-skip-ws-backward (1- beg))
459 (/= (point) beg)
460 (= (c-backward-token-2) 1)
461 (c-unfind-type (buffer-substring-no-properties
462 (point) beg)))
463 (goto-char end)
464 (or (eq end (point-max))
465 (c-skip-ws-forward (1+ end))
466 (/= (point) end)
467 (progn (forward-char) (c-end-of-current-token) nil)
468 (c-unfind-type (buffer-substring-no-properties
469 end (point))))))))
470
471 ;; c-maybe-stale-found-type records a place near the region being
472 ;; changed where an element of `found-types' might become stale. It
473 ;; is set in c-before-change and is either nil, or has the form:
474 ;;
475 ;; (c-decl-id-start "foo" 97 107 " (* ooka) " "o"), where
476 ;;
477 ;; o - `c-decl-id-start' is the c-type text property value at buffer
478 ;; pos 96.
479 ;;
480 ;; o - 97 107 is the region potentially containing the stale type -
481 ;; this is delimited by a non-nil c-type text property at 96 and
482 ;; either another one or a ";", "{", or "}" at 107.
483 ;;
484 ;; o - " (* ooka) " is the (before change) buffer portion containing
485 ;; the suspect type (here "ooka").
486 ;;
487 ;; o - "o" is the buffer contents which is about to be deleted. This
488 ;; would be the empty string for an insertion.
489 (defvar c-maybe-stale-found-type nil)
490 (make-variable-buffer-local 'c-maybe-stale-found-type)
491
492 (defvar c-just-done-before-change nil)
493 (make-variable-buffer-local 'c-just-done-before-change)
494 ;; This variable is set to t by `c-before-change' and to nil by
495 ;; `c-after-change'. It is used to detect a spurious invocation of
496 ;; `before-change-functions' directly following on from a correct one. This
497 ;; happens in some Emacsen, for example when `basic-save-buffer' does (insert
498 ;; ?\n) when `require-final-newline' is non-nil.
499
500 (defun c-basic-common-init (mode default-style)
501 "Do the necessary initialization for the syntax handling routines
502 and the line breaking/filling code. Intended to be used by other
503 packages that embed CC Mode.
504
505 MODE is the CC Mode flavor to set up, e.g. `c-mode' or `java-mode'.
506 DEFAULT-STYLE tells which indentation style to install. It has the
507 same format as `c-default-style'.
508
509 Note that `c-init-language-vars' must be called before this function.
510 This function cannot do that since `c-init-language-vars' is a macro
511 that requires a literal mode spec at compile time."
512
513 (setq c-buffer-is-cc-mode mode)
514
515 ;; these variables should always be buffer local; they do not affect
516 ;; indentation style.
517 (make-local-variable 'comment-start)
518 (make-local-variable 'comment-end)
519 (make-local-variable 'comment-start-skip)
520
521 (make-local-variable 'paragraph-start)
522 (make-local-variable 'paragraph-separate)
523 (make-local-variable 'paragraph-ignore-fill-prefix)
524 (make-local-variable 'adaptive-fill-mode)
525 (make-local-variable 'adaptive-fill-regexp)
526 (make-local-variable 'fill-paragraph-handle-comment)
527
528 ;; now set their values
529 (set (make-local-variable 'parse-sexp-ignore-comments) t)
530 (set (make-local-variable 'indent-line-function) 'c-indent-line)
531 (set (make-local-variable 'indent-region-function) 'c-indent-region)
532 (set (make-local-variable 'normal-auto-fill-function) 'c-do-auto-fill)
533 (set (make-local-variable 'comment-multi-line) t)
534 (set (make-local-variable 'comment-line-break-function)
535 'c-indent-new-comment-line)
536
537 ;; Prevent time-wasting activity on C-y.
538 (when (boundp 'yank-handled-properties)
539 (make-local-variable 'yank-handled-properties)
540 (let ((yank-cat-handler (assq 'category yank-handled-properties)))
541 (when yank-cat-handler
542 (setq yank-handled-properties (remq yank-cat-handler
543 yank-handled-properties)))))
544
545 ;; For the benefit of adaptive file, which otherwise mis-fills.
546 (setq fill-paragraph-handle-comment nil)
547
548 ;; Install `c-fill-paragraph' on `fill-paragraph-function' so that a
549 ;; direct call to `fill-paragraph' behaves better. This still
550 ;; doesn't work with filladapt but it's better than nothing.
551 (set (make-local-variable 'fill-paragraph-function) 'c-fill-paragraph)
552
553 ;; Initialize the cache of brace pairs, and opening braces/brackets/parens.
554 (c-state-cache-init)
555
556 (when (or c-recognize-<>-arglists
557 (c-major-mode-is 'awk-mode)
558 (c-major-mode-is '(java-mode c-mode c++-mode objc-mode)))
559 ;; We'll use the syntax-table text property to change the syntax
560 ;; of some chars for this language, so do the necessary setup for
561 ;; that.
562 ;;
563 ;; Note to other package developers: It's ok to turn this on in CC
564 ;; Mode buffers when CC Mode doesn't, but it's not ok to turn it
565 ;; off if CC Mode has turned it on.
566
567 ;; Emacs.
568 (when (boundp 'parse-sexp-lookup-properties)
569 (set (make-local-variable 'parse-sexp-lookup-properties) t))
570
571 ;; Same as above for XEmacs.
572 (when (boundp 'lookup-syntax-properties)
573 (set (make-local-variable 'lookup-syntax-properties) t)))
574
575 ;; Use this in Emacs 21+ to avoid meddling with the rear-nonsticky
576 ;; property on each character.
577 (when (boundp 'text-property-default-nonsticky)
578 (make-local-variable 'text-property-default-nonsticky)
579 (mapc (lambda (tprop)
580 (unless (assq tprop text-property-default-nonsticky)
581 (setq text-property-default-nonsticky
582 (cons `(,tprop . t) text-property-default-nonsticky))))
583 '(syntax-table category c-type)))
584
585 ;; In Emacs 21 and later it's possible to turn off the ad-hoc
586 ;; heuristic that open parens in column 0 are defun starters. Since
587 ;; we have c-state-cache, that heuristic isn't useful and only causes
588 ;; trouble, so turn it off.
589 ;; 2006/12/17: This facility is somewhat confused, and doesn't really seem
590 ;; helpful. Comment it out for now.
591 ;; (when (memq 'col-0-paren c-emacs-features)
592 ;; (make-local-variable 'open-paren-in-column-0-is-defun-start)
593 ;; (setq open-paren-in-column-0-is-defun-start nil))
594
595 (c-clear-found-types)
596
597 ;; now set the mode style based on default-style
598 (let ((style (cc-choose-style-for-mode mode default-style)))
599 ;; Override style variables if `c-old-style-variable-behavior' is
600 ;; set. Also override if we are using global style variables,
601 ;; have already initialized a style once, and are switching to a
602 ;; different style. (It's doubtful whether this is desirable, but
603 ;; the whole situation with nonlocal style variables is a bit
604 ;; awkward. It's at least the most compatible way with the old
605 ;; style init procedure.)
606 (c-set-style style (not (or c-old-style-variable-behavior
607 (and (not c-style-variables-are-local-p)
608 c-indentation-style
609 (not (string-equal c-indentation-style
610 style)))))))
611 (c-setup-paragraph-variables)
612
613 ;; we have to do something special for c-offsets-alist so that the
614 ;; buffer local value has its own alist structure.
615 (setq c-offsets-alist (copy-alist c-offsets-alist))
616
617 ;; setup the comment indent variable in a Emacs version portable way
618 (set (make-local-variable 'comment-indent-function) 'c-comment-indent)
619
620 ;; In Emacs 24.4 onwards, prevent Emacs's built in electric indentation from
621 ;; messing up CC Mode's, and set `c-electric-flag' if `electric-indent-mode'
622 ;; has been called by the user.
623 (when (boundp 'electric-indent-inhibit) (setq electric-indent-inhibit t))
624 ;; CC-mode should obey Emacs's generic preferences, tho only do it if
625 ;; Emacs's generic preferences can be set per-buffer (Emacs>=24.4).
626 (when (fboundp 'electric-indent-local-mode)
627 (setq c-electric-flag electric-indent-mode))
628
629 ;; ;; Put submode indicators onto minor-mode-alist, but only once.
630 ;; (or (assq 'c-submode-indicators minor-mode-alist)
631 ;; (setq minor-mode-alist
632 ;; (cons '(c-submode-indicators c-submode-indicators)
633 ;; minor-mode-alist)))
634 (c-update-modeline)
635
636 ;; Install the functions that ensure that various internal caches
637 ;; don't become invalid due to buffer changes.
638 (when (featurep 'xemacs)
639 (make-local-hook 'before-change-functions)
640 (make-local-hook 'after-change-functions))
641 (add-hook 'before-change-functions 'c-before-change nil t)
642 (setq c-just-done-before-change nil)
643 (add-hook 'after-change-functions 'c-after-change nil t)
644 (when (boundp 'font-lock-extend-after-change-region-function)
645 (set (make-local-variable 'font-lock-extend-after-change-region-function)
646 'c-extend-after-change-region))) ; Currently (2009-05) used by all
647 ; languages with #define (C, C++,; ObjC), and by AWK.
648
649 (defun c-setup-doc-comment-style ()
650 "Initialize the variables that depend on the value of `c-doc-comment-style'."
651 (when (and (featurep 'font-lock)
652 (symbol-value 'font-lock-mode))
653 ;; Force font lock mode to reinitialize itself.
654 (font-lock-mode 0)
655 (font-lock-mode 1)))
656
657 ;; Buffer local variables defining the region to be fontified by a font lock
658 ;; after-change function. They are initialized in c-before-change to
659 ;; before-change-functions' BEG and END. `c-new-END' is amended in
660 ;; c-after-change with after-change-functions' BEG, END, and OLD-LEN. These
661 ;; variables may be modified by any before/after-change function, in
662 ;; particular by functions in `c-get-state-before-change-functions' and
663 ;; `c-before-font-lock-functions'.
664 (defvar c-new-BEG 0)
665 (make-variable-buffer-local 'c-new-BEG)
666 (defvar c-new-END 0)
667 (make-variable-buffer-local 'c-new-END)
668 ;; The following two variables record the values of `c-new-BEG' and
669 ;; `c-new-END' just after `c-new-END' has been adjusted for the length of text
670 ;; inserted or removed. They may be read by any after-change function (but
671 ;; should not be altered by one).
672 (defvar c-old-BEG 0)
673 (make-variable-buffer-local 'c-old-BEG)
674 (defvar c-old-END 0)
675 (make-variable-buffer-local 'c-old-END)
676
677 (defun c-common-init (&optional mode)
678 "Common initialization for all CC Mode modes.
679 In addition to the work done by `c-basic-common-init' and
680 `c-font-lock-init', this function sets up various other things as
681 customary in CC Mode modes but which aren't strictly necessary for CC
682 Mode to operate correctly.
683
684 MODE is the symbol for the mode to initialize, like `c-mode'. See
685 `c-basic-common-init' for details. It's only optional to be
686 compatible with old code; callers should always specify it."
687
688 (unless mode
689 ;; Called from an old third party package. The fallback is to
690 ;; initialize for C.
691 (c-init-language-vars-for 'c-mode))
692
693 (c-basic-common-init mode c-default-style)
694 (when mode
695 ;; Only initialize font locking if we aren't called from an old package.
696 (c-font-lock-init))
697
698 ;; Starting a mode is a sort of "change". So call the change functions...
699 (save-restriction
700 (widen)
701 (setq c-new-BEG (point-min))
702 (setq c-new-END (point-max))
703 (save-excursion
704 (let (before-change-functions after-change-functions)
705 (mapc (lambda (fn)
706 (funcall fn (point-min) (point-max)))
707 c-get-state-before-change-functions)
708 (mapc (lambda (fn)
709 (funcall fn (point-min) (point-max)
710 (- (point-max) (point-min))))
711 c-before-font-lock-functions))))
712
713 (set (make-local-variable 'outline-regexp) "[^#\n\^M]")
714 (set (make-local-variable 'outline-level) 'c-outline-level)
715 (set (make-local-variable 'add-log-current-defun-function)
716 (lambda ()
717 (or (c-cpp-define-name) (c-defun-name))))
718 (let ((rfn (assq mode c-require-final-newline)))
719 (when rfn
720 (if (boundp 'mode-require-final-newline)
721 (and (cdr rfn)
722 (set (make-local-variable 'require-final-newline)
723 mode-require-final-newline))
724 (set (make-local-variable 'require-final-newline) (cdr rfn))))))
725
726 (defun c-count-cfss (lv-alist)
727 ;; LV-ALIST is an alist like `file-local-variables-alist'. Count how many
728 ;; elements with the key `c-file-style' there are in it.
729 (let ((elt-ptr lv-alist) elt (cownt 0))
730 (while elt-ptr
731 (setq elt (car elt-ptr)
732 elt-ptr (cdr elt-ptr))
733 (when (eq (car elt) 'c-file-style)
734 (setq cownt (1+ cownt))))
735 cownt))
736
737 (defun c-before-hack-hook ()
738 "Set the CC Mode style and \"offsets\" when in the buffer's local variables.
739 They are set only when, respectively, the pseudo variables
740 `c-file-style' and `c-file-offsets' are present in the list.
741
742 This function is called from the hook `before-hack-local-variables-hook'."
743 (when c-buffer-is-cc-mode
744 (let ((mode-cons (assq 'mode file-local-variables-alist))
745 (stile (cdr (assq 'c-file-style file-local-variables-alist)))
746 (offsets (cdr (assq 'c-file-offsets file-local-variables-alist))))
747 (when mode-cons
748 (hack-one-local-variable (car mode-cons) (cdr mode-cons))
749 (setq file-local-variables-alist
750 (delq mode-cons file-local-variables-alist)))
751 (when stile
752 (or (stringp stile) (error "c-file-style is not a string"))
753 (if (boundp 'dir-local-variables-alist)
754 ;; Determine whether `c-file-style' was set in the file's local
755 ;; variables or in a .dir-locals.el (a directory setting).
756 (let ((cfs-in-file-and-dir-count
757 (c-count-cfss file-local-variables-alist))
758 (cfs-in-dir-count (c-count-cfss dir-local-variables-alist)))
759 (c-set-style stile
760 (and (= cfs-in-file-and-dir-count cfs-in-dir-count)
761 'keep-defaults)))
762 (c-set-style stile)))
763 (when offsets
764 (mapc
765 (lambda (langentry)
766 (let ((langelem (car langentry))
767 (offset (cdr langentry)))
768 (c-set-offset langelem offset)))
769 offsets)))))
770
771 (defun c-remove-any-local-eval-or-mode-variables ()
772 ;; If the buffer specifies `mode' or `eval' in its File Local Variable list
773 ;; or on the first line, remove all occurrences. See
774 ;; `c-postprocess-file-styles' for justification. There is no need to save
775 ;; point here, or even bother too much about the buffer contents. However,
776 ;; DON'T mess up the kill-ring.
777 ;;
778 ;; Most of the code here is derived from Emacs 21.3's `hack-local-variables'
779 ;; in files.el.
780 (goto-char (point-max))
781 (search-backward "\n\^L" (max (- (point-max) 3000) (point-min)) 'move)
782 (let (lv-point (prefix "") (suffix ""))
783 (when (let ((case-fold-search t))
784 (search-forward "Local Variables:" nil t))
785 (setq lv-point (point))
786 ;; The prefix is what comes before "local variables:" in its line.
787 ;; The suffix is what comes after "local variables:" in its line.
788 (skip-chars-forward " \t")
789 (or (eolp)
790 (setq suffix (buffer-substring (point)
791 (progn (end-of-line) (point)))))
792 (goto-char (match-beginning 0))
793 (or (bolp)
794 (setq prefix
795 (buffer-substring (point)
796 (progn (beginning-of-line) (point)))))
797
798 (while (search-forward-regexp
799 (concat "^[ \t]*"
800 (regexp-quote prefix)
801 "\\(mode\\|eval\\):.*"
802 (regexp-quote suffix)
803 "$")
804 nil t)
805 (forward-line 0)
806 (delete-region (point) (progn (forward-line) (point)))))
807
808 ;; Delete the first line, if we've got one, in case it contains a mode spec.
809 (unless (and lv-point
810 (progn (goto-char lv-point)
811 (forward-line 0)
812 (bobp)))
813 (goto-char (point-min))
814 (unless (eobp)
815 (delete-region (point) (progn (forward-line) (point)))))))
816
817 (defun c-postprocess-file-styles ()
818 "Function that post processes relevant file local variables in CC Mode.
819 Currently, this function simply applies any style and offset settings
820 found in the file's Local Variable list. It first applies any style
821 setting found in `c-file-style', then it applies any offset settings
822 it finds in `c-file-offsets'.
823
824 Note that the style variables are always made local to the buffer."
825
826 ;; apply file styles and offsets
827 (when c-buffer-is-cc-mode
828 (if (or c-file-style c-file-offsets)
829 (c-make-styles-buffer-local t))
830 (when c-file-style
831 (or (stringp c-file-style)
832 (error "c-file-style is not a string"))
833 (c-set-style c-file-style))
834
835 (and c-file-offsets
836 (mapc
837 (lambda (langentry)
838 (let ((langelem (car langentry))
839 (offset (cdr langentry)))
840 (c-set-offset langelem offset)))
841 c-file-offsets))
842 ;; Problem: The file local variable block might have explicitly set a
843 ;; style variable. The `c-set-style' or `mapcar' call might have
844 ;; overwritten this. So we run `hack-local-variables' again to remedy
845 ;; this. There are no guarantees this will work properly, particularly as
846 ;; we have no control over what the other hook functions on
847 ;; `hack-local-variables-hook' would have done. We now (2006/2/1) remove
848 ;; any `eval' or `mode' expressions before we evaluate again (see below).
849 ;; ACM, 2005/11/2.
850 ;;
851 ;; Problem (bug reported by Gustav Broberg): if one of the variables is
852 ;; `mode', this will invoke c-mode (etc.) again, setting up the style etc.
853 ;; We prevent this by temporarily removing `mode' from the Local Variables
854 ;; section.
855 (if (or c-file-style c-file-offsets)
856 (let ((hack-local-variables-hook nil) (inhibit-read-only t))
857 (c-tentative-buffer-changes
858 (c-remove-any-local-eval-or-mode-variables)
859 (hack-local-variables))
860 nil))))
861
862 (if (boundp 'before-hack-local-variables-hook)
863 (add-hook 'before-hack-local-variables-hook 'c-before-hack-hook)
864 (add-hook 'hack-local-variables-hook 'c-postprocess-file-styles))
865
866 (defmacro c-run-mode-hooks (&rest hooks)
867 ;; Emacs 21.1 has introduced a system with delayed mode hooks that
868 ;; requires the use of the new function `run-mode-hooks'.
869 (if (cc-bytecomp-fboundp 'run-mode-hooks)
870 `(run-mode-hooks ,@hooks)
871 `(progn ,@(mapcar (lambda (hook) `(run-hooks ,hook)) hooks))))
872
873 \f
874 ;;; Change hooks, linking with Font Lock and electric-indent-mode.
875
876 (defun c-called-from-text-property-change-p ()
877 ;; Is the primitive which invoked `before-change-functions' or
878 ;; `after-change-functions' one which merely changes text properties? This
879 ;; function must be called directly from a member of one of the above hooks.
880 ;;
881 ;; In the following call, frame 0 is `backtrace-frame', frame 1 is
882 ;; `c-called-from-text-property-change-p', frame 2 is
883 ;; `c-before/after-change', frame 3 is the primitive invoking the change
884 ;; hook.
885 (memq (cadr (backtrace-frame 3))
886 '(put-text-property remove-list-of-text-properties)))
887
888 (defun c-depropertize-CPP (beg end)
889 ;; Remove the punctuation syntax-table text property from the CPP parts of
890 ;; (c-new-BEG c-new-END).
891 ;;
892 ;; This function is in the C/C++/ObjC values of
893 ;; `c-get-state-before-change-functions' and is called exclusively as a
894 ;; before change function.
895 (c-save-buffer-state ()
896 (goto-char c-new-BEG)
897 (while (and (< (point) beg)
898 (search-forward-regexp c-anchored-cpp-prefix beg t))
899 (goto-char (match-beginning 1))
900 (let ((m-beg (point)))
901 (c-end-of-macro)
902 (c-clear-char-property-with-value
903 m-beg (min (point) beg) 'syntax-table '(1))))
904
905 (goto-char end)
906 (while (and (< (point) c-new-END)
907 (search-forward-regexp c-anchored-cpp-prefix c-new-END t))
908 (goto-char (match-beginning 1))
909 (let ((m-beg (point)))
910 (c-end-of-macro)
911 (c-clear-char-property-with-value
912 m-beg (min (point) c-new-END) 'syntax-table '(1))))))
913
914 (defun c-extend-region-for-CPP (beg end)
915 ;; Adjust `c-new-BEG', `c-new-END' respectively to the beginning and end of
916 ;; any preprocessor construct they may be in.
917 ;;
918 ;; Point is undefined both before and after this function call; the buffer
919 ;; has already been widened, and match-data saved. The return value is
920 ;; meaningless.
921 ;;
922 ;; This function is in the C/C++/ObjC values of
923 ;; `c-get-state-before-change-functions' and is called exclusively as a
924 ;; before change function.
925 (goto-char c-new-BEG)
926 (c-beginning-of-macro)
927 (setq c-new-BEG (point))
928
929 (goto-char c-new-END)
930 (when (c-beginning-of-macro)
931 (c-end-of-macro)
932 (or (eobp) (forward-char))) ; Over the terminating NL which may be marked
933 ; with a c-cpp-delimiter category property
934 (setq c-new-END (point)))
935
936 (defun c-depropertize-new-text (beg end old-len)
937 ;; Remove from the new text in (BEG END) any and all text properties which
938 ;; might interfere with CC Mode's proper working.
939 ;;
940 ;; This function is called exclusively as an after-change function. It
941 ;; appears in the value (for all languages) of
942 ;; `c-before-font-lock-functions'. The value of point is undefined both on
943 ;; entry and exit, and the return value has no significance. The parameters
944 ;; BEG, END, and OLD-LEN are the standard ones supplied to all after-change
945 ;; functions.
946 (c-save-buffer-state ()
947 (when (> end beg)
948 (c-clear-char-properties beg end 'syntax-table)
949 (c-clear-char-properties beg end 'category)
950 (c-clear-char-properties beg end 'c-is-sws)
951 (c-clear-char-properties beg end 'c-in-sws)
952 (c-clear-char-properties beg end 'c-type)
953 (c-clear-char-properties beg end 'c-awk-NL-prop))))
954
955 (defun c-extend-font-lock-region-for-macros (begg endd old-len)
956 ;; Extend the region (c-new-BEG c-new-END) to cover all (possibly changed)
957 ;; preprocessor macros; The return value has no significance.
958 ;;
959 ;; Point is undefined on both entry and exit to this function. The buffer
960 ;; will have been widened on entry.
961 ;;
962 ;; This function is in the C/C++/ObjC value of `c-before-font-lock-functions'.
963 (goto-char endd)
964 (if (c-beginning-of-macro)
965 (c-end-of-macro))
966 (setq c-new-END (max endd c-new-END (point)))
967 ;; Determine the region, (c-new-BEG c-new-END), which will get font
968 ;; locked. This restricts the region should there be long macros.
969 (setq c-new-BEG (max c-new-BEG (c-determine-limit 500 begg))
970 c-new-END (min c-new-END (c-determine-+ve-limit 500 endd))))
971
972 (defun c-neutralize-CPP-line (beg end)
973 ;; BEG and END bound a region, typically a preprocessor line. Put a
974 ;; "punctuation" syntax-table property on syntactically obtrusive
975 ;; characters, ones which would interact syntactically with stuff outside
976 ;; this region.
977 ;;
978 ;; These are unmatched string delimiters, or unmatched
979 ;; parens/brackets/braces. An unclosed comment is regarded as valid, NOT
980 ;; obtrusive.
981 (save-excursion
982 (let (s)
983 (while
984 (progn
985 (setq s (parse-partial-sexp beg end -1))
986 (cond
987 ((< (nth 0 s) 0) ; found an unmated ),},]
988 (c-put-char-property (1- (point)) 'syntax-table '(1))
989 t)
990 ((nth 3 s) ; In a string
991 (c-put-char-property (nth 8 s) 'syntax-table '(1))
992 t)
993 ((> (nth 0 s) 0) ; In a (,{,[
994 (c-put-char-property (nth 1 s) 'syntax-table '(1))
995 t)
996 (t nil)))))))
997
998 (defun c-neutralize-syntax-in-and-mark-CPP (begg endd old-len)
999 ;; (i) "Neutralize" every preprocessor line wholly or partially in the
1000 ;; changed region. "Restore" lines which were CPP lines before the change
1001 ;; and are no longer so.
1002 ;;
1003 ;; (ii) Mark each CPP construct by placing a `category' property value
1004 ;; `c-cpp-delimiter' at its start and end. The marked characters are the
1005 ;; opening # and usually the terminating EOL, but sometimes the character
1006 ;; before a comment delimiter.
1007 ;;
1008 ;; That is, set syntax-table properties on characters that would otherwise
1009 ;; interact syntactically with those outside the CPP line(s).
1010 ;;
1011 ;; This function is called from an after-change function, BEGG ENDD and
1012 ;; OLD-LEN being the standard parameters. It prepares the buffer for font
1013 ;; locking, hence must get called before `font-lock-after-change-function'.
1014 ;;
1015 ;; Point is undefined both before and after this function call, the buffer
1016 ;; has been widened, and match-data saved. The return value is ignored.
1017 ;;
1018 ;; This function is in the C/C++/ObjC value of `c-before-font-lock-functions'.
1019 ;;
1020 ;; Note: SPEED _MATTERS_ IN THIS FUNCTION!!!
1021 ;;
1022 ;; This function might make hidden buffer changes.
1023 (c-save-buffer-state (limits)
1024 ;; Clear 'syntax-table properties "punctuation":
1025 ;; (c-clear-char-property-with-value c-new-BEG c-new-END 'syntax-table '(1))
1026
1027 ;; CPP "comment" markers:
1028 (if (eval-when-compile (memq 'category-properties c-emacs-features));Emacs.
1029 (c-clear-char-property-with-value
1030 c-new-BEG c-new-END 'category 'c-cpp-delimiter))
1031 ;; FIXME!!! What about the "<" and ">" category properties? 2009-11-16
1032
1033 ;; Add needed properties to each CPP construct in the region.
1034 (goto-char c-new-BEG)
1035 (if (setq limits (c-literal-limits)) ; Go past any literal.
1036 (goto-char (cdr limits)))
1037 (skip-chars-backward " \t")
1038 (let ((pps-position (point)) pps-state mbeg)
1039 (while (and (< (point) c-new-END)
1040 (search-forward-regexp c-anchored-cpp-prefix c-new-END t))
1041 ;; If we've found a "#" inside a macro/string/comment, ignore it.
1042 (unless
1043 (or (save-excursion
1044 (goto-char (match-beginning 0))
1045 (let ((here (point)))
1046 (and (save-match-data (c-beginning-of-macro))
1047 (< (point) here))))
1048 (progn
1049 (setq pps-state
1050 (parse-partial-sexp pps-position (point) nil nil pps-state)
1051 pps-position (point))
1052 (or (nth 3 pps-state) ; in a string?
1053 (nth 4 pps-state)))) ; in a comment?
1054 (goto-char (match-beginning 1))
1055 (setq mbeg (point))
1056 (if (> (c-no-comment-end-of-macro) mbeg)
1057 (progn
1058 (c-neutralize-CPP-line mbeg (point)) ; "punctuation" properties
1059 (if (eval-when-compile
1060 (memq 'category-properties c-emacs-features)) ;Emacs.
1061 (c-set-cpp-delimiters mbeg (point)))) ; "comment" markers
1062 (forward-line)) ; no infinite loop with, e.g., "#//"
1063 )))))
1064
1065 (defun c-before-after-change-digit-quote (beg end &optional old-len)
1066 ;; This function either removes or applies the punctuation value ('(1)) of
1067 ;; the `syntax-table' text property on single quote marks which are
1068 ;; separator characters in long integer literals, e.g. "4'294'967'295". It
1069 ;; applies to both decimal/octal and hex literals. (FIXME (2016-06-10): it
1070 ;; should also apply to binary literals.)
1071 ;;
1072 ;; In both uses of the function, the `syntax-table' properties are
1073 ;; removed/applied only on quote marks which appear to be digit separators.
1074 ;;
1075 ;; Point is undefined on both entry and exit to this function, and the
1076 ;; return value has no significance. The function is called solely as a
1077 ;; before-change function (see `c-get-state-before-change-functions') and as
1078 ;; an after change function (see `c-before-font-lock-functions', with the
1079 ;; parameters BEG, END, and (optionally) OLD-LEN being given the standard
1080 ;; values for before/after-change functions.
1081 (c-save-buffer-state ((num-begin c-new-BEG) digit-re try-end)
1082 (goto-char c-new-END)
1083 (when (looking-at "\\(x\\)?[0-9a-fA-F']+")
1084 (setq c-new-END (match-end 0)))
1085 (goto-char c-new-BEG)
1086 (when (looking-at "\\(x?\\)[0-9a-fA-F']")
1087 (if (re-search-backward "\\(0x\\)?[0-9a-fA-F]*\\=" nil t)
1088 (setq c-new-BEG (point))))
1089
1090 (while
1091 (re-search-forward "[0-9a-fA-F]'[0-9a-fA-F]" c-new-END t)
1092 (setq try-end (1- (point)))
1093 (re-search-backward "[^0-9a-fA-F']" num-begin t)
1094 (setq digit-re
1095 (cond
1096 ((and (not (bobp)) (eq (char-before) ?0) (memq (char-after) '(?x ?X)))
1097 "[0-9a-fA-F]")
1098 ((and (eq (char-after (1+ (point))) ?0)
1099 (memq (char-after (+ 2 (point))) '(?b ?B)))
1100 "[01]")
1101 ((memq (char-after (1+ (point))) '(?0 ?1 ?2 ?3 ?4 ?5 ?6 ?7 ?8 ?9))
1102 "[0-9]")
1103 (t nil)))
1104 (when digit-re
1105 (cond ((eq (char-after) ?x) (forward-char))
1106 ((looking-at ".?0[Bb]") (goto-char (match-end 0)))
1107 ((looking-at digit-re))
1108 (t (forward-char)))
1109 (when (not (c-in-literal))
1110 (let ((num-end ; End of valid sequence of digits/quotes.
1111 (save-excursion
1112 (re-search-forward
1113 (concat "\\=\\(" digit-re "+'\\)*" digit-re "+") nil t)
1114 (point))))
1115 (setq try-end ; End of sequence of digits/quotes
1116 (save-excursion
1117 (re-search-forward
1118 (concat "\\=\\(" digit-re "\\|'\\)+") nil t)
1119 (point)))
1120 (while (re-search-forward
1121 (concat digit-re "\\('\\)" digit-re) num-end t)
1122 (if old-len ; i.e. are we in an after-change function?
1123 (c-put-char-property (match-beginning 1) 'syntax-table '(1))
1124 (c-clear-char-property (match-beginning 1) 'syntax-table))
1125 (backward-char)))))
1126 (goto-char try-end)
1127 (setq num-begin (point)))))
1128
1129 (defun c-before-change (beg end)
1130 ;; Function to be put on `before-change-functions'. Primarily, this calls
1131 ;; the language dependent `c-get-state-before-change-functions'. It is
1132 ;; otherwise used only to remove stale entries from the `c-found-types'
1133 ;; cache, and to record entries which a `c-after-change' function might
1134 ;; confirm as stale.
1135 ;;
1136 ;; Note that this function must be FAST rather than accurate. Note
1137 ;; also that it only has any effect when font locking is enabled.
1138 ;; We exploit this by checking for font-lock-*-face instead of doing
1139 ;; rigorous syntactic analysis.
1140
1141 ;; If either change boundary is wholly inside an identifier, delete
1142 ;; it/them from the cache. Don't worry about being inside a string
1143 ;; or a comment - "wrongly" removing a symbol from `c-found-types'
1144 ;; isn't critical.
1145 (unless (or (c-called-from-text-property-change-p)
1146 c-just-done-before-change) ; guard against a spurious second
1147 ; invocation of before-change-functions.
1148 (setq c-just-done-before-change t)
1149 ;; (c-new-BEG c-new-END) will be the region to fontify.
1150 (setq c-new-BEG beg c-new-END end)
1151 (setq c-maybe-stale-found-type nil)
1152 (save-restriction
1153 (save-match-data
1154 (widen)
1155 (save-excursion
1156 ;; Are we inserting/deleting stuff in the middle of an identifier?
1157 (c-unfind-enclosing-token beg)
1158 (c-unfind-enclosing-token end)
1159 ;; Are we coalescing two tokens together, e.g. "fo o" -> "foo"?
1160 (when (< beg end)
1161 (c-unfind-coalesced-tokens beg end))
1162 ;; Are we (potentially) disrupting the syntactic context which
1163 ;; makes a type a type? E.g. by inserting stuff after "foo" in
1164 ;; "foo bar;", or before "foo" in "typedef foo *bar;"?
1165 ;;
1166 ;; We search for appropriate c-type properties "near" the change.
1167 ;; First, find an appropriate boundary for this property search.
1168 (let (lim
1169 type type-pos
1170 marked-id term-pos
1171 (end1
1172 (or (and (eq (get-text-property end 'face)
1173 'font-lock-comment-face)
1174 (previous-single-property-change end 'face))
1175 end)))
1176 (when (>= end1 beg) ; Don't hassle about changes entirely in comments.
1177 ;; Find a limit for the search for a `c-type' property
1178 (while
1179 (and (/= (skip-chars-backward "^;{}") 0)
1180 (> (point) (point-min))
1181 (memq (c-get-char-property (1- (point)) 'face)
1182 '(font-lock-comment-face font-lock-string-face))))
1183 (setq lim (max (point-min) (1- (point))))
1184
1185 ;; Look for the latest `c-type' property before end1
1186 (when (and (> end1 (point-min))
1187 (setq type-pos
1188 (if (get-text-property (1- end1) 'c-type)
1189 end1
1190 (previous-single-property-change end1 'c-type
1191 nil lim))))
1192 (setq type (get-text-property (max (1- type-pos) lim) 'c-type))
1193
1194 (when (memq type '(c-decl-id-start c-decl-type-start))
1195 ;; Get the identifier, if any, that the property is on.
1196 (goto-char (1- type-pos))
1197 (setq marked-id
1198 (when (looking-at "\\(\\sw\\|\\s_\\)")
1199 (c-beginning-of-current-token)
1200 (buffer-substring-no-properties (point) type-pos)))
1201
1202 (goto-char end1)
1203 (skip-chars-forward "^;{}") ;FIXME!!! loop for comment, maybe
1204 (setq lim (point))
1205 (setq term-pos
1206 (or (c-next-single-property-change end 'c-type nil lim)
1207 lim))
1208 (setq c-maybe-stale-found-type
1209 (list type marked-id
1210 type-pos term-pos
1211 (buffer-substring-no-properties type-pos
1212 term-pos)
1213 (buffer-substring-no-properties beg end)))))))
1214
1215 (if c-get-state-before-change-functions
1216 (mapc (lambda (fn)
1217 (funcall fn beg end))
1218 c-get-state-before-change-functions))
1219 )))
1220 ;; The following must be done here rather than in `c-after-change' because
1221 ;; newly inserted parens would foul up the invalidation algorithm.
1222 (c-invalidate-state-cache beg)))
1223
1224 (defvar c-in-after-change-fontification nil)
1225 (make-variable-buffer-local 'c-in-after-change-fontification)
1226 ;; A flag to prevent region expanding stuff being done twice for after-change
1227 ;; fontification.
1228
1229 (defun c-after-change (beg end old-len)
1230 ;; Function put on `after-change-functions' to adjust various caches
1231 ;; etc. Prefer speed to finesse here, since there will be an order
1232 ;; of magnitude more calls to this function than any of the
1233 ;; functions that use the caches.
1234 ;;
1235 ;; Note that care must be taken so that this is called before any
1236 ;; font-lock callbacks since we might get calls to functions using
1237 ;; these caches from inside them, and we must thus be sure that this
1238 ;; has already been executed.
1239 ;;
1240 ;; This calls the language variable c-before-font-lock-functions, if non nil.
1241 ;; This typically sets `syntax-table' properties.
1242
1243 ;; (c-new-BEG c-new-END) will be the region to fontify. It may become
1244 ;; larger than (beg end).
1245 (setq c-new-END (- (+ c-new-END (- end beg)) old-len))
1246 (setq c-old-BEG c-new-BEG c-old-END c-new-END)
1247
1248 (unless (c-called-from-text-property-change-p)
1249 (setq c-just-done-before-change nil)
1250 (c-save-buffer-state (case-fold-search)
1251 ;; When `combine-after-change-calls' is used we might get calls
1252 ;; with regions outside the current narrowing. This has been
1253 ;; observed in Emacs 20.7.
1254 (save-restriction
1255 (save-match-data ; c-recognize-<>-arglists changes match-data
1256 (widen)
1257
1258 (when (> end (point-max))
1259 ;; Some emacsen might return positions past the end. This has been
1260 ;; observed in Emacs 20.7 when rereading a buffer changed on disk
1261 ;; (haven't been able to minimize it, but Emacs 21.3 appears to
1262 ;; work).
1263 (setq end (point-max))
1264 (when (> beg end)
1265 (setq beg end)))
1266
1267 ;; C-y is capable of spuriously converting category properties
1268 ;; c-</>-as-paren-syntax and c-cpp-delimiter into hard syntax-table
1269 ;; properties. Remove these when it happens.
1270 (when (eval-when-compile (memq 'category-properties c-emacs-features))
1271 (c-save-buffer-state ()
1272 (c-clear-char-property-with-value beg end 'syntax-table
1273 c-<-as-paren-syntax)
1274 (c-clear-char-property-with-value beg end 'syntax-table
1275 c->-as-paren-syntax)
1276 (c-clear-char-property-with-value beg end 'syntax-table nil)))
1277
1278 (c-trim-found-types beg end old-len) ; maybe we don't need all of these.
1279 (c-invalidate-sws-region-after beg end)
1280 ;; (c-invalidate-state-cache beg) ; moved to `c-before-change'.
1281 (c-invalidate-find-decl-cache beg)
1282
1283 (when c-recognize-<>-arglists
1284 (c-after-change-check-<>-operators beg end))
1285
1286 (setq c-in-after-change-fontification t)
1287 (save-excursion
1288 (mapc (lambda (fn)
1289 (funcall fn beg end old-len))
1290 c-before-font-lock-functions)))))))
1291
1292 (defun c-fl-decl-start (pos)
1293 ;; If the beginning of the line containing POS is in the middle of a "local"
1294 ;; declaration (i.e. one which does not start outside of braces enclosing
1295 ;; POS, such as a struct), return the beginning of that declaration.
1296 ;; Otherwise return nil. Note that declarations, in this sense, can be
1297 ;; nested.
1298 ;;
1299 ;; This function is called indirectly from font locking stuff - either from
1300 ;; c-after-change (to prepare for after-change font-locking) or from font
1301 ;; lock context (etc.) fontification.
1302 (let ((lit-limits (c-literal-limits))
1303 (new-pos pos)
1304 bod-lim bo-decl)
1305 (goto-char (c-point 'bol new-pos))
1306 (when lit-limits ; Comment or string.
1307 (goto-char (car lit-limits)))
1308 (setq bod-lim (c-determine-limit 500))
1309
1310 (while
1311 ;; Go to a less nested declaration each time round this loop.
1312 (and
1313 (eq (car (c-beginning-of-decl-1 bod-lim)) 'same)
1314 (> (point) bod-lim)
1315 (progn (setq bo-decl (point))
1316 ;; Are we looking at a keyword such as "template" or
1317 ;; "typedef" which can decorate a type, or the type itself?
1318 (when (or (looking-at c-prefix-spec-kwds-re)
1319 (c-forward-type t))
1320 ;; We've found another candidate position.
1321 (setq new-pos (min new-pos bo-decl))
1322 (goto-char bo-decl))
1323 t)
1324 ;; Try and go out a level to search again.
1325 (progn
1326 (c-backward-syntactic-ws bod-lim)
1327 (and (> (point) bod-lim)
1328 (or (memq (char-before) '(?\( ?\[))
1329 (and (eq (char-before) ?\<)
1330 (eq (c-get-char-property
1331 (1- (point)) 'syntax-table)
1332 c-<-as-paren-syntax)))))
1333 (not (bobp)))
1334 (backward-char)) ; back over (, [, <.
1335 (and (/= new-pos pos) new-pos)))
1336
1337 (defun c-change-expand-fl-region (_beg _end _old-len)
1338 ;; Expand the region (c-new-BEG c-new-END) to an after-change font-lock
1339 ;; region. This will usually be the smallest sequence of whole lines
1340 ;; containing `c-new-BEG' and `c-new-END', but if `c-new-BEG' is in a
1341 ;; "local" declaration (see `c-fl-decl-start') the beginning of this is used
1342 ;; as the lower bound.
1343 ;;
1344 ;; This is called from an after-change-function, but the parameters BEG END
1345 ;; and OLD-LEN are not used.
1346 (if font-lock-mode
1347 (setq c-new-BEG
1348 (or (c-fl-decl-start c-new-BEG) (c-point 'bol c-new-BEG))
1349 c-new-END
1350 (save-excursion
1351 (goto-char c-new-END)
1352 (if (bolp)
1353 (point)
1354 (c-point 'bonl c-new-END))))))
1355
1356 (defun c-context-expand-fl-region (beg end)
1357 ;; Return a cons (NEW-BEG . NEW-END), where NEW-BEG is the beginning of a
1358 ;; "local" declaration containing BEG (see `c-fl-decl-start') or BOL BEG is
1359 ;; in. NEW-END is beginning of the line after the one END is in.
1360 (cons (or (c-fl-decl-start beg) (c-point 'bol beg))
1361 (c-point 'bonl end)))
1362
1363 (defun c-before-context-fl-expand-region (beg end)
1364 ;; Expand the region (BEG END) as specified by
1365 ;; `c-before-context-fontification-functions'. Return a cons of the bounds
1366 ;; of the new region.
1367 (save-restriction
1368 (widen)
1369 (save-excursion
1370 (let ((new-beg beg) (new-end end)
1371 (new-region (cons beg end)))
1372 (mapc (lambda (fn)
1373 (setq new-region (funcall fn new-beg new-end))
1374 (setq new-beg (car new-region) new-end (cdr new-region)))
1375 c-before-context-fontification-functions)
1376 new-region))))
1377
1378 (defun c-font-lock-fontify-region (beg end &optional verbose)
1379 ;; Effectively advice around `font-lock-fontify-region' which extends the
1380 ;; region (BEG END), for example, to avoid context fontification chopping
1381 ;; off the start of the context. Do not extend the region if it's already
1382 ;; been done (i.e. from an after-change fontification. An example (C++)
1383 ;; where the chopping off used to happen is this:
1384 ;;
1385 ;; template <typename T>
1386 ;;
1387 ;;
1388 ;; void myfunc(T* p) {}
1389 ;;
1390 ;; Type a space in the first blank line, and the fontification of the next
1391 ;; line was fouled up by context fontification.
1392 (let (new-beg new-end new-region case-fold-search)
1393 (if (and c-in-after-change-fontification
1394 (< beg c-new-END) (> end c-new-BEG))
1395 ;; Region and the latest after-change fontification region overlap.
1396 ;; Determine the upper and lower bounds of our adjusted region
1397 ;; separately.
1398 (progn
1399 (if (<= beg c-new-BEG)
1400 (setq c-in-after-change-fontification nil))
1401 (setq new-beg
1402 (if (and (>= beg (c-point 'bol c-new-BEG))
1403 (<= beg c-new-BEG))
1404 ;; Either jit-lock has accepted `c-new-BEG', or has
1405 ;; (probably) extended the change region spuriously to
1406 ;; BOL, which position likely has a syntactically
1407 ;; different position. To ensure correct fontification,
1408 ;; we start at `c-new-BEG', assuming any characters to the
1409 ;; left of `c-new-BEG' on the line do not require
1410 ;; fontification.
1411 c-new-BEG
1412 (setq new-region (c-before-context-fl-expand-region beg end)
1413 new-end (cdr new-region))
1414 (car new-region)))
1415 (setq new-end
1416 (if (and (>= end (c-point 'bol c-new-END))
1417 (<= end c-new-END))
1418 c-new-END
1419 (or new-end
1420 (cdr (c-before-context-fl-expand-region beg end))))))
1421 ;; Context (etc.) fontification.
1422 (setq new-region (c-before-context-fl-expand-region beg end)
1423 new-beg (car new-region) new-end (cdr new-region)))
1424 (funcall (default-value 'font-lock-fontify-region-function)
1425 new-beg new-end verbose)))
1426
1427 (defun c-after-font-lock-init ()
1428 ;; Put on `font-lock-mode-hook'. This function ensures our after-change
1429 ;; function will get executed before the font-lock one.
1430 (when (memq #'c-after-change after-change-functions)
1431 (remove-hook 'after-change-functions #'c-after-change t)
1432 (add-hook 'after-change-functions #'c-after-change nil t)))
1433
1434 (defun c-font-lock-init ()
1435 "Set up the font-lock variables for using the font-lock support in CC Mode.
1436 This does not load the font-lock package. Use after
1437 `c-basic-common-init' and after cc-fonts has been loaded.
1438 This function is called from `c-common-init', once per mode initialization."
1439
1440 (set (make-local-variable 'font-lock-defaults)
1441 `(,(if (c-major-mode-is 'awk-mode)
1442 ;; awk-mode currently has only one font lock level.
1443 'awk-font-lock-keywords
1444 (mapcar 'c-mode-symbol
1445 '("font-lock-keywords" "font-lock-keywords-1"
1446 "font-lock-keywords-2" "font-lock-keywords-3")))
1447 nil nil
1448 ,c-identifier-syntax-modifications
1449 c-beginning-of-syntax
1450 (font-lock-mark-block-function
1451 . c-mark-function)))
1452
1453 ;; Prevent `font-lock-default-fontify-region' extending the region it will
1454 ;; fontify to whole lines by removing `font-lock-extend-region-wholelines'
1455 ;; from `font-lock-extend-region-functions'. (Emacs only). This fixes
1456 ;; Emacs bug #19669.
1457 (when (boundp 'font-lock-extend-region-functions)
1458 (setq font-lock-extend-region-functions
1459 (delq 'font-lock-extend-region-wholelines
1460 font-lock-extend-region-functions)))
1461
1462 (make-local-variable 'font-lock-fontify-region-function)
1463 (setq font-lock-fontify-region-function 'c-font-lock-fontify-region)
1464
1465 (if (featurep 'xemacs)
1466 (make-local-hook 'font-lock-mode-hook))
1467 (add-hook 'font-lock-mode-hook 'c-after-font-lock-init nil t))
1468
1469 ;; Emacs 22 and later.
1470 (defun c-extend-after-change-region (beg end _old-len)
1471 "Extend the region to be fontified, if necessary."
1472 ;; Note: the parameter OLD-LEN is ignored here. This somewhat indirect
1473 ;; implementation exists because it is minimally different from the
1474 ;; stand-alone CC Mode which, lacking
1475 ;; font-lock-extend-after-change-region-function, is forced to use advice
1476 ;; instead.
1477 ;;
1478 ;; Of the seven CC Mode languages, currently (2009-05) only C, C++, Objc
1479 ;; (the languages with #define) and AWK Mode make non-null use of this
1480 ;; function.
1481 (when (eq font-lock-support-mode 'jit-lock-mode)
1482 (save-restriction
1483 (widen)
1484 (c-save-buffer-state () ; Protect the undo-list from put-text-property.
1485 (if (< c-new-BEG beg)
1486 (put-text-property c-new-BEG beg 'fontified nil))
1487 (if (> c-new-END end)
1488 (put-text-property end c-new-END 'fontified nil)))))
1489 (cons c-new-BEG c-new-END))
1490
1491 ;; Emacs < 22 and XEmacs
1492 (defmacro c-advise-fl-for-region (function)
1493 `(defadvice ,function (before get-awk-region activate)
1494 ;; Make sure that any string/regexp is completely font-locked.
1495 (when c-buffer-is-cc-mode
1496 (save-excursion
1497 (ad-set-arg 1 c-new-END) ; end
1498 (ad-set-arg 0 c-new-BEG))))) ; beg
1499
1500 (unless (boundp 'font-lock-extend-after-change-region-function)
1501 (c-advise-fl-for-region font-lock-after-change-function)
1502 (c-advise-fl-for-region jit-lock-after-change)
1503 (c-advise-fl-for-region lazy-lock-defer-rest-after-change)
1504 (c-advise-fl-for-region lazy-lock-defer-line-after-change))
1505
1506 ;; Connect up to `electric-indent-mode' (Emacs 24.4 and later).
1507 (defun c-electric-indent-mode-hook ()
1508 ;; Emacs has en/disabled `electric-indent-mode'. Propagate this through to
1509 ;; each CC Mode buffer.
1510 (mapc (lambda (buf)
1511 (with-current-buffer buf
1512 (when c-buffer-is-cc-mode
1513 ;; Don't use `c-toggle-electric-state' here due to recursion.
1514 (setq c-electric-flag electric-indent-mode)
1515 (c-update-modeline))))
1516 (buffer-list)))
1517
1518 (defun c-electric-indent-local-mode-hook ()
1519 ;; Emacs has en/disabled `electric-indent-local-mode' for this buffer.
1520 ;; Propagate this through to this buffer's value of `c-electric-flag'
1521 (when c-buffer-is-cc-mode
1522 (setq c-electric-flag electric-indent-mode)
1523 (c-update-modeline)))
1524
1525 \f
1526 ;; Support for C
1527
1528 (defvar c-mode-syntax-table
1529 (funcall (c-lang-const c-make-mode-syntax-table c))
1530 "Syntax table used in c-mode buffers.")
1531
1532 (c-define-abbrev-table 'c-mode-abbrev-table
1533 '(("else" "else" c-electric-continued-statement 0)
1534 ("while" "while" c-electric-continued-statement 0))
1535 "Abbreviation table used in c-mode buffers.")
1536
1537 (defvar c-mode-map
1538 (let ((map (c-make-inherited-keymap)))
1539 ;; Add bindings which are only useful for C.
1540 (define-key map "\C-c\C-e" 'c-macro-expand)
1541 map)
1542 "Keymap used in c-mode buffers.")
1543
1544
1545 (easy-menu-define c-c-menu c-mode-map "C Mode Commands"
1546 (cons "C" (c-lang-const c-mode-menu c)))
1547
1548 ;; In XEmacs >= 21.5 modes should add their own entries to
1549 ;; `auto-mode-alist'. The comment form of autoload is used to avoid
1550 ;; doing this on load. That since `add-to-list' prepends the value
1551 ;; which could cause it to clobber user settings. Later emacsen have
1552 ;; an append option, but it's not safe to use.
1553
1554 ;; The extension ".C" is associated with C++ while the lowercase
1555 ;; variant goes with C. On case insensitive file systems, this means
1556 ;; that ".c" files also might open C++ mode if the C++ entry comes
1557 ;; first on `auto-mode-alist'. Thus we try to ensure that ".C" comes
1558 ;; after ".c", and since `add-to-list' adds the entry first we have to
1559 ;; add the ".C" entry first.
1560 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.\\(cc\\|hh\\)\\'" . c++-mode))
1561 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.[ch]\\(pp\\|xx\\|\\+\\+\\)\\'" . c++-mode))
1562 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.\\(CC?\\|HH?\\)\\'" . c++-mode))
1563
1564 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.c\\'" . c-mode))
1565 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.h\\'" . c-or-c++-mode))
1566
1567 ;; NB: The following two associate yacc and lex files to C Mode, which
1568 ;; is not really suitable for those formats. Anyway, afaik there's
1569 ;; currently no better mode for them, and besides this is legacy.
1570 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.y\\(acc\\)?\\'" . c-mode))
1571 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.lex\\'" . c-mode))
1572
1573 ;; Preprocessed files generated by C and C++ compilers.
1574 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.i\\'" . c-mode))
1575 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.ii\\'" . c++-mode))
1576
1577 (unless (fboundp 'prog-mode) (defalias 'prog-mode 'fundamental-mode))
1578
1579 ;;;###autoload
1580 (define-derived-mode c-mode prog-mode "C"
1581 "Major mode for editing C code.
1582
1583 To submit a problem report, enter `\\[c-submit-bug-report]' from a
1584 c-mode buffer. This automatically sets up a mail buffer with version
1585 information already added. You just need to add a description of the
1586 problem, including a reproducible test case, and send the message.
1587
1588 To see what version of CC Mode you are running, enter `\\[c-version]'.
1589
1590 The hook `c-mode-common-hook' is run with no args at mode
1591 initialization, then `c-mode-hook'.
1592
1593 Key bindings:
1594 \\{c-mode-map}"
1595 :after-hook (progn (c-make-noise-macro-regexps)
1596 (c-make-macro-with-semi-re)
1597 (c-update-modeline))
1598 (c-initialize-cc-mode t)
1599 (setq abbrev-mode t)
1600 (c-init-language-vars-for 'c-mode)
1601 (c-common-init 'c-mode)
1602 (easy-menu-add c-c-menu)
1603 (cc-imenu-init cc-imenu-c-generic-expression)
1604 (c-run-mode-hooks 'c-mode-common-hook))
1605
1606 (defconst c-or-c++-mode--regexp
1607 (eval-when-compile
1608 (let ((id "[a-zA-Z0-9_]+") (ws "[ \t\r]+") (ws-maybe "[ \t\r]*"))
1609 (concat "^" ws-maybe "\\(?:"
1610 "using" ws "\\(?:namespace" ws "std;\\|std::\\)"
1611 "\\|" "namespace" "\\(:?" ws id "\\)?" ws-maybe "{"
1612 "\\|" "class" ws id ws-maybe "[:{\n]"
1613 "\\|" "template" ws-maybe "<.*>"
1614 "\\|" "#include" ws-maybe "<\\(?:string\\|iostream\\|map\\)>"
1615 "\\)")))
1616 "A regexp applied to C header files to check if they are really C++.")
1617
1618 ;;;###autoload
1619 (defun c-or-c++-mode ()
1620 "Analyse buffer and enable either C or C++ mode.
1621
1622 Some people and projects use .h extension for C++ header files
1623 which is also the one used for C header files. This makes
1624 matching on file name insufficient for detecting major mode that
1625 should be used.
1626
1627 This function attempts to use file contents to determine whether
1628 the code is C or C++ and based on that chooses whether to enable
1629 `c-mode' or `c++-mode'."
1630 (if (save-excursion
1631 (save-restriction
1632 (save-match-data
1633 (widen)
1634 (goto-char (point-min))
1635 (re-search-forward c-or-c++-mode--regexp
1636 (+ (point) c-guess-region-max) t))))
1637 (c++-mode)
1638 (c-mode)))
1639
1640 \f
1641 ;; Support for C++
1642
1643 (defvar c++-mode-syntax-table
1644 (funcall (c-lang-const c-make-mode-syntax-table c++))
1645 "Syntax table used in c++-mode buffers.")
1646
1647 (c-define-abbrev-table 'c++-mode-abbrev-table
1648 '(("else" "else" c-electric-continued-statement 0)
1649 ("while" "while" c-electric-continued-statement 0)
1650 ("catch" "catch" c-electric-continued-statement 0))
1651 "Abbreviation table used in c++-mode buffers.")
1652
1653 (defvar c++-mode-map
1654 (let ((map (c-make-inherited-keymap)))
1655 ;; Add bindings which are only useful for C++.
1656 (define-key map "\C-c\C-e" 'c-macro-expand)
1657 (define-key map "\C-c:" 'c-scope-operator)
1658 (define-key map "<" 'c-electric-lt-gt)
1659 (define-key map ">" 'c-electric-lt-gt)
1660 map)
1661 "Keymap used in c++-mode buffers.")
1662
1663 (easy-menu-define c-c++-menu c++-mode-map "C++ Mode Commands"
1664 (cons "C++" (c-lang-const c-mode-menu c++)))
1665
1666 ;;;###autoload
1667 (define-derived-mode c++-mode prog-mode "C++"
1668 "Major mode for editing C++ code.
1669 To submit a problem report, enter `\\[c-submit-bug-report]' from a
1670 c++-mode buffer. This automatically sets up a mail buffer with
1671 version information already added. You just need to add a description
1672 of the problem, including a reproducible test case, and send the
1673 message.
1674
1675 To see what version of CC Mode you are running, enter `\\[c-version]'.
1676
1677 The hook `c-mode-common-hook' is run with no args at mode
1678 initialization, then `c++-mode-hook'.
1679
1680 Key bindings:
1681 \\{c++-mode-map}"
1682 :after-hook (progn (c-make-noise-macro-regexps)
1683 (c-make-macro-with-semi-re)
1684 (c-update-modeline))
1685 (c-initialize-cc-mode t)
1686 (setq abbrev-mode t)
1687 (c-init-language-vars-for 'c++-mode)
1688 (c-common-init 'c++-mode)
1689 (easy-menu-add c-c++-menu)
1690 (cc-imenu-init cc-imenu-c++-generic-expression)
1691 (c-run-mode-hooks 'c-mode-common-hook))
1692
1693 \f
1694 ;; Support for Objective-C
1695
1696 (defvar objc-mode-syntax-table
1697 (funcall (c-lang-const c-make-mode-syntax-table objc))
1698 "Syntax table used in objc-mode buffers.")
1699
1700 (c-define-abbrev-table 'objc-mode-abbrev-table
1701 '(("else" "else" c-electric-continued-statement 0)
1702 ("while" "while" c-electric-continued-statement 0))
1703 "Abbreviation table used in objc-mode buffers.")
1704
1705 (defvar objc-mode-map
1706 (let ((map (c-make-inherited-keymap)))
1707 ;; Add bindings which are only useful for Objective-C.
1708 (define-key map "\C-c\C-e" 'c-macro-expand)
1709 map)
1710 "Keymap used in objc-mode buffers.")
1711
1712 (easy-menu-define c-objc-menu objc-mode-map "ObjC Mode Commands"
1713 (cons "ObjC" (c-lang-const c-mode-menu objc)))
1714
1715 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.m\\'" . objc-mode))
1716
1717 ;;;###autoload
1718 (define-derived-mode objc-mode prog-mode "ObjC"
1719 "Major mode for editing Objective C code.
1720 To submit a problem report, enter `\\[c-submit-bug-report]' from an
1721 objc-mode buffer. This automatically sets up a mail buffer with
1722 version information already added. You just need to add a description
1723 of the problem, including a reproducible test case, and send the
1724 message.
1725
1726 To see what version of CC Mode you are running, enter `\\[c-version]'.
1727
1728 The hook `c-mode-common-hook' is run with no args at mode
1729 initialization, then `objc-mode-hook'.
1730
1731 Key bindings:
1732 \\{objc-mode-map}"
1733 :after-hook (progn (c-make-noise-macro-regexps)
1734 (c-make-macro-with-semi-re)
1735 (c-update-modeline))
1736 (c-initialize-cc-mode t)
1737 (setq abbrev-mode t)
1738 (c-init-language-vars-for 'objc-mode)
1739 (c-common-init 'objc-mode)
1740 (easy-menu-add c-objc-menu)
1741 (cc-imenu-init nil 'cc-imenu-objc-function)
1742 (c-run-mode-hooks 'c-mode-common-hook))
1743
1744 \f
1745 ;; Support for Java
1746
1747 (defvar java-mode-syntax-table
1748 (funcall (c-lang-const c-make-mode-syntax-table java))
1749 "Syntax table used in java-mode buffers.")
1750
1751 (c-define-abbrev-table 'java-mode-abbrev-table
1752 '(("else" "else" c-electric-continued-statement 0)
1753 ("while" "while" c-electric-continued-statement 0)
1754 ("catch" "catch" c-electric-continued-statement 0)
1755 ("finally" "finally" c-electric-continued-statement 0))
1756 "Abbreviation table used in java-mode buffers.")
1757
1758 (defvar java-mode-map
1759 (let ((map (c-make-inherited-keymap)))
1760 ;; Add bindings which are only useful for Java.
1761 map)
1762 "Keymap used in java-mode buffers.")
1763
1764 ;; Regexp trying to describe the beginning of a Java top-level
1765 ;; definition. This is not used by CC Mode, nor is it maintained
1766 ;; since it's practically impossible to write a regexp that reliably
1767 ;; matches such a construct. Other tools are necessary.
1768 (defconst c-Java-defun-prompt-regexp
1769 "^[ \t]*\\(\\(\\(public\\|protected\\|private\\|const\\|abstract\\|synchronized\\|final\\|static\\|threadsafe\\|transient\\|native\\|volatile\\)\\s-+\\)*\\(\\(\\([[a-zA-Z][][_$.a-zA-Z0-9]*[][_$.a-zA-Z0-9]+\\|[[a-zA-Z]\\)\\s-*\\)\\s-+\\)\\)?\\(\\([[a-zA-Z][][_$.a-zA-Z0-9]*\\s-+\\)\\s-*\\)?\\([_a-zA-Z][^][ \t:;.,{}()\7f=]*\\|\\([_$a-zA-Z][_$.a-zA-Z0-9]*\\)\\)\\s-*\\(([^);{}]*)\\)?\\([] \t]*\\)\\(\\s-*\\<throws\\>\\s-*\\(\\([_$a-zA-Z][_$.a-zA-Z0-9]*\\)[, \t\n\r\f\v]*\\)+\\)?\\s-*")
1770
1771 (easy-menu-define c-java-menu java-mode-map "Java Mode Commands"
1772 (cons "Java" (c-lang-const c-mode-menu java)))
1773
1774 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.java\\'" . java-mode))
1775
1776 ;;;###autoload
1777 (define-derived-mode java-mode prog-mode "Java"
1778 "Major mode for editing Java code.
1779 To submit a problem report, enter `\\[c-submit-bug-report]' from a
1780 java-mode buffer. This automatically sets up a mail buffer with
1781 version information already added. You just need to add a description
1782 of the problem, including a reproducible test case, and send the
1783 message.
1784
1785 To see what version of CC Mode you are running, enter `\\[c-version]'.
1786
1787 The hook `c-mode-common-hook' is run with no args at mode
1788 initialization, then `java-mode-hook'.
1789
1790 Key bindings:
1791 \\{java-mode-map}"
1792 :after-hook (c-update-modeline)
1793 (c-initialize-cc-mode t)
1794 (setq abbrev-mode t)
1795 (c-init-language-vars-for 'java-mode)
1796 (c-common-init 'java-mode)
1797 (easy-menu-add c-java-menu)
1798 (cc-imenu-init cc-imenu-java-generic-expression)
1799 (c-run-mode-hooks 'c-mode-common-hook))
1800
1801 \f
1802 ;; Support for CORBA's IDL language
1803
1804 (defvar idl-mode-syntax-table
1805 (funcall (c-lang-const c-make-mode-syntax-table idl))
1806 "Syntax table used in idl-mode buffers.")
1807
1808 (c-define-abbrev-table 'idl-mode-abbrev-table nil
1809 "Abbreviation table used in idl-mode buffers.")
1810
1811 (defvar idl-mode-map
1812 (let ((map (c-make-inherited-keymap)))
1813 ;; Add bindings which are only useful for IDL.
1814 map)
1815 "Keymap used in idl-mode buffers.")
1816
1817 (easy-menu-define c-idl-menu idl-mode-map "IDL Mode Commands"
1818 (cons "IDL" (c-lang-const c-mode-menu idl)))
1819
1820 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.idl\\'" . idl-mode))
1821
1822 ;;;###autoload
1823 (define-derived-mode idl-mode prog-mode "IDL"
1824 "Major mode for editing CORBA's IDL, PSDL and CIDL code.
1825 To submit a problem report, enter `\\[c-submit-bug-report]' from an
1826 idl-mode buffer. This automatically sets up a mail buffer with
1827 version information already added. You just need to add a description
1828 of the problem, including a reproducible test case, and send the
1829 message.
1830
1831 To see what version of CC Mode you are running, enter `\\[c-version]'.
1832
1833 The hook `c-mode-common-hook' is run with no args at mode
1834 initialization, then `idl-mode-hook'.
1835
1836 Key bindings:
1837 \\{idl-mode-map}"
1838 :after-hook (c-update-modeline)
1839 (c-initialize-cc-mode t)
1840 (c-init-language-vars-for 'idl-mode)
1841 (c-common-init 'idl-mode)
1842 (easy-menu-add c-idl-menu)
1843 ;;(cc-imenu-init cc-imenu-idl-generic-expression) ;TODO
1844 (c-run-mode-hooks 'c-mode-common-hook))
1845
1846 \f
1847 ;; Support for Pike
1848
1849 (defvar pike-mode-syntax-table
1850 (funcall (c-lang-const c-make-mode-syntax-table pike))
1851 "Syntax table used in pike-mode buffers.")
1852
1853 (c-define-abbrev-table 'pike-mode-abbrev-table
1854 '(("else" "else" c-electric-continued-statement 0)
1855 ("while" "while" c-electric-continued-statement 0))
1856 "Abbreviation table used in pike-mode buffers.")
1857
1858 (defvar pike-mode-map
1859 (let ((map (c-make-inherited-keymap)))
1860 ;; Additional bindings.
1861 (define-key map "\C-c\C-e" 'c-macro-expand)
1862 map)
1863 "Keymap used in pike-mode buffers.")
1864
1865 (easy-menu-define c-pike-menu pike-mode-map "Pike Mode Commands"
1866 (cons "Pike" (c-lang-const c-mode-menu pike)))
1867
1868 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.\\(u?lpc\\|pike\\|pmod\\(\\.in\\)?\\)\\'" . pike-mode))
1869 ;;;###autoload (add-to-list 'interpreter-mode-alist '("pike" . pike-mode))
1870
1871 ;;;###autoload
1872 (define-derived-mode pike-mode prog-mode "Pike"
1873 "Major mode for editing Pike code.
1874 To submit a problem report, enter `\\[c-submit-bug-report]' from a
1875 pike-mode buffer. This automatically sets up a mail buffer with
1876 version information already added. You just need to add a description
1877 of the problem, including a reproducible test case, and send the
1878 message.
1879
1880 To see what version of CC Mode you are running, enter `\\[c-version]'.
1881
1882 The hook `c-mode-common-hook' is run with no args at mode
1883 initialization, then `pike-mode-hook'.
1884
1885 Key bindings:
1886 \\{pike-mode-map}"
1887 :after-hook (c-update-modeline)
1888 (c-initialize-cc-mode t)
1889 (setq abbrev-mode t)
1890 (c-init-language-vars-for 'pike-mode)
1891 (c-common-init 'pike-mode)
1892 (easy-menu-add c-pike-menu)
1893 ;;(cc-imenu-init cc-imenu-pike-generic-expression) ;TODO
1894 (c-run-mode-hooks 'c-mode-common-hook))
1895
1896 \f
1897 ;; Support for AWK
1898
1899 ;;;###autoload (add-to-list 'auto-mode-alist '("\\.awk\\'" . awk-mode))
1900 ;;;###autoload (add-to-list 'interpreter-mode-alist '("awk" . awk-mode))
1901 ;;;###autoload (add-to-list 'interpreter-mode-alist '("mawk" . awk-mode))
1902 ;;;###autoload (add-to-list 'interpreter-mode-alist '("nawk" . awk-mode))
1903 ;;;###autoload (add-to-list 'interpreter-mode-alist '("gawk" . awk-mode))
1904
1905 (c-define-abbrev-table 'awk-mode-abbrev-table
1906 '(("else" "else" c-electric-continued-statement 0)
1907 ("while" "while" c-electric-continued-statement 0))
1908 "Abbreviation table used in awk-mode buffers.")
1909
1910 (defvar awk-mode-map
1911 (let ((map (c-make-inherited-keymap)))
1912 ;; Add bindings which are only useful for awk.
1913 (define-key map "#" 'self-insert-command);Overrides electric parent binding.
1914 (define-key map "/" 'self-insert-command);Overrides electric parent binding.
1915 (define-key map "*" 'self-insert-command);Overrides electric parent binding.
1916 (define-key map "\C-c\C-n" 'undefined) ; #if doesn't exist in awk.
1917 (define-key map "\C-c\C-p" 'undefined)
1918 (define-key map "\C-c\C-u" 'undefined)
1919 (define-key map "\M-a" 'c-beginning-of-statement) ; 2003/10/7
1920 (define-key map "\M-e" 'c-end-of-statement) ; 2003/10/7
1921 (define-key map "\C-\M-a" 'c-awk-beginning-of-defun)
1922 (define-key map "\C-\M-e" 'c-awk-end-of-defun)
1923 map)
1924 "Keymap used in awk-mode buffers.")
1925
1926 (easy-menu-define c-awk-menu awk-mode-map "AWK Mode Commands"
1927 (cons "AWK" (c-lang-const c-mode-menu awk)))
1928
1929 ;; (require 'cc-awk) brings these in.
1930 (defvar awk-mode-syntax-table)
1931 (declare-function c-awk-unstick-NL-prop "cc-awk" ())
1932
1933 ;;;###autoload
1934 (define-derived-mode awk-mode prog-mode "AWK"
1935 "Major mode for editing AWK code.
1936 To submit a problem report, enter `\\[c-submit-bug-report]' from an
1937 awk-mode buffer. This automatically sets up a mail buffer with version
1938 information already added. You just need to add a description of the
1939 problem, including a reproducible test case, and send the message.
1940
1941 To see what version of CC Mode you are running, enter `\\[c-version]'.
1942
1943 The hook `c-mode-common-hook' is run with no args at mode
1944 initialization, then `awk-mode-hook'.
1945
1946 Key bindings:
1947 \\{awk-mode-map}"
1948 :after-hook (c-update-modeline)
1949 ;; We need the next line to stop the macro defining
1950 ;; `awk-mode-syntax-table'. This would mask the real table which is
1951 ;; declared in cc-awk.el and hasn't yet been loaded.
1952 :syntax-table nil
1953 (require 'cc-awk) ; Added 2003/6/10.
1954 (c-initialize-cc-mode t)
1955 (setq abbrev-mode t)
1956 (c-init-language-vars-for 'awk-mode)
1957 (c-common-init 'awk-mode)
1958 (c-awk-unstick-NL-prop)
1959 (c-run-mode-hooks 'c-mode-common-hook))
1960
1961 \f
1962 ;; bug reporting
1963
1964 (defconst c-mode-help-address
1965 "submit@debbugs.gnu.org"
1966 "Address(es) for CC Mode bug reports.")
1967
1968 (defun c-version ()
1969 "Echo the current version of CC Mode in the minibuffer."
1970 (interactive)
1971 (message "Using CC Mode version %s" c-version)
1972 (c-keep-region-active))
1973
1974 (define-obsolete-variable-alias 'c-prepare-bug-report-hooks
1975 'c-prepare-bug-report-hook "24.3")
1976 (defvar c-prepare-bug-report-hook nil)
1977
1978 ;; Dynamic variables used by reporter.
1979 (defvar reporter-prompt-for-summary-p)
1980 (defvar reporter-dont-compact-list)
1981
1982 ;; This could be "emacs,cc-mode" in the version included in Emacs.
1983 (defconst c-mode-bug-package "cc-mode"
1984 "The package to use in the bug submission.")
1985
1986 ;; reporter-submit-bug-report requires sendmail.
1987 (declare-function mail-position-on-field "sendmail" (field &optional soft))
1988
1989 (defun c-submit-bug-report ()
1990 "Submit via mail a bug report on CC Mode."
1991 (interactive)
1992 (require 'reporter)
1993 ;; load in reporter
1994 (let ((reporter-prompt-for-summary-p t)
1995 (reporter-dont-compact-list '(c-offsets-alist))
1996 (style c-indentation-style)
1997 (c-features c-emacs-features))
1998 (and
1999 (if (y-or-n-p "Do you want to submit a report on CC Mode? ")
2000 t (message "") nil)
2001 (reporter-submit-bug-report
2002 c-mode-help-address
2003 (concat "CC Mode " c-version " (" mode-name ")")
2004 (let ((vars (append
2005 c-style-variables
2006 '(c-buffer-is-cc-mode
2007 c-tab-always-indent
2008 c-syntactic-indentation
2009 c-syntactic-indentation-in-macros
2010 c-ignore-auto-fill
2011 c-auto-align-backslashes
2012 c-backspace-function
2013 c-delete-function
2014 c-electric-pound-behavior
2015 c-default-style
2016 c-enable-xemacs-performance-kludge-p
2017 c-old-style-variable-behavior
2018 defun-prompt-regexp
2019 tab-width
2020 comment-column
2021 parse-sexp-ignore-comments
2022 parse-sexp-lookup-properties
2023 lookup-syntax-properties
2024 ;; A brain-damaged XEmacs only variable that, if
2025 ;; set to nil can cause all kinds of chaos.
2026 signal-error-on-buffer-boundary
2027 ;; Variables that affect line breaking and comments.
2028 auto-fill-mode
2029 auto-fill-function
2030 filladapt-mode
2031 comment-multi-line
2032 comment-start-skip
2033 fill-prefix
2034 fill-column
2035 paragraph-start
2036 adaptive-fill-mode
2037 adaptive-fill-regexp)
2038 nil)))
2039 (mapc (lambda (var) (unless (boundp var)
2040 (setq vars (delq var vars))))
2041 '(signal-error-on-buffer-boundary
2042 filladapt-mode
2043 defun-prompt-regexp
2044 font-lock-mode
2045 auto-fill-mode
2046 font-lock-maximum-decoration
2047 parse-sexp-lookup-properties
2048 lookup-syntax-properties))
2049 vars)
2050 (lambda ()
2051 (run-hooks 'c-prepare-bug-report-hook)
2052 (save-excursion
2053 (or (mail-position-on-field "X-Debbugs-Package")
2054 (insert c-mode-bug-package)))
2055 (insert (format "Buffer Style: %s\nc-emacs-features: %s\n"
2056 style c-features)))))))
2057
2058 \f
2059 (cc-provide 'cc-mode)
2060
2061 ;; Local Variables:
2062 ;; indent-tabs-mode: t
2063 ;; tab-width: 8
2064 ;; End:
2065 ;;; cc-mode.el ends here