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