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