]> code.delx.au - gnu-emacs/blob - lisp/progmodes/c-mode.el
(c++-mode): Doc fix.
[gnu-emacs] / lisp / progmodes / c-mode.el
1 ;;; c-mode.el --- C code editing commands for Emacs
2 ;; Copyright (C) 1985, 86, 87, 92, 94, 95 Free Software Foundation, Inc.
3
4 ;; Maintainer: FSF
5 ;; Keywords: c
6
7 ;; This file is part of GNU Emacs.
8
9 ;; GNU Emacs is free software; you can redistribute it and/or modify
10 ;; it under the terms of the GNU General Public License as published by
11 ;; the Free Software Foundation; either version 2, or (at your option)
12 ;; any later version.
13
14 ;; GNU Emacs is distributed in the hope that it will be useful,
15 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
16 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
17 ;; GNU General Public License for more details.
18
19 ;; You should have received a copy of the GNU General Public License
20 ;; along with GNU Emacs; see the file COPYING. If not, write to
21 ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
22
23 ;;; Commentary:
24
25 ;; A smart editing mode for C code. It knows a lot about C syntax and tries
26 ;; to position the cursor according to C layout conventions. You can
27 ;; change the details of the layout style with option variables. Load it
28 ;; and do M-x describe-mode for details.
29
30 ;;; Code:
31
32 (defvar c-mode-abbrev-table nil
33 "Abbrev table in use in C mode.")
34 (define-abbrev-table 'c-mode-abbrev-table ())
35
36 (defvar c-mode-map (make-sparse-keymap)
37 "Keymap used in C mode.")
38
39 (define-key c-mode-map "{" 'electric-c-brace)
40 (define-key c-mode-map "}" 'electric-c-brace)
41 (define-key c-mode-map ";" 'electric-c-semi)
42 (define-key c-mode-map "#" 'electric-c-sharp-sign)
43 (define-key c-mode-map ":" 'electric-c-terminator)
44 (define-key c-mode-map "\e\C-h" 'mark-c-function)
45 (define-key c-mode-map "\e\C-q" 'indent-c-exp)
46 (define-key c-mode-map "\ea" 'c-beginning-of-statement)
47 (define-key c-mode-map "\ee" 'c-end-of-statement)
48 (define-key c-mode-map "\C-c\C-n" 'c-forward-conditional)
49 (define-key c-mode-map "\C-c\C-p" 'c-backward-conditional)
50 (define-key c-mode-map "\C-c\C-u" 'c-up-conditional)
51 (define-key c-mode-map "\177" 'backward-delete-char-untabify)
52 (define-key c-mode-map "\t" 'c-indent-command)
53
54 (define-key c-mode-map [menu-bar] (make-sparse-keymap))
55
56 ;; "C-mode" is not strictly the right punctuation--it should be "C
57 ;; mode"--but that would look like two menu items. "C-mode" is the
58 ;; best alternative I can think of.
59 (define-key c-mode-map [menu-bar c]
60 (cons "C-mode" (make-sparse-keymap "C-mode")))
61
62 (define-key c-mode-map [menu-bar c comment-region]
63 '("Comment Out Region" . comment-region))
64 (define-key c-mode-map [menu-bar c c-macro-expand]
65 '("Macro Expand Region" . c-macro-expand))
66 (define-key c-mode-map [menu-bar c c-backslash-region]
67 '("Backslashify" . c-backslash-region))
68 (define-key c-mode-map [menu-bar c indent-exp]
69 '("Indent Expression" . indent-c-exp))
70 (define-key c-mode-map [menu-bar c indent-line]
71 '("Indent Line" . c-indent-command))
72 (define-key c-mode-map [menu-bar c fill]
73 '("Fill Comment Paragraph" . c-fill-paragraph))
74 (define-key c-mode-map [menu-bar c cpp-highlight-buffer]
75 '("Highlight Conditionals" . cpp-highlight-buffer))
76 (define-key c-mode-map [menu-bar c up]
77 '("Up Conditional" . c-up-conditional))
78 (define-key c-mode-map [menu-bar c backward]
79 '("Backward Conditional" . c-backward-conditional))
80 (define-key c-mode-map [menu-bar c forward]
81 '("Forward Conditional" . c-forward-conditional))
82 (define-key c-mode-map [menu-bar c backward-stmt]
83 '("Backward Statement" . c-beginning-of-statement))
84 (define-key c-mode-map [menu-bar c forward-stmt]
85 '("Forward Statement" . c-end-of-statement))
86
87 (put 'comment-region 'menu-enable 'mark-active)
88 (put 'c-macro-expand 'menu-enable 'mark-active)
89 (put 'c-backslash-region 'menu-enable 'mark-active)
90
91 (autoload 'c-macro-expand "cmacexp"
92 "Display the result of expanding all C macros occurring in the region.
93 The expansion is entirely correct because it uses the C preprocessor."
94 t)
95
96 (defvar c-mode-syntax-table nil
97 "Syntax table in use in C-mode buffers.")
98
99 (if c-mode-syntax-table
100 ()
101 (setq c-mode-syntax-table (make-syntax-table))
102 (modify-syntax-entry ?\\ "\\" c-mode-syntax-table)
103 (modify-syntax-entry ?/ ". 14" c-mode-syntax-table)
104 (modify-syntax-entry ?* ". 23" c-mode-syntax-table)
105 (modify-syntax-entry ?+ "." c-mode-syntax-table)
106 (modify-syntax-entry ?- "." c-mode-syntax-table)
107 (modify-syntax-entry ?= "." c-mode-syntax-table)
108 (modify-syntax-entry ?% "." c-mode-syntax-table)
109 (modify-syntax-entry ?< "." c-mode-syntax-table)
110 (modify-syntax-entry ?> "." c-mode-syntax-table)
111 (modify-syntax-entry ?& "." c-mode-syntax-table)
112 (modify-syntax-entry ?| "." c-mode-syntax-table)
113 (modify-syntax-entry ?\' "\"" c-mode-syntax-table))
114
115 (defconst c-indent-level 2
116 "*Indentation of C statements with respect to containing block.")
117 (defconst c-brace-imaginary-offset 0
118 "*Imagined indentation of a C open brace that actually follows a statement.")
119 (defconst c-brace-offset 0
120 "*Extra indentation for braces, compared with other text in same context.")
121 (defconst c-argdecl-indent 5
122 "*Indentation level of declarations of C function arguments.")
123 (defconst c-label-offset -2
124 "*Offset of C label lines and case statements relative to usual indentation.")
125 (defconst c-continued-statement-offset 2
126 "*Extra indent for lines not starting new statements.")
127 (defconst c-continued-brace-offset 0
128 "*Extra indent for substatements that start with open-braces.
129 This is in addition to `c-continued-statement-offset'.")
130 (defconst c-style-alist
131 '(("GNU"
132 (c-indent-level . 2)
133 (c-argdecl-indent . 5)
134 (c-brace-offset . 0)
135 (c-continued-brace-offset . 0)
136 (c-label-offset . -2)
137 (c-continued-statement-offset . 2))
138 ("K&R"
139 (c-indent-level . 5)
140 (c-argdecl-indent . 0)
141 (c-brace-offset . 0)
142 (c-continued-brace-offset . -5)
143 (c-label-offset . -5)
144 (c-continued-statement-offset . 5))
145 ("BSD"
146 (c-indent-level . 4)
147 (c-argdecl-indent . 4)
148 (c-brace-offset . 0)
149 (c-continued-brace-offset . -4)
150 (c-label-offset . -4)
151 (c-continued-statement-offset . 4))
152 ("C++"
153 (c-indent-level . 4)
154 (c-argdecl-indent . 0)
155 (c-brace-offset . 0)
156 (c-continued-brace-offset . -4)
157 (c-label-offset . -4)
158 (c-continued-statement-offset . 4)
159 (c-auto-newline . t))
160 ("Whitesmith"
161 (c-indent-level . 4)
162 (c-argdecl-indent . 4)
163 (c-brace-offset . 0)
164 (c-continued-brace-offset . 0)
165 (c-label-offset . -4)
166 (c-continued-statement-offset . 4))))
167
168 (defconst c-auto-newline nil
169 "*Non-nil means automatically newline before and after braces,
170 and after colons and semicolons, inserted in C code.
171 If you do not want a leading newline before braces then use:
172 (define-key c-mode-map \"{\" 'electric-c-semi)")
173
174 (defconst c-tab-always-indent t
175 "*Non-nil means TAB in C mode should always reindent the current line,
176 regardless of where in the line point is when the TAB command is used.")
177
178 ;;; Regular expression used internally to recognize labels in switch
179 ;;; statements.
180 (defconst c-switch-label-regexp "case[ \t'/(]\\|default[ \t]*:")
181
182 ;; This is actually the expression for C++ mode, but it's used for C too.
183 (defvar c-imenu-generic-expression
184 (`
185 ((nil
186 (,
187 (concat
188 "^" ; beginning of line is required
189 "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
190 "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; type specs; there can be no
191 "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; more than 3 tokens, right?
192
193 "\\(" ; last type spec including */&
194 "[a-zA-Z0-9_:]+"
195 "\\([ \t]*[*&]+[ \t]*\\|[ \t]+\\)" ; either pointer/ref sign or whitespace
196 "\\)?" ; if there is a last type spec
197 "\\(" ; name; take that into the imenu entry
198 "[a-zA-Z0-9_:~]+" ; member function, ctor or dtor...
199 ; (may not contain * because then
200 ; "a::operator char*" would become "char*"!)
201 "\\|"
202 "\\([a-zA-Z0-9_:~]*::\\)?operator"
203 "[^a-zA-Z1-9_][^(]*" ; ...or operator
204 " \\)"
205 "[ \t]*([^)]*)[ \t\n]*[^ ;]" ; require something other than a ; after
206 ; the (...) to avoid prototypes. Can't
207 ; catch cases with () inside the parentheses
208 ; surrounding the parameters
209 ; (like "int foo(int a=bar()) {...}"
210
211 )) 6)
212 ("Class"
213 (, (concat
214 "^" ; beginning of line is required
215 "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
216 "class[ \t]+"
217 "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
218 "[ \t]*[:{]"
219 )) 2)
220 ;; Example of generic expression for finding prototypes, structs, unions, enums.
221 ;; Uncomment if you want to find these too. It will be a bit slower gathering
222 ;; the indexes.
223 ; ("Prototypes"
224 ; (,
225 ; (concat
226 ; "^" ; beginning of line is required
227 ; "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
228 ; "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; type specs; there can be no
229 ; "\\([a-zA-Z0-9_:]+[ \t]+\\)?" ; more than 3 tokens, right?
230
231 ; "\\(" ; last type spec including */&
232 ; "[a-zA-Z0-9_:]+"
233 ; "\\([ \t]*[*&]+[ \t]*\\|[ \t]+\\)" ; either pointer/ref sign or whitespace
234 ; "\\)?" ; if there is a last type spec
235 ; "\\(" ; name; take that into the imenu entry
236 ; "[a-zA-Z0-9_:~]+" ; member function, ctor or dtor...
237 ; ; (may not contain * because then
238 ; ; "a::operator char*" would become "char*"!)
239 ; "\\|"
240 ; "\\([a-zA-Z0-9_:~]*::\\)?operator"
241 ; "[^a-zA-Z1-9_][^(]*" ; ...or operator
242 ; " \\)"
243 ; "[ \t]*([^)]*)[ \t\n]*;" ; require ';' after
244 ; ; the (...) Can't
245 ; ; catch cases with () inside the parentheses
246 ; ; surrounding the parameters
247 ; ; (like "int foo(int a=bar());"
248 ; )) 6)
249 ; ("Struct"
250 ; (, (concat
251 ; "^" ; beginning of line is required
252 ; "\\(static[ \t]+\\)?" ; there may be static or const.
253 ; "\\(const[ \t]+\\)?"
254 ; "struct[ \t]+"
255 ; "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
256 ; "[ \t]*[{]"
257 ; )) 3)
258 ; ("Enum"
259 ; (, (concat
260 ; "^" ; beginning of line is required
261 ; "\\(static[ \t]+\\)?" ; there may be static or const.
262 ; "\\(const[ \t]+\\)?"
263 ; "enum[ \t]+"
264 ; "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
265 ; "[ \t]*[{]"
266 ; )) 3)
267 ; ("Union"
268 ; (, (concat
269 ; "^" ; beginning of line is required
270 ; "\\(static[ \t]+\\)?" ; there may be static or const.
271 ; "\\(const[ \t]+\\)?"
272 ; "union[ \t]+"
273 ; "\\([a-zA-Z0-9_]+\\)" ; this is the string we want to get
274 ; "[ \t]*[{]"
275 ; )) 3)
276 ))
277 "Imenu generic expression for C mode. See `imenu-generic-expression'.")
278 \f
279 (defun c-mode ()
280 "Major mode for editing C code.
281 Expression and list commands understand all C brackets.
282 Tab indents for C code.
283 Comments are delimited with /* ... */.
284 Paragraphs are separated by blank lines only.
285 Delete converts tabs to spaces as it moves back.
286 \\{c-mode-map}
287 Variables controlling indentation style:
288 c-tab-always-indent
289 Non-nil means TAB in C mode should always reindent the current line,
290 regardless of where in the line point is when the TAB command is used.
291 c-auto-newline
292 Non-nil means automatically newline before and after braces,
293 and after colons and semicolons, inserted in C code.
294 c-indent-level
295 Indentation of C statements within surrounding block.
296 The surrounding block's indentation is the indentation
297 of the line on which the open-brace appears.
298 c-continued-statement-offset
299 Extra indentation given to a substatement, such as the
300 then-clause of an if or body of a while.
301 c-continued-brace-offset
302 Extra indentation given to a brace that starts a substatement.
303 This is in addition to c-continued-statement-offset.
304 c-brace-offset
305 Extra indentation for line if it starts with an open brace.
306 c-brace-imaginary-offset
307 An open brace following other text is treated as if it were
308 this far to the right of the start of its line.
309 c-argdecl-indent
310 Indentation level of declarations of C function arguments.
311 c-label-offset
312 Extra indentation for line that is a label, or case or default.
313
314 Settings for K&R and BSD indentation styles are
315 c-indent-level 5 8
316 c-continued-statement-offset 5 8
317 c-brace-offset -5 -8
318 c-argdecl-indent 0 8
319 c-label-offset -5 -8
320
321 Turning on C mode calls the value of the variable c-mode-hook with no args,
322 if that value is non-nil."
323 (interactive)
324 (kill-all-local-variables)
325 (use-local-map c-mode-map)
326 (setq major-mode 'c-mode)
327 (setq mode-name "C")
328 (setq local-abbrev-table c-mode-abbrev-table)
329 (set-syntax-table c-mode-syntax-table)
330 (make-local-variable 'paragraph-start)
331 (setq paragraph-start (concat "$\\|" page-delimiter))
332 (make-local-variable 'paragraph-separate)
333 (setq paragraph-separate paragraph-start)
334 (make-local-variable 'paragraph-ignore-fill-prefix)
335 (setq paragraph-ignore-fill-prefix t)
336 (make-local-variable 'fill-paragraph-function)
337 (setq fill-paragraph-function 'c-fill-paragraph)
338 (make-local-variable 'indent-line-function)
339 (setq indent-line-function 'c-indent-line)
340 (make-local-variable 'indent-region-function)
341 (setq indent-region-function 'c-indent-region)
342 (make-local-variable 'require-final-newline)
343 (setq require-final-newline t)
344 (make-local-variable 'outline-regexp)
345 (setq outline-regexp "[^#\n\^M]")
346 (make-local-variable 'outline-level)
347 (setq outline-level 'c-outline-level)
348 (make-local-variable 'comment-start)
349 (setq comment-start "/* ")
350 (make-local-variable 'comment-end)
351 (setq comment-end " */")
352 (make-local-variable 'comment-column)
353 (setq comment-column 32)
354 (make-local-variable 'comment-start-skip)
355 (setq comment-start-skip "/\\*+ *")
356 (make-local-variable 'comment-indent-function)
357 (setq comment-indent-function 'c-comment-indent)
358 (make-local-variable 'comment-multi-line)
359 (setq comment-multi-line t)
360 (make-local-variable 'parse-sexp-ignore-comments)
361 (setq parse-sexp-ignore-comments t)
362 (make-local-variable 'imenu-generic-expression)
363 (setq imenu-generic-expression c-imenu-generic-expression)
364 (run-hooks 'c-mode-hook))
365
366 (defun c-outline-level ()
367 (save-excursion
368 (skip-chars-forward "\t ")
369 (current-column)))
370 \f
371 ;; This is used by indent-for-comment
372 ;; to decide how much to indent a comment in C code
373 ;; based on its context.
374 (defun c-comment-indent ()
375 (if (looking-at "^/\\*")
376 0 ;Existing comment at bol stays there.
377 (let ((opoint (point)))
378 (save-excursion
379 (beginning-of-line)
380 (cond ((looking-at "[ \t]*}[ \t]*\\($\\|/\\*\\)")
381 ;; A comment following a solitary close-brace
382 ;; should have only one space.
383 (search-forward "}")
384 (1+ (current-column)))
385 ((or (looking-at "^#[ \t]*endif[ \t]*")
386 (looking-at "^#[ \t]*else[ \t]*"))
387 7) ;2 spaces after #endif
388 ((progn
389 (goto-char opoint)
390 (skip-chars-backward " \t")
391 (and (= comment-column 0) (bolp)))
392 ;; If comment-column is 0, and nothing but space
393 ;; before the comment, align it at 0 rather than 1.
394 0)
395 (t
396 (max (1+ (current-column)) ;Else indent at comment column
397 comment-column))))))) ; except leave at least one space.
398
399 (defun c-fill-paragraph (&optional arg)
400 "Like \\[fill-paragraph] but handle C comments.
401 If any of the current line is a comment or within a comment,
402 fill the comment or the paragraph of it that point is in,
403 preserving the comment indentation or line-starting decorations."
404 (interactive "P")
405 (let* (comment-start-place
406 (first-line
407 ;; Check for obvious entry to comment.
408 (save-excursion
409 (beginning-of-line)
410 (skip-chars-forward " \t\n")
411 (and (looking-at comment-start-skip)
412 (setq comment-start-place (point))))))
413 (if (and (eq major-mode 'c++-mode)
414 (save-excursion
415 (beginning-of-line)
416 (looking-at ".*//")))
417 (let (fill-prefix
418 (paragraph-start
419 ;; Lines containing just a comment start or just an end
420 ;; should not be filled into paragraphs they are next to.
421 (concat
422 paragraph-start
423 "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$"))
424 (paragraph-separate
425 (concat
426 paragraph-separate
427 "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$")))
428 (save-excursion
429 (beginning-of-line)
430 ;; Move up to first line of this comment.
431 (while (and (not (bobp)) (looking-at "[ \t]*//"))
432 (forward-line -1))
433 (if (not (looking-at ".*//"))
434 (forward-line 1))
435 ;; Find the comment start in this line.
436 (re-search-forward "[ \t]*//[ \t]*")
437 ;; Set the fill-prefix to be what all lines except the first
438 ;; should start with.
439 (let ((endcol (current-column)))
440 (skip-chars-backward " \t")
441 (setq fill-prefix
442 (concat (make-string (- (current-column) 2) ?\ )
443 "//"
444 (make-string (- endcol (current-column)) ?\ ))))
445 (save-restriction
446 ;; Narrow down to just the lines of this comment.
447 (narrow-to-region (point)
448 (save-excursion
449 (forward-line 1)
450 (while (looking-at "[ \t]*//")
451 (forward-line 1))
452 (point)))
453 (insert fill-prefix)
454 (fill-paragraph arg)
455 (delete-region (point-min)
456 (+ (point-min) (length fill-prefix))))))
457 (if (or first-line
458 ;; t if we enter a comment between start of function and this line.
459 (eq (calculate-c-indent) t)
460 ;; t if this line contains a comment starter.
461 (setq first-line
462 (save-excursion
463 (beginning-of-line)
464 (prog1
465 (re-search-forward comment-start-skip
466 (save-excursion (end-of-line)
467 (point))
468 t)
469 (setq comment-start-place (point))))))
470 ;; Inside a comment: fill one comment paragraph.
471 (let ((fill-prefix
472 ;; The prefix for each line of this paragraph
473 ;; is the appropriate part of the start of this line,
474 ;; up to the column at which text should be indented.
475 (save-excursion
476 (beginning-of-line)
477 (if (looking-at "[ \t]*/\\*.*\\*/")
478 (progn (re-search-forward comment-start-skip)
479 (make-string (current-column) ?\ ))
480 (if first-line (forward-line 1))
481
482 (let ((line-width (progn (end-of-line) (current-column))))
483 (beginning-of-line)
484 (prog1
485 (buffer-substring
486 (point)
487
488 ;; How shall we decide where the end of the
489 ;; fill-prefix is?
490 ;; calculate-c-indent-within-comment bases its value
491 ;; on the indentation of previous lines; if they're
492 ;; indented specially, it could return a column
493 ;; that's well into the current line's text. So
494 ;; we'll take at most that many space, tab, or *
495 ;; characters, and use that as our fill prefix.
496 (let ((max-prefix-end
497 (progn
498 (move-to-column
499 (calculate-c-indent-within-comment t)
500 t)
501 (point))))
502 (beginning-of-line)
503 (skip-chars-forward " \t*" max-prefix-end)
504 ;; Don't include part of comment terminator
505 ;; in the fill-prefix.
506 (and (eq (following-char) ?/)
507 (eq (preceding-char) ?*)
508 (backward-char 1))
509 (point)))
510
511 ;; If the comment is only one line followed by a blank
512 ;; line, calling move-to-column above may have added
513 ;; some spaces and tabs to the end of the line; the
514 ;; fill-paragraph function will then delete it and the
515 ;; newline following it, so we'll lose a blank line
516 ;; when we shouldn't. So delete anything
517 ;; move-to-column added to the end of the line. We
518 ;; record the line width instead of the position of the
519 ;; old line end because move-to-column might break a
520 ;; tab into spaces, and the new characters introduced
521 ;; there shouldn't be deleted.
522
523 ;; If you can see a better way to do this, please make
524 ;; the change. This seems very messy to me.
525 (delete-region (progn (move-to-column line-width)
526 (point))
527 (progn (end-of-line) (point))))))))
528
529 (paragraph-start
530 ;; Lines containing just a comment start or just an end
531 ;; should not be filled into paragraphs they are next to.
532 (concat
533 paragraph-start
534 "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$"))
535 (paragraph-separate
536 (concat
537 paragraph-separate
538 "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$"))
539 (chars-to-delete 0))
540 (save-restriction
541 ;; Don't fill the comment together with the code following it.
542 ;; So temporarily exclude everything before the comment start,
543 ;; and everything after the line where the comment ends.
544 ;; If comment-start-place is non-nil, the comment starter is there.
545 ;; Otherwise, point is inside the comment.
546 (narrow-to-region (save-excursion
547 (if comment-start-place
548 (goto-char comment-start-place)
549 (search-backward "/*"))
550 ;; Protect text before the comment start
551 ;; by excluding it. Add spaces to bring back
552 ;; proper indentation of that point.
553 (let ((column (current-column)))
554 (prog1 (point)
555 (setq chars-to-delete column)
556 (insert-char ?\ column))))
557 (save-excursion
558 (if comment-start-place
559 (goto-char (+ comment-start-place 2)))
560 (search-forward "*/" nil 'move)
561 (forward-line 1)
562 (point)))
563 (save-excursion
564 (goto-char (point-max))
565 (forward-line -1)
566 ;; And comment terminator was on a separate line before,
567 ;; keep it that way.
568 ;; This also avoids another problem:
569 ;; if the fill-prefix ends in a *, it could eat up
570 ;; the * of the comment terminator.
571 (if (looking-at "[ \t]*\\*/")
572 (narrow-to-region (point-min) (point))))
573 (fill-paragraph arg)
574 (save-excursion
575 ;; Delete the chars we inserted to avoid clobbering
576 ;; the stuff before the comment start.
577 (goto-char (point-min))
578 (if (> chars-to-delete 0)
579 (delete-region (point) (+ (point) chars-to-delete)))
580 ;; Find the comment ender (should be on last line of buffer,
581 ;; given the narrowing) and don't leave it on its own line.
582 ;; Do this with a fill command, so as to preserve sentence
583 ;; boundaries.
584 (goto-char (point-max))
585 (forward-line -1)
586 (search-forward "*/" nil 'move)
587 (beginning-of-line)
588 (if (looking-at "[ \t]*\\*/")
589 (let ((fill-column (+ fill-column 9999)))
590 (forward-line -1)
591 (fill-region-as-paragraph (point) (point-max)))))))
592 ;; Outside of comments: do ordinary filling.
593 (fill-paragraph arg)))
594 t))
595
596 (defun electric-c-brace (arg)
597 "Insert character and correct line's indentation."
598 (interactive "P")
599 (let (insertpos)
600 (if (and (not arg)
601 (eolp)
602 (or (save-excursion
603 (skip-chars-backward " \t")
604 (bolp))
605 (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
606 (progn
607 (insert last-command-char)
608 (c-indent-line)
609 (if c-auto-newline
610 (progn
611 (newline)
612 ;; (newline) may have done auto-fill
613 (setq insertpos (- (point) 2))
614 (c-indent-line)))
615 (save-excursion
616 (if insertpos (goto-char (1+ insertpos)))
617 (delete-char -1))))
618 (if insertpos
619 (save-excursion
620 (goto-char insertpos)
621 (self-insert-command (prefix-numeric-value arg)))
622 (self-insert-command (prefix-numeric-value arg)))))
623
624 (defun electric-c-sharp-sign (arg)
625 "Insert character and correct line's indentation."
626 (interactive "P")
627 (if (save-excursion
628 (skip-chars-backward " \t")
629 (bolp))
630 (let ((c-auto-newline nil))
631 (electric-c-terminator arg))
632 (self-insert-command (prefix-numeric-value arg))))
633
634 (defun electric-c-semi (arg)
635 "Insert character and correct line's indentation."
636 (interactive "P")
637 (if c-auto-newline
638 (electric-c-terminator arg)
639 (self-insert-command (prefix-numeric-value arg))))
640
641 (defun electric-c-terminator (arg)
642 "Insert character and correct line's indentation."
643 (interactive "P")
644 (let (insertpos (end (point)))
645 (if (and (not arg) (eolp)
646 (not (save-excursion
647 (beginning-of-line)
648 (skip-chars-forward " \t")
649 (or (= (following-char) ?#)
650 ;; Colon is special only after a label, or case ....
651 ;; So quickly rule out most other uses of colon
652 ;; and do no indentation for them.
653 (and (eq last-command-char ?:)
654 (not (looking-at c-switch-label-regexp))
655 (save-excursion
656 (skip-chars-forward "a-zA-Z0-9_$")
657 (skip-chars-forward " \t")
658 (< (point) end)))
659 (progn
660 (beginning-of-defun)
661 (let ((pps (parse-partial-sexp (point) end)))
662 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
663 (progn
664 (insert last-command-char)
665 (c-indent-line)
666 (and c-auto-newline
667 (not (c-inside-parens-p))
668 (progn
669 (newline)
670 ;; (newline) may have done auto-fill
671 (setq insertpos (- (point) 2))
672 (c-indent-line)))
673 (save-excursion
674 (if insertpos (goto-char (1+ insertpos)))
675 (delete-char -1))))
676 (if insertpos
677 (save-excursion
678 (goto-char insertpos)
679 (self-insert-command (prefix-numeric-value arg)))
680 (self-insert-command (prefix-numeric-value arg)))))
681
682 (defun c-inside-parens-p ()
683 (condition-case ()
684 (save-excursion
685 (save-restriction
686 (narrow-to-region (point)
687 (progn (beginning-of-defun) (point)))
688 (goto-char (point-max))
689 (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
690 (error nil)))
691 \f
692 (defun c-indent-command (&optional whole-exp)
693 "Indent current line as C code, or in some cases insert a tab character.
694 If `c-tab-always-indent' is non-nil (the default), always indent current line.
695 Otherwise, indent the current line only if point is at the left margin or
696 in the line's indentation; otherwise insert a tab.
697
698 A numeric argument, regardless of its value, means indent rigidly all the
699 lines of the expression starting after point so that this line becomes
700 properly indented. The relative indentation among the lines of the
701 expression are preserved."
702 (interactive "P")
703 (if whole-exp
704 ;; If arg, always indent this line as C
705 ;; and shift remaining lines of expression the same amount.
706 (let ((shift-amt (c-indent-line))
707 beg end)
708 (save-excursion
709 (if c-tab-always-indent
710 (beginning-of-line))
711 ;; Find beginning of following line.
712 (save-excursion
713 (forward-line 1) (setq beg (point)))
714 ;; Find first beginning-of-sexp for sexp extending past this line.
715 (while (< (point) beg)
716 (forward-sexp 1)
717 (setq end (point))
718 (skip-chars-forward " \t\n")))
719 (if (> end beg)
720 (indent-code-rigidly beg end shift-amt "#")))
721 (if (and (not c-tab-always-indent)
722 (save-excursion
723 (skip-chars-backward " \t")
724 (not (bolp))))
725 (insert-tab)
726 (c-indent-line))))
727
728 (defun c-indent-line ()
729 "Indent current line as C code.
730 Return the amount the indentation changed by."
731 (let ((indent (calculate-c-indent nil))
732 beg shift-amt
733 (case-fold-search nil)
734 (pos (- (point-max) (point))))
735 (beginning-of-line)
736 (setq beg (point))
737 (cond ((eq indent nil)
738 (setq indent (current-indentation)))
739 ((eq indent t)
740 (setq indent (calculate-c-indent-within-comment)))
741 ((looking-at "[ \t]*#")
742 (setq indent 0))
743 (t
744 (skip-chars-forward " \t")
745 (if (listp indent) (setq indent (car indent)))
746 (cond ((or (looking-at c-switch-label-regexp)
747 (and (looking-at "[A-Za-z]")
748 (save-excursion
749 (forward-sexp 1)
750 (looking-at ":"))))
751 (setq indent (max 1 (+ indent c-label-offset))))
752 ((and (looking-at "else\\b")
753 (not (looking-at "else\\s_")))
754 (setq indent (save-excursion
755 (c-backward-to-start-of-if)
756 (current-indentation))))
757 ((and (looking-at "}[ \t]*else\\b")
758 (not (looking-at "}[ \t]*else\\s_")))
759 (setq indent (save-excursion
760 (forward-char)
761 (backward-sexp)
762 (c-backward-to-start-of-if)
763 (current-indentation))))
764 ((and (looking-at "while\\b")
765 (not (looking-at "while\\s_"))
766 (save-excursion
767 (c-backward-to-start-of-do)))
768 ;; This is a `while' that ends a do-while.
769 (setq indent (save-excursion
770 (c-backward-to-start-of-do)
771 (current-indentation))))
772 ((= (following-char) ?})
773 (setq indent (- indent c-indent-level)))
774 ((= (following-char) ?{)
775 (setq indent (+ indent c-brace-offset))))))
776 (skip-chars-forward " \t")
777 (setq shift-amt (- indent (current-column)))
778 (if (zerop shift-amt)
779 (if (> (- (point-max) pos) (point))
780 (goto-char (- (point-max) pos)))
781 (delete-region beg (point))
782 (indent-to indent)
783 ;; If initial point was within line's indentation,
784 ;; position after the indentation. Else stay at same point in text.
785 (if (> (- (point-max) pos) (point))
786 (goto-char (- (point-max) pos))))
787 shift-amt))
788
789 (defun calculate-c-indent (&optional parse-start)
790 "Return appropriate indentation for current line as C code.
791 In usual case returns an integer: the column to indent to.
792 Returns nil if line starts inside a string, t if in a comment."
793 (save-excursion
794 (beginning-of-line)
795 (let ((indent-point (point))
796 (case-fold-search nil)
797 state
798 containing-sexp)
799 (if parse-start
800 (goto-char parse-start)
801 (beginning-of-defun))
802 (while (< (point) indent-point)
803 (setq parse-start (point))
804 (setq state (parse-partial-sexp (point) indent-point 0))
805 (setq containing-sexp (car (cdr state))))
806 (cond ((or (nth 3 state) (nth 4 state))
807 ;; return nil or t if should not change this line
808 (nth 4 state))
809 ((null containing-sexp)
810 ;; Line is at top level. May be data or function definition,
811 ;; or may be function argument declaration.
812 ;; Indent like the previous top level line
813 ;; unless that ends in a closeparen without semicolon,
814 ;; in which case this line is the first argument decl.
815 (goto-char indent-point)
816 (skip-chars-forward " \t")
817 (if (= (following-char) ?{)
818 0 ; Unless it starts a function body
819 (c-backward-to-noncomment (or parse-start (point-min)))
820 ;; Look at previous line that's at column 0
821 ;; to determine whether we are in top-level decls
822 ;; or function's arg decls. Set basic-indent accordingly.
823 (let ((basic-indent
824 (save-excursion
825 (re-search-backward "^[^ \^L\t\n#]" nil 'move)
826 (let (comment lim)
827 ;; Recognize the DEFUN macro in Emacs.
828 (if (save-excursion
829 ;; Move down to the (putative) argnames line.
830 (while (and (not (eobp))
831 (not (looking-at " *[({}#/]")))
832 (forward-line 1))
833 ;; Go back to the DEFUN, if it is one.
834 (condition-case nil
835 (backward-sexp 1)
836 (error))
837 (beginning-of-line)
838 (looking-at "DEFUN\\b"))
839 c-argdecl-indent
840 (if (and (looking-at "\\sw\\|\\s_")
841 ;; This is careful to stop at the first
842 ;; paren if we have
843 ;; int foo Proto ((int, int));
844 (looking-at "[^\"\n=(]*(")
845 (progn
846 (goto-char (1- (match-end 0)))
847 ;; Skip any number of paren-groups.
848 ;; Consider typedef int (*fcn) (int);
849 (while (= (following-char) ?\()
850 (setq lim (point))
851 (condition-case nil
852 (forward-sexp 1)
853 (error))
854 (skip-chars-forward " \t\f"))
855 ;; Have we reached something
856 ;; that shows this isn't a function
857 ;; definition?
858 (and (< (point) indent-point)
859 (not (memq (following-char)
860 '(?\, ?\;)))))
861 ;; Make sure the "function decl" we found
862 ;; is not inside a comment.
863 (progn
864 ;; Move back to the `(' starting arglist
865 (goto-char lim)
866 (beginning-of-line)
867 (while (and (not comment)
868 (search-forward "/*" lim t))
869 (setq comment
870 (not (search-forward "*/" lim t))))
871 (not comment)))
872 c-argdecl-indent 0))))))
873 basic-indent)))
874
875 ;; ;; Now add a little if this is a continuation line.
876 ;; (+ basic-indent (if (or (bobp)
877 ;; (memq (preceding-char) '(?\) ?\; ?\}))
878 ;; ;; Line with zero indentation
879 ;; ;; is probably the return-type
880 ;; ;; of a function definition,
881 ;; ;; so following line is function name.
882 ;; (= (current-indentation) 0))
883 ;; 0 c-continued-statement-offset))
884
885 ((/= (char-after containing-sexp) ?{)
886 ;; line is expression, not statement:
887 ;; indent to just after the surrounding open.
888 (goto-char (1+ containing-sexp))
889 (current-column))
890 (t
891 ;; Statement level. Is it a continuation or a new statement?
892 ;; Find previous non-comment character.
893 (goto-char indent-point)
894 (c-backward-to-noncomment containing-sexp)
895 ;; Back up over label lines, since they don't
896 ;; affect whether our line is a continuation.
897 (while (or (eq (preceding-char) ?\,)
898 (and (eq (preceding-char) ?:)
899 (or (eq (char-after (- (point) 2)) ?\')
900 (memq (char-syntax (char-after (- (point) 2)))
901 '(?w ?_)))))
902 (if (eq (preceding-char) ?\,)
903 (progn (forward-char -1)
904 (c-backward-to-start-of-continued-exp containing-sexp)))
905 (beginning-of-line)
906 (c-backward-to-noncomment containing-sexp))
907 ;; Check for a preprocessor statement or its continuation lines.
908 ;; Move back to end of previous non-preprocessor line,
909 ;; or possibly beginning of buffer.
910 (let ((found (point)) stop)
911 (while (not stop)
912 (beginning-of-line)
913 (cond ((bobp)
914 (setq found (point)
915 stop t))
916 ((save-excursion (forward-char -1)
917 (= (preceding-char) ?\\))
918 (forward-char -1))
919 ;; This line is not preceded by a backslash.
920 ;; So either it starts a preprocessor command
921 ;; or any following continuation lines
922 ;; should not be skipped.
923 ((= (following-char) ?#)
924 (forward-char -1)
925 (setq found (point)))
926 (t (setq stop t))))
927 (goto-char found))
928 ;; Now we get the answer.
929 (if (and (not (memq (preceding-char) '(0 ?\, ?\; ?\} ?\{)))
930 ;; But don't treat a line with a close-brace
931 ;; as a continuation. It is probably the
932 ;; end of an enum type declaration.
933 (save-excursion
934 (goto-char indent-point)
935 (skip-chars-forward " \t")
936 (not (= (following-char) ?}))))
937 ;; This line is continuation of preceding line's statement;
938 ;; indent c-continued-statement-offset more than the
939 ;; previous line of the statement.
940 (progn
941 (c-backward-to-start-of-continued-exp containing-sexp)
942 (+ c-continued-statement-offset (current-column)
943 (if (save-excursion (goto-char indent-point)
944 (skip-chars-forward " \t")
945 (eq (following-char) ?{))
946 c-continued-brace-offset 0)))
947 ;; This line starts a new statement.
948 ;; Position following last unclosed open.
949 (goto-char containing-sexp)
950 ;; Is line first statement after an open-brace?
951 (or
952 ;; If no, find that first statement and indent like it.
953 (save-excursion
954 (forward-char 1)
955 (let ((colon-line-end 0))
956 (while (progn (skip-chars-forward " \t\n")
957 (looking-at "#\\|/\\*\\|case[ \t\n'/(].*:\\|[a-zA-Z0-9_$]*:"))
958 ;; Skip over comments and labels following openbrace.
959 (cond ((= (following-char) ?\#)
960 (forward-line 1))
961 ((= (following-char) ?\/)
962 (forward-char 2)
963 (search-forward "*/" nil 'move))
964 ;; case or label:
965 (t
966 (save-excursion (end-of-line)
967 (setq colon-line-end (point)))
968 (search-forward ":"))))
969 ;; The first following code counts
970 ;; if it is before the line we want to indent.
971 (and (< (point) indent-point)
972 (-
973 (if (> colon-line-end (point))
974 (- (current-indentation) c-label-offset)
975 (current-column))
976 ;; If prev stmt starts with open-brace, that
977 ;; open brace was offset by c-brace-offset.
978 ;; Compensate to get the column where
979 ;; an ordinary statement would start.
980 (if (= (following-char) ?\{) c-brace-offset 0)))))
981 ;; If no previous statement,
982 ;; indent it relative to line brace is on.
983 (calculate-c-indent-after-brace))))))))
984
985 (defun calculate-c-indent-after-brace ()
986 "Return the proper C indent for the first line after an open-brace.
987 This function is called with point before the brace."
988 ;; For open brace in column zero, don't let statement
989 ;; start there too. If c-indent-level is zero,
990 ;; use c-brace-offset + c-continued-statement-offset instead.
991 ;; For open-braces not the first thing in a line,
992 ;; add in c-brace-imaginary-offset.
993 (+ (if (and (bolp) (zerop c-indent-level))
994 (+ c-brace-offset c-continued-statement-offset)
995 c-indent-level)
996 ;; Move back over whitespace before the openbrace.
997 ;; If openbrace is not first nonwhite thing on the line,
998 ;; add the c-brace-imaginary-offset.
999 (progn (skip-chars-backward " \t")
1000 (if (bolp) 0 c-brace-imaginary-offset))
1001 ;; If the openbrace is preceded by a parenthesized exp,
1002 ;; move to the beginning of that;
1003 ;; possibly a different line
1004 (progn
1005 (if (eq (preceding-char) ?\))
1006 (forward-sexp -1))
1007 ;; Get initial indentation of the line we are on.
1008 (current-indentation))))
1009
1010 (defun calculate-c-indent-within-comment (&optional after-star)
1011 "Return the indentation amount for line inside a block comment.
1012 Optional arg AFTER-STAR means, if lines in the comment have a leading star,
1013 return the indentation of the text that would follow this star."
1014 (let (end star-start)
1015 (save-excursion
1016 (beginning-of-line)
1017 (skip-chars-forward " \t")
1018 (setq star-start (= (following-char) ?\*))
1019 (skip-chars-backward " \t\n")
1020 (setq end (point))
1021 (beginning-of-line)
1022 (skip-chars-forward " \t")
1023 (if after-star
1024 (and (looking-at "\\*")
1025 (re-search-forward "\\*[ \t]*")))
1026 (and (re-search-forward "/\\*[ \t]*" end t)
1027 star-start
1028 (not after-star)
1029 (goto-char (1+ (match-beginning 0))))
1030 (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
1031 (1+ (current-column))
1032 (current-column)))))
1033
1034
1035 (defun c-backward-to-noncomment (lim)
1036 (let (opoint stop)
1037 (while (not stop)
1038 (skip-chars-backward " \t\n\f" lim)
1039 (setq opoint (point))
1040 (if (and (>= (point) (+ 2 lim))
1041 (save-excursion
1042 (forward-char -2)
1043 (looking-at "\\*/")))
1044 (search-backward "/*" lim 'move)
1045 (setq stop (or (<= (point) lim)
1046 (save-excursion
1047 (beginning-of-line)
1048 (skip-chars-forward " \t")
1049 (not (looking-at "#")))))
1050 (or stop (beginning-of-line))))))
1051
1052 (defun c-backward-to-start-of-continued-exp (lim)
1053 (if (memq (preceding-char) '(?\) ?\"))
1054 (forward-sexp -1))
1055 (beginning-of-line)
1056 (if (<= (point) lim)
1057 (goto-char (1+ lim)))
1058 (skip-chars-forward " \t"))
1059
1060 (defun c-backward-to-start-of-if (&optional limit)
1061 "Move to the start of the last \"unbalanced\" `if'."
1062 (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
1063 (let ((if-level 1)
1064 (case-fold-search nil))
1065 (while (and (not (bobp)) (not (zerop if-level)))
1066 (backward-sexp 1)
1067 (cond ((and (looking-at "else\\b")
1068 (not (looking-at "else\\s_")))
1069 (setq if-level (1+ if-level)))
1070 ((and (looking-at "if\\b")
1071 (not (looking-at "if\\s_")))
1072 (setq if-level (1- if-level)))
1073 ((< (point) limit)
1074 (setq if-level 0)
1075 (goto-char limit))))))
1076
1077 (defun c-backward-to-start-of-do (&optional limit)
1078 "If point follows a `do' statement, move to beginning of it and return t.
1079 Otherwise return nil and don't move point."
1080 (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
1081 (let ((first t)
1082 (startpos (point))
1083 (done nil))
1084 (while (not done)
1085 (let ((next-start (point)))
1086 (condition-case nil
1087 ;; Move back one token or one brace or paren group.
1088 (backward-sexp 1)
1089 ;; If we find an open-brace, we lose.
1090 (error (setq done 'fail)))
1091 (if done
1092 nil
1093 ;; If we reached a `do', we win.
1094 (if (looking-at "do\\b")
1095 (setq done 'succeed)
1096 ;; Otherwise, if we skipped a semicolon, we lose.
1097 ;; (Exception: we can skip one semicolon before getting
1098 ;; to a the last token of the statement, unless that token
1099 ;; is a close brace.)
1100 (if (save-excursion
1101 (forward-sexp 1)
1102 (or (and (not first) (= (preceding-char) ?}))
1103 (search-forward ";" next-start t
1104 (if (and first
1105 (/= (preceding-char) ?}))
1106 2 1))))
1107 (setq done 'fail)
1108 (setq first nil)
1109 ;; If we go too far back in the buffer, we lose.
1110 (if (< (point) limit)
1111 (setq done 'fail)))))))
1112 (if (eq done 'succeed)
1113 t
1114 (goto-char startpos)
1115 nil)))
1116 \f
1117 (defun c-beginning-of-statement (count)
1118 "Go to the beginning of the innermost C statement.
1119 With prefix arg, go back N - 1 statements. If already at the beginning of a
1120 statement then go to the beginning of the preceding one.
1121 If within a string or comment, or next to a comment (only whitespace between),
1122 move by sentences instead of statements."
1123 (interactive "p")
1124 (let ((here (point)) state)
1125 (save-excursion
1126 (beginning-of-defun)
1127 (setq state (parse-partial-sexp (point) here nil nil)))
1128 (if (or (nth 3 state) (nth 4 state)
1129 (looking-at (concat "[ \t]*" comment-start-skip))
1130 (save-excursion (skip-chars-backward " \t")
1131 (goto-char (- (point) 2))
1132 (looking-at "\\*/")))
1133 (forward-sentence (- count))
1134 (while (> count 0)
1135 (c-beginning-of-statement-1)
1136 (setq count (1- count)))
1137 (while (< count 0)
1138 (c-end-of-statement-1)
1139 (setq count (1+ count))))))
1140
1141 (defun c-end-of-statement (count)
1142 "Go to the end of the innermost C statement.
1143 With prefix arg, go forward N - 1 statements.
1144 Move forward to end of the next statement if already at end.
1145 If within a string or comment, move by sentences instead of statements."
1146 (interactive "p")
1147 (c-beginning-of-statement (- count)))
1148
1149 (defun c-beginning-of-statement-1 ()
1150 (let ((last-begin (point))
1151 (first t))
1152 (condition-case ()
1153 (progn
1154 (while (and (not (bobp))
1155 (progn
1156 (backward-sexp 1)
1157 (or first
1158 (not (re-search-forward "[;{}]" last-begin t)))))
1159 (setq last-begin (point) first nil))
1160 (goto-char last-begin))
1161 (error (if first (backward-up-list 1) (goto-char last-begin))))))
1162
1163 (defun c-end-of-statement-1 ()
1164 (condition-case ()
1165 (progn
1166 (while (and (not (eobp))
1167 (let ((beg (point)))
1168 (forward-sexp 1)
1169 (let ((end (point)))
1170 (save-excursion
1171 (goto-char beg)
1172 (not (re-search-forward "[;{}]" end t)))))))
1173 (re-search-backward "[;}]")
1174 (forward-char 1))
1175 (error
1176 (let ((beg (point)))
1177 (backward-up-list -1)
1178 (let ((end (point)))
1179 (goto-char beg)
1180 (search-forward ";" end 'move))))))
1181 \f
1182 (defun mark-c-function ()
1183 "Put mark at end of C function, point at beginning."
1184 (interactive)
1185 (push-mark (point))
1186 (end-of-defun)
1187 (push-mark (point) nil t)
1188 (beginning-of-defun)
1189 (backward-paragraph))
1190 \f
1191 ;; Idea of ENDPOS is, indent each line, stopping when
1192 ;; ENDPOS is encountered. But it's too much of a pain to make that work.
1193 (defun indent-c-exp (&optional endpos)
1194 "Indent each line of the C grouping following point."
1195 (interactive)
1196 (let* ((indent-stack (list nil))
1197 (opoint (point)) ;; May be altered below.
1198 (contain-stack
1199 (list (if endpos
1200 (let (funbeg)
1201 ;; Find previous fcn-start.
1202 (save-excursion (forward-char 1)
1203 (beginning-of-defun)
1204 (setq funbeg (point)))
1205 (setq opoint funbeg)
1206 ;; Try to find containing open,
1207 ;; but don't scan past that fcn-start.
1208 (save-restriction
1209 (narrow-to-region funbeg (point))
1210 (condition-case nil
1211 (save-excursion
1212 (backward-up-list 1)
1213 (point))
1214 ;; We gave up: must be between fcns.
1215 ;; Set opoint to beg of prev fcn
1216 ;; since otherwise calculate-c-indent
1217 ;; will get wrong answers.
1218 (error (setq opoint funbeg)
1219 (point)))))
1220 (point))))
1221 (case-fold-search nil)
1222 restart outer-loop-done inner-loop-done state ostate
1223 this-indent last-sexp
1224 at-else at-brace at-while
1225 last-depth this-point
1226 (next-depth 0))
1227 ;; If the braces don't match, get an error right away.
1228 (save-excursion
1229 (forward-sexp 1))
1230 ;; Realign the comment on the first line, even though we don't reindent it.
1231 (save-excursion
1232 (let ((beg (point)))
1233 (and (re-search-forward
1234 comment-start-skip
1235 (save-excursion (end-of-line) (point)) t)
1236 ;; Make sure this isn't a comment alone on a line
1237 ;; (which should be indented like code instead).
1238 (save-excursion
1239 (goto-char (match-beginning 0))
1240 (skip-chars-backward " \t")
1241 (not (bolp)))
1242 ;; Make sure the comment starter we found
1243 ;; is not actually in a string or quoted.
1244 (let ((new-state
1245 (parse-partial-sexp beg (point)
1246 nil nil state)))
1247 (and (not (nth 3 new-state)) (not (nth 5 new-state))))
1248 (progn (indent-for-comment) (beginning-of-line)))))
1249 (save-excursion
1250 (setq outer-loop-done nil)
1251 (while (and (not (eobp))
1252 (if endpos (< (point) endpos)
1253 (not outer-loop-done)))
1254 (setq last-depth next-depth)
1255 ;; Compute how depth changes over this line
1256 ;; plus enough other lines to get to one that
1257 ;; does not end inside a comment or string.
1258 ;; Meanwhile, do appropriate indentation on comment lines.
1259 (setq inner-loop-done nil)
1260 (while (and (not inner-loop-done)
1261 (not (and (eobp) (setq outer-loop-done t))))
1262 (setq ostate state)
1263 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1264 nil nil state))
1265 (setq next-depth (car state))
1266 (if (and (car (cdr (cdr state)))
1267 (>= (car (cdr (cdr state))) 0))
1268 (setq last-sexp (car (cdr (cdr state)))))
1269 ;; If this line started within a comment, indent it as such.
1270 (if (or (nth 4 ostate) (nth 7 ostate))
1271 (c-indent-line))
1272 ;; If it ends outside of comments or strings, exit the inner loop.
1273 ;; Otherwise move on to next line.
1274 (if (or (nth 3 state) (nth 4 state) (nth 7 state))
1275 (forward-line 1)
1276 (setq inner-loop-done t)))
1277 (and endpos
1278 (while (< next-depth 0)
1279 (setq indent-stack (append indent-stack (list nil)))
1280 (setq contain-stack (append contain-stack (list nil)))
1281 (setq next-depth (1+ next-depth))
1282 (setq last-depth (1+ last-depth))
1283 (setcar (nthcdr 6 state) (1+ (nth 6 state)))))
1284 (setq outer-loop-done (and (not endpos) (<= next-depth 0)))
1285 (if outer-loop-done
1286 nil
1287 ;; If this line had ..))) (((.. in it, pop out of the levels
1288 ;; that ended anywhere in this line, even if the final depth
1289 ;; doesn't indicate that they ended.
1290 (while (> last-depth (nth 6 state))
1291 (setq indent-stack (cdr indent-stack)
1292 contain-stack (cdr contain-stack)
1293 last-depth (1- last-depth)))
1294 (if (/= last-depth next-depth)
1295 (setq last-sexp nil))
1296 ;; Add levels for any parens that were started in this line.
1297 (while (< last-depth next-depth)
1298 (setq indent-stack (cons nil indent-stack)
1299 contain-stack (cons nil contain-stack)
1300 last-depth (1+ last-depth)))
1301 (if (null (car contain-stack))
1302 (setcar contain-stack (or (car (cdr state))
1303 (save-excursion (forward-sexp -1)
1304 (point)))))
1305 (forward-line 1)
1306 (skip-chars-forward " \t")
1307 ;; Don't really reindent if the line is just whitespace,
1308 ;; or if it is past the endpos.
1309 ;; (The exit test in the outer while
1310 ;; does not exit until we have passed the first line
1311 ;; past the region.)
1312 (if (or (eolp) (and endpos (>= (point) endpos)))
1313 nil
1314 ;; Is this line in a new nesting level?
1315 ;; In other words, is this the first line that
1316 ;; starts in the new level?
1317 (if (and (car indent-stack)
1318 (>= (car indent-stack) 0))
1319 nil
1320 ;; Yes.
1321 ;; Compute the standard indent for this level.
1322 (let (val)
1323 (if (= (char-after (car contain-stack)) ?{)
1324 (save-excursion
1325 (goto-char (car contain-stack))
1326 (setq val (calculate-c-indent-after-brace)))
1327 (setq val (calculate-c-indent
1328 (if (car indent-stack)
1329 (- (car indent-stack))
1330 opoint))))
1331 ;; t means we are in a block comment and should
1332 ;; calculate accordingly.
1333 (if (eq val t)
1334 (setq val (calculate-c-indent-within-comment)))
1335 (setcar indent-stack val)))
1336 ;; Adjust indent of this individual line
1337 ;; based on its predecessor.
1338 ;; Handle continuation lines, if, else, while, and so on.
1339 (if (/= (char-after (car contain-stack)) ?{)
1340 (setq this-indent (car indent-stack))
1341 ;; Line is at statement level.
1342 ;; Is it a new statement? Is it an else?
1343 ;; Find last non-comment character before this line
1344 (save-excursion
1345 (setq this-point (point))
1346 (setq at-else (and (looking-at "else\\b")
1347 (not (looking-at "else\\s_"))))
1348 (setq at-brace (= (following-char) ?{))
1349 (setq at-while (and (looking-at "while\\b")
1350 (not (looking-at "while\\s_"))))
1351 (if (= (following-char) ?})
1352 (setq this-indent (car indent-stack))
1353 (c-backward-to-noncomment opoint)
1354 (if (not (memq (preceding-char) '(0 ?\, ?\; ?} ?: ?{)))
1355 ;; Preceding line did not end in comma or semi;
1356 ;; indent this line c-continued-statement-offset
1357 ;; more than previous.
1358 (progn
1359 (c-backward-to-start-of-continued-exp (car contain-stack))
1360 (setq this-indent
1361 (+ c-continued-statement-offset (current-column)
1362 (if at-brace c-continued-brace-offset 0))))
1363 ;; Preceding line ended in comma or semi;
1364 ;; use the standard indent for this level.
1365 (cond (at-else (progn (c-backward-to-start-of-if opoint)
1366 (setq this-indent
1367 (current-indentation))))
1368 ((and at-while (c-backward-to-start-of-do opoint))
1369 (setq this-indent (current-indentation)))
1370 ((eq (preceding-char) ?\,)
1371 (goto-char this-point)
1372 (setq this-indent (calculate-c-indent)))
1373 (t (setq this-indent (car indent-stack))))))))
1374 ;; Adjust line indentation according to its contents
1375 (if (or (looking-at c-switch-label-regexp)
1376 (and (looking-at "[A-Za-z]")
1377 (save-excursion
1378 (forward-sexp 1)
1379 (looking-at ":"))))
1380 (setq this-indent (max 1 (+ this-indent c-label-offset))))
1381 (if (= (following-char) ?})
1382 (setq this-indent (- this-indent c-indent-level)))
1383 (if (= (following-char) ?{)
1384 ;; Don't move an open-brace in column 0.
1385 ;; This is good when constructs such as
1386 ;; `extern "C" {' surround a function definition
1387 ;; that should be indented as usual.
1388 ;; It is also good for nested functions.
1389 ;; It is bad when an open-brace is indented at column 0
1390 ;; and you want to fix that, but we can't win 'em all.
1391 (if (zerop (current-column))
1392 (setq this-indent 0)
1393 (setq this-indent (+ this-indent c-brace-offset))))
1394 ;; Don't leave indentation in empty lines.
1395 (if (eolp) (setq this-indent 0))
1396 ;; Put chosen indentation into effect.
1397 (or (= (current-column) this-indent)
1398 (= (following-char) ?\#)
1399 (progn
1400 (delete-region (point) (progn (beginning-of-line) (point)))
1401 (indent-to this-indent)))
1402 ;; Indent any comment following the text.
1403 (or (looking-at comment-start-skip)
1404 (save-excursion
1405 (let ((beg (point)))
1406 (and (re-search-forward
1407 comment-start-skip
1408 (save-excursion (end-of-line) (point)) t)
1409 ;; Make sure the comment starter we found
1410 ;; is not actually in a string or quoted.
1411 (let ((new-state
1412 (parse-partial-sexp beg (point)
1413 nil nil state)))
1414 (and (not (nth 3 new-state)) (not (nth 5 new-state))))
1415 (indent-for-comment)))))))))))
1416
1417 ;; Look at all comment-start strings in the current line after point.
1418 ;; Return t if one of them starts a real comment.
1419 ;; This is not used yet, because indent-for-comment
1420 ;; isn't smart enough to handle the cases this can find.
1421 (defun indent-c-find-real-comment ()
1422 (let (win)
1423 (while (and (not win)
1424 (re-search-forward comment-start-skip
1425 (save-excursion (end-of-line) (point))
1426 t))
1427 ;; Make sure the comment start is not quoted.
1428 (let ((state-1
1429 (parse-partial-sexp
1430 (save-excursion (beginning-of-line) (point))
1431 (point) nil nil state)))
1432 (setq win (and (null (nth 3 state-1)) (null (nth 5 state-1))))))
1433 win))
1434
1435 ;; Indent every line whose first char is between START and END inclusive.
1436 (defun c-indent-region (start end)
1437 (save-excursion
1438 (goto-char start)
1439 ;; Advance to first nonblank line.
1440 (skip-chars-forward " \t\n")
1441 (beginning-of-line)
1442 (let ((endmark (copy-marker end))
1443 (c-tab-always-indent t))
1444 (while (and (bolp) (not (eobp)) (< (point) endmark))
1445 ;; Indent one line as with TAB.
1446 (let ((shift-amt (c-indent-line))
1447 nextline sexpbeg sexpend)
1448 (if (save-excursion (beginning-of-line) (looking-at "[ \t]*#"))
1449 (forward-line 1)
1450 (save-excursion
1451 ;; Find beginning of following line.
1452 (save-excursion
1453 (forward-line 1) (setq nextline (point)))
1454 ;; Find first beginning-of-sexp for sexp extending past this line.
1455 (beginning-of-line)
1456 (while (< (point) nextline)
1457 (condition-case nil
1458 (progn
1459 (forward-sexp 1)
1460 (setq sexpend (point-marker)))
1461 (error (setq sexpend nil)
1462 (goto-char nextline)))
1463 (skip-chars-forward " \t\n"))
1464 (if sexpend
1465 (progn
1466 ;; Make sure the sexp we found really starts on the
1467 ;; current line and extends past it.
1468 (goto-char sexpend)
1469 (backward-sexp 1)
1470 (setq sexpbeg (point)))))
1471 ;; If that sexp ends within the region,
1472 ;; indent it all at once, fast.
1473 (if (and sexpend (> sexpend nextline) (<= sexpend endmark)
1474 (< sexpbeg nextline))
1475 (progn
1476 (indent-c-exp)
1477 (goto-char sexpend)))
1478 ;; Move to following line and try again.
1479 (and sexpend (set-marker sexpend nil))
1480 (forward-line 1))))
1481 (set-marker endmark nil))))
1482 \f
1483 (defun set-c-style (style &optional global)
1484 "Set C-mode variables to use one of several different indentation styles.
1485 The arguments are a string representing the desired style
1486 and a flag which, if non-nil, means to set the style globally.
1487 \(Interactively, the flag comes from the prefix argument.)
1488 Available styles are GNU, K&R, BSD and Whitesmith."
1489 (interactive (list (let ((completion-ignore-case t))
1490 (completing-read "Use which C indentation style? "
1491 c-style-alist nil t))
1492 current-prefix-arg))
1493 (let ((vars (cdr (assoc style c-style-alist))))
1494 (or vars
1495 (error "Invalid C indentation style `%s'" style))
1496 (while vars
1497 (or global
1498 (make-local-variable (car (car vars))))
1499 (set (car (car vars)) (cdr (car vars)))
1500 (setq vars (cdr vars)))))
1501 \f
1502 ;;; This page handles insertion and removal of backslashes for C macros.
1503
1504 (defvar c-backslash-column 48
1505 "*Minimum column for end-of-line backslashes of macro definitions.")
1506
1507 (defun c-backslash-region (from to delete-flag)
1508 "Insert, align, or delete end-of-line backslashes on the lines in the region.
1509 With no argument, inserts backslashes and aligns existing backslashes.
1510 With an argument, deletes the backslashes.
1511
1512 This function does not modify the last line of the region if the region ends
1513 right at the start of the following line; it does not modify blank lines
1514 at the start of the region. So you can put the region around an entire macro
1515 definition and conveniently use this command."
1516 (interactive "r\nP")
1517 (save-excursion
1518 (goto-char from)
1519 (let ((column c-backslash-column)
1520 (endmark (make-marker)))
1521 (move-marker endmark to)
1522 ;; Compute the smallest column number past the ends of all the lines.
1523 (if (not delete-flag)
1524 (while (< (point) to)
1525 (end-of-line)
1526 (if (= (preceding-char) ?\\)
1527 (progn (forward-char -1)
1528 (skip-chars-backward " \t")))
1529 (setq column (max column (1+ (current-column))))
1530 (forward-line 1)))
1531 ;; Adjust upward to a tab column, if that doesn't push past the margin.
1532 (if (> (% column tab-width) 0)
1533 (let ((adjusted (* (/ (+ column tab-width -1) tab-width) tab-width)))
1534 (if (< adjusted (window-width))
1535 (setq column adjusted))))
1536 ;; Don't modify blank lines at start of region.
1537 (goto-char from)
1538 (while (and (< (point) endmark) (eolp))
1539 (forward-line 1))
1540 ;; Add or remove backslashes on all the lines.
1541 (while (and (< (point) endmark)
1542 ;; Don't backslashify the last line
1543 ;; if the region ends right at the start of the next line.
1544 (save-excursion
1545 (forward-line 1)
1546 (< (point) endmark)))
1547 (if (not delete-flag)
1548 (c-append-backslash column)
1549 (c-delete-backslash))
1550 (forward-line 1))
1551 (move-marker endmark nil))))
1552
1553 (defun c-append-backslash (column)
1554 (end-of-line)
1555 ;; Note that "\\\\" is needed to get one backslash.
1556 (if (= (preceding-char) ?\\)
1557 (progn (forward-char -1)
1558 (delete-horizontal-space)
1559 (indent-to column))
1560 (indent-to column)
1561 (insert "\\")))
1562
1563 (defun c-delete-backslash ()
1564 (end-of-line)
1565 (or (bolp)
1566 (progn
1567 (forward-char -1)
1568 (if (looking-at "\\\\")
1569 (delete-region (1+ (point))
1570 (progn (skip-chars-backward " \t") (point)))))))
1571 \f
1572 (defun c-up-conditional (count)
1573 "Move back to the containing preprocessor conditional, leaving mark behind.
1574 A prefix argument acts as a repeat count. With a negative argument,
1575 move forward to the end of the containing preprocessor conditional.
1576 When going backwards, `#elif' is treated like `#else' followed by `#if'.
1577 When going forwards, `#elif' is ignored."
1578 (interactive "p")
1579 (c-forward-conditional (- count) t))
1580
1581 (defun c-backward-conditional (count &optional up-flag)
1582 "Move back across a preprocessor conditional, leaving mark behind.
1583 A prefix argument acts as a repeat count. With a negative argument,
1584 move forward across a preprocessor conditional."
1585 (interactive "p")
1586 (c-forward-conditional (- count) up-flag))
1587
1588 (defun c-forward-conditional (count &optional up-flag)
1589 "Move forward across a preprocessor conditional, leaving mark behind.
1590 A prefix argument acts as a repeat count. With a negative argument,
1591 move backward across a preprocessor conditional."
1592 (interactive "p")
1593 (let* ((forward (> count 0))
1594 (increment (if forward -1 1))
1595 (search-function (if forward 're-search-forward 're-search-backward))
1596 (opoint (point))
1597 (new))
1598 (save-excursion
1599 (while (/= count 0)
1600 (let ((depth (if up-flag 0 -1)) found)
1601 (save-excursion
1602 ;; Find the "next" significant line in the proper direction.
1603 (while (and (not found)
1604 ;; Rather than searching for a # sign that comes
1605 ;; at the beginning of a line aside from whitespace,
1606 ;; search first for a string starting with # sign.
1607 ;; Then verify what precedes it.
1608 ;; This is faster on account of the fastmap feature of
1609 ;; the regexp matcher.
1610 (funcall search-function
1611 "#[ \t]*\\(if\\|elif\\|endif\\)"
1612 nil t))
1613 (beginning-of-line)
1614 ;; Now verify it is really a preproc line.
1615 (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")
1616 (let ((prev depth))
1617 ;; Update depth according to what we found.
1618 (beginning-of-line)
1619 (cond ((looking-at "[ \t]*#[ \t]*endif")
1620 (setq depth (+ depth increment)))
1621 ((looking-at "[ \t]*#[ \t]*elif")
1622 (if (and forward (= depth 0))
1623 (setq found (point))))
1624 (t (setq depth (- depth increment))))
1625 ;; If we are trying to move across, and we find
1626 ;; an end before we find a beginning, get an error.
1627 (if (and (< prev 0) (< depth prev))
1628 (error (if forward
1629 "No following conditional at this level"
1630 "No previous conditional at this level")))
1631 ;; When searching forward, start from next line
1632 ;; so that we don't find the same line again.
1633 (if forward (forward-line 1))
1634 ;; If this line exits a level of conditional, exit inner loop.
1635 (if (< depth 0)
1636 (setq found (point))))
1637 ;; If the line is not really a conditional, skip past it.
1638 (if forward (end-of-line)))))
1639 (or found
1640 (error "No containing preprocessor conditional"))
1641 (goto-char (setq new found)))
1642 (setq count (+ count increment))))
1643 (push-mark)
1644 (goto-char new)))
1645
1646 ;;; c-mode.el ends here