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