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