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