1 ;;; c-mode.el --- C code editing commands for Emacs
2 ;; Copyright (C) 1985, 1986, 1987, 1992 Free Software Foundation, Inc.
7 ;; This file is part of GNU Emacs.
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)
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.
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.
25 (defvar c-mode-abbrev-table nil
26 "Abbrev table in use in C mode.")
27 (define-abbrev-table 'c-mode-abbrev-table ())
30 "Keymap used in C mode.")
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))
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."
54 (defvar c-mode-syntax-table nil
55 "Syntax table in use in C-mode buffers.")
57 (if c-mode-syntax-table
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))
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
91 (c-argdecl-indent . 5)
94 (c-continued-statement-offset . 2))
97 (c-argdecl-indent . 0)
100 (c-continued-statement-offset . 5))
103 (c-argdecl-indent . 4)
104 (c-brace-offset . -4)
105 (c-label-offset . -4)
106 (c-continued-statement-offset . 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))
116 (c-argdecl-indent . 4)
118 (c-label-offset . -4)
119 (c-continued-statement-offset . 4))))
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)")
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.")
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.
139 Variables controlling indentation style:
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.
144 Non-nil means automatically newline before and after braces,
145 and after colons and semicolons, inserted in C code.
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.
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.
162 Indentation level of declarations of C function arguments.
164 Extra indentation for line that is a label, or case or default.
166 Settings for K&R and BSD indentation styles are
168 c-continued-statement-offset 5 8
173 Turning on C mode calls the value of the variable c-mode-hook with no args,
174 if that value is non-nil."
176 (kill-all-local-variables)
177 (use-local-map c-mode-map)
178 (setq major-mode 'c-mode)
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))
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)))
217 (cond ((looking-at "[ \t]*}[ \t]*\\($\\|/\\*\\)")
218 ;; A comment following a solitary close-brace
219 ;; should have only one space.
221 (1+ (current-column)))
222 ((or (looking-at "^#[ \t]*endif[ \t]*")
223 (looking-at "^#[ \t]*else[ \t]*"))
224 7) ;2 spaces after #endif
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.
233 (max (1+ (current-column)) ;Else indent at comment column
234 comment-column))))))) ; except leave at least one space.
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."
242 (let* (comment-start-place
244 ;; Check for obvious entry to comment.
247 (skip-chars-forward " \t")
248 (and (looking-at comment-start-skip)
249 (setq comment-start-place (point))))))
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)
256 (re-search-forward comment-start-skip
257 (save-excursion (end-of-line)
260 (setq comment-start-place (point)))))
261 ;; Inside a comment: fill one comment paragraph.
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.
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)
275 (calculate-c-indent-within-comment t)
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/*]"))
284 (concat paragraph-separate
285 "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[^ \t/*]")))
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
294 (search-backward "/*")
298 (if comment-start-place
299 (goto-char (+ comment-start-place 2)))
300 (search-forward "*/" nil 'move)
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))
309 (search-forward "*/")
311 (if (looking-at "[ \t]*\\*/")
312 (delete-indentation)))))
313 ;; Outside of comments: do ordinary filling.
314 (fill-paragraph arg))))
316 (defun electric-c-brace (arg)
317 "Insert character and correct line's indentation."
323 (skip-chars-backward " \t")
325 (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
327 (insert last-command-char)
332 ;; (newline) may have done auto-fill
333 (setq insertpos (- (point) 2))
336 (if insertpos (goto-char (1+ insertpos)))
340 (goto-char insertpos)
341 (self-insert-command (prefix-numeric-value arg)))
342 (self-insert-command (prefix-numeric-value arg)))))
344 (defun electric-c-sharp-sign (arg)
345 "Insert character and correct line's indentation."
348 (skip-chars-backward " \t")
350 (let ((c-auto-newline nil))
351 (electric-c-terminator arg))
352 (self-insert-command (prefix-numeric-value arg))))
354 (defun electric-c-semi (arg)
355 "Insert character and correct line's indentation."
358 (electric-c-terminator arg)
359 (self-insert-command (prefix-numeric-value arg))))
361 (defun electric-c-terminator (arg)
362 "Insert character and correct line's indentation."
364 (let (insertpos (end (point)))
365 (if (and (not arg) (eolp)
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\\>"))
376 (skip-chars-forward "a-zA-Z0-9_$")
377 (skip-chars-forward " \t")
381 (let ((pps (parse-partial-sexp (point) end)))
382 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
384 (insert last-command-char)
387 (not (c-inside-parens-p))
390 ;; (newline) may have done auto-fill
391 (setq insertpos (- (point) 2))
394 (if insertpos (goto-char (1+ insertpos)))
398 (goto-char insertpos)
399 (self-insert-command (prefix-numeric-value arg)))
400 (self-insert-command (prefix-numeric-value arg)))))
402 (defun c-inside-parens-p ()
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))) ?\()))
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.
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."
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))
429 (if c-tab-always-indent
431 ;; Find beginning of following line.
433 (forward-line 1) (setq beg (point)))
434 ;; Find first beginning-of-sexp for sexp extending past this line.
435 (while (< (point) beg)
438 (skip-chars-forward " \t\n")))
440 (indent-code-rigidly beg end shift-amt "#")))
441 (if (and (not c-tab-always-indent)
443 (skip-chars-backward " \t")
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))
453 (case-fold-search nil)
454 (pos (- (point-max) (point))))
457 (cond ((eq indent nil)
458 (setq indent (current-indentation)))
460 (setq indent (calculate-c-indent-within-comment)))
461 ((looking-at "[ \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]")
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
481 (current-indentation))))
482 ((and (looking-at "while\\b")
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))
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))))
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."
512 (let ((indent-point (point))
513 (case-fold-search nil)
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
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.
542 (re-search-backward "^[^ \^L\t\n#]" nil 'move)
544 ;; Recognize the DEFUN macro in Emacs.
546 ;; Move down to the (putative) argnames line.
547 (while (not (looking-at " *[({}#/]"))
549 ;; Go back to the DEFUN, if it is one.
554 (looking-at "DEFUN\\b"))
556 (if (and (looking-at "\\sw\\|\\s_")
557 (looking-at "[^\"\n=]*(")
559 (goto-char (1- (match-end 0)))
564 (skip-chars-forward " \t\f")
565 (and (< (point) indent-point)
566 (not (memq (following-char)
568 ;; Make sure the "function decl" we found
569 ;; is not inside a comment.
572 (while (and (not comment)
573 (search-forward "/*" lim t))
575 (not (search-forward "*/" lim t))))
577 c-argdecl-indent 0))))))
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))
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))
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)))
607 (if (eq (preceding-char) ?\,)
608 (progn (forward-char -1)
609 (c-backward-to-start-of-continued-exp containing-sexp)))
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)
616 (cond ((save-excursion (end-of-line 0)
617 (= (preceding-char) ?\\))
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) ?#))
625 (setq found (point)))
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.
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.
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?
652 ;; If no, find that first statement and indent like it.
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) ?\#)
661 ((= (following-char) ?\/)
663 (search-forward "*/" nil 'move))
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)
673 (if (> colon-line-end (point))
674 (- (current-indentation) c-label-offset)
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)
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
700 (if (eq (preceding-char) ?\))
702 ;; Get initial indentation of the line we are on.
703 (current-indentation))))))))))
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)
712 (skip-chars-forward " \t")
713 (setq star-start (= (following-char) ?\*))
714 (skip-chars-backward " \t\n")
717 (skip-chars-forward " \t")
719 (and (looking-at "\\*")
720 (re-search-forward "\\*[ \t]*")))
721 (and (re-search-forward "/\\*[ \t]*" end t)
724 (goto-char (1+ (match-beginning 0))))
725 (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
726 (1+ (current-column))
730 (defun c-backward-to-noncomment (lim)
733 (skip-chars-backward " \t\n\f" lim)
734 (setq opoint (point))
735 (if (and (>= (point) (+ 2 lim))
738 (looking-at "\\*/")))
739 (search-backward "/*" lim 'move)
740 (setq stop (or (<= (point) lim)
743 (skip-chars-forward " \t")
744 (not (looking-at "#")))))
745 (or stop (beginning-of-line))))))
747 (defun c-backward-to-start-of-continued-exp (lim)
748 (if (memq (preceding-char) '(?\) ?\"))
752 (goto-char (1+ lim)))
753 (skip-chars-forward " \t"))
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))))
759 (case-fold-search nil))
760 (while (and (not (bobp)) (not (zerop if-level)))
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)))
768 (goto-char limit))))))
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))))
778 (let ((next-start (point)))
780 ;; Move back one token or one brace or paren group.
782 ;; If we find an open-brace, we lose.
783 (error (setq done 'fail)))
786 ;; If we reached a `do', we win.
787 (if (looking-at "do\\b")
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.)
795 (or (and (not first) (= (preceding-char) ?}))
796 (search-forward ";" next-start t
798 (/= (preceding-char) ?}))
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)
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."
816 (let ((here (point)) state)
819 (setq state (parse-partial-sexp (point) here nil nil)))
820 (if (or (nth 3 state) (nth 4 state))
821 (forward-sentence (- count))
823 (c-beginning-of-statement-1)
824 (setq count (1- count)))
826 (c-end-of-statement-1)
827 (setq count (1+ count))))))
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."
835 (c-beginning-of-statement (- count)))
837 (defun c-beginning-of-statement-1 ()
838 (let ((last-begin (point))
842 (while (and (not (bobp))
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))))))
851 (defun c-end-of-statement-1 ()
854 (while (and (not (eobp))
860 (not (re-search-forward "[;{}]" end t)))))))
861 (re-search-backward "[;}]")
865 (backward-up-list -1)
868 (search-forward ";" end 'move))))))
870 (defun mark-c-function ()
871 "Put mark at end of C function, point at beginning."
877 (backward-paragraph))
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."
884 (let* ((indent-stack (list nil))
885 (opoint (point)) ;; May be altered below.
889 ;; Find previous fcn-start.
890 (save-excursion (forward-char 1)
892 (setq funbeg (point)))
893 ;; Try to find containing open,
894 ;; but don't scan past that fcn-start.
896 (narrow-to-region funbeg (point))
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)
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
913 ;; If the braces don't match, get an error right away.
916 ;; Realign the comment on the first line, even though we don't reindent it.
919 (and (re-search-forward
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.
925 (parse-partial-sexp beg (point)
927 (and (not (nth 3 new-state)) (not (nth 5 new-state))))
928 (progn (indent-for-comment) (beginning-of-line)))))
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))))
943 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
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))
951 (if (or (nth 3 state))
953 (setq inner-loop-done t)))
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)))
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)
983 (skip-chars-forward " \t")
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
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.
1005 (c-backward-to-start-of-continued-exp (car contain-stack))
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)
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))
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]")
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) ?\#)
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
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.
1053 (parse-partial-sexp beg (point)
1055 (and (not (nth 3 new-state)) (not (nth 5 new-state))))
1056 (progn (indent-for-comment) (beginning-of-line)))))))))))
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 ()
1064 (while (and (not win)
1065 (re-search-forward comment-start-skip
1066 (save-excursion (end-of-line) (point))
1068 ;; Make sure the comment start is not quoted.
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))))))
1076 ;; Indent every line whose first char is between START and END inclusive.
1077 (defun c-indent-region (start end)
1080 (let ((endmark (copy-marker end)))
1081 (and (bolp) (not (eolp))
1083 (indent-c-exp endmark)
1084 (set-marker endmark nil))))
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))))
1097 (error "Invalid C indentation style `%s'" style))
1100 (make-local-variable (car (car vars))))
1101 (set (car (car vars)) (cdr (car vars)))
1102 (setq vars (cdr vars)))))
1104 ;;; This page handles insertion and removal of backslashes for C macros.
1106 (defvar c-backslash-column 48
1107 "*Minimum column for end-of-line backslashes of macro definitions.")
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.
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")
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)
1128 (if (= (preceding-char) ?\\)
1129 (progn (forward-char -1)
1130 (skip-chars-backward " \t")))
1131 (setq column (max column (1+ (current-column))))
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.
1140 (while (and (< (point) endmark) (eolp))
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.
1148 (< (point) endmark)))
1149 (if (not delete-flag)
1150 (c-append-backslash column)
1151 (c-delete-backslash))
1153 (move-marker endmark nil))))
1155 (defun c-append-backslash (column)
1157 ;; Note that "\\\\" is needed to get one backslash.
1158 (if (= (preceding-char) ?\\)
1159 (progn (forward-char -1)
1160 (delete-horizontal-space)
1165 (defun c-delete-backslash ()
1168 (if (looking-at "\\\\")
1169 (delete-region (1+ (point))
1170 (progn (skip-chars-backward " \t") (point)))))
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."
1179 (let* ((forward (< count 0))
1180 (increment (if forward -1 1))
1181 (search-function (if forward 're-search-forward 're-search-backward))
1186 (if forward (end-of-line))
1187 (let ((depth 0) found)
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\\)"
1202 (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")))
1203 ;; Update depth according to what we found.
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.
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))))
1218 (error "No containing preprocessor conditional"))
1219 (goto-char (setq new found)))
1220 (setq count (- count increment))))
1224 ;;; c-mode.el ends here