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