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."
243 ;; Check for obvious entry to comment.
246 (skip-chars-forward " \t")
247 (looking-at comment-start-skip))))
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)
257 ;; Inside a comment: fill one comment paragraph.
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.
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)
271 (calculate-c-indent-within-comment t)
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/*]"))
280 (concat paragraph-separate
281 "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[^ \t/*]")))
284 ;; Don't fill the comment together with the code following it.
285 (narrow-to-region (save-excursion
286 (search-backward "/*")
290 (search-forward "*/" nil 'move)
295 (search-forward "*/")
297 (if (looking-at "[ \t]*\\*/")
298 (delete-indentation)))))
299 ;; Outside of comments: do ordinary filling.
300 (fill-paragraph arg))))
302 (defun electric-c-brace (arg)
303 "Insert character and correct line's indentation."
309 (skip-chars-backward " \t")
311 (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
313 (insert last-command-char)
318 ;; (newline) may have done auto-fill
319 (setq insertpos (- (point) 2))
322 (if insertpos (goto-char (1+ insertpos)))
326 (goto-char insertpos)
327 (self-insert-command (prefix-numeric-value arg)))
328 (self-insert-command (prefix-numeric-value arg)))))
330 (defun electric-c-sharp-sign (arg)
331 "Insert character and correct line's indentation."
334 (skip-chars-backward " \t")
336 (let ((c-auto-newline nil))
337 (electric-c-terminator arg))
338 (self-insert-command (prefix-numeric-value arg))))
340 (defun electric-c-semi (arg)
341 "Insert character and correct line's indentation."
344 (electric-c-terminator arg)
345 (self-insert-command (prefix-numeric-value arg))))
347 (defun electric-c-terminator (arg)
348 "Insert character and correct line's indentation."
350 (let (insertpos (end (point)))
351 (if (and (not arg) (eolp)
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\\>"))
362 (skip-chars-forward "a-zA-Z0-9_$")
363 (skip-chars-forward " \t")
367 (let ((pps (parse-partial-sexp (point) end)))
368 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
370 (insert last-command-char)
373 (not (c-inside-parens-p))
376 ;; (newline) may have done auto-fill
377 (setq insertpos (- (point) 2))
380 (if insertpos (goto-char (1+ insertpos)))
384 (goto-char insertpos)
385 (self-insert-command (prefix-numeric-value arg)))
386 (self-insert-command (prefix-numeric-value arg)))))
388 (defun c-inside-parens-p ()
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))) ?\()))
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.
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."
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))
415 (if c-tab-always-indent
417 ;; Find beginning of following line.
419 (forward-line 1) (setq beg (point)))
420 ;; Find first beginning-of-sexp for sexp extending past this line.
421 (while (< (point) beg)
424 (skip-chars-forward " \t\n")))
426 (indent-code-rigidly beg end shift-amt "#")))
427 (if (and (not c-tab-always-indent)
429 (skip-chars-backward " \t")
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))
439 (case-fold-search nil)
440 (pos (- (point-max) (point))))
443 (cond ((eq indent nil)
444 (setq indent (current-indentation)))
446 (setq indent (calculate-c-indent-within-comment)))
447 ((looking-at "[ \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]")
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
467 (current-indentation))))
468 ((and (looking-at "while\\b")
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))
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))))
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."
498 (let ((indent-point (point))
499 (case-fold-search nil)
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
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.
528 (re-search-backward "^[^ \^L\t\n#]" nil 'move)
530 ;; Recognize the DEFUN macro in Emacs.
532 ;; Move down to the (putative) argnames line.
533 (while (not (looking-at " *("))
535 ;; Go back to the DEFUN, if it is one.
540 (looking-at "DEFUN\\b"))
542 (if (and (looking-at "\\sw\\|\\s_")
543 (looking-at "[^\"\n=]*(")
545 (goto-char (1- (match-end 0)))
550 (skip-chars-forward " \t\f")
551 (and (< (point) indent-point)
552 (not (memq (following-char)
554 ;; Make sure the "function decl" we found
555 ;; is not inside a comment.
558 (while (and (not comment)
559 (search-forward "/*" lim t))
561 (not (search-forward "*/" lim t))))
563 c-argdecl-indent 0))))))
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))
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))
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)))
593 (if (eq (preceding-char) ?\,)
594 (progn (forward-char -1)
595 (c-backward-to-start-of-continued-exp containing-sexp)))
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)
602 (cond ((save-excursion (end-of-line 0)
603 (= (preceding-char) ?\\))
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) ?#))
611 (setq found (point)))
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.
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.
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?
638 ;; If no, find that first statement and indent like it.
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) ?\#)
647 ((= (following-char) ?\/)
649 (search-forward "*/" nil 'move))
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)
659 (if (> colon-line-end (point))
660 (- (current-indentation) c-label-offset)
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)
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
686 (if (eq (preceding-char) ?\))
688 ;; Get initial indentation of the line we are on.
689 (current-indentation))))))))))
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)
698 (skip-chars-forward " \t")
699 (setq star-start (= (following-char) ?\*))
700 (skip-chars-backward " \t\n")
703 (skip-chars-forward " \t")
705 (and (looking-at "\\*")
706 (re-search-forward "\\*[ \t]*")))
707 (and (re-search-forward "/\\*[ \t]*" end t)
710 (goto-char (1+ (match-beginning 0))))
711 (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
712 (1+ (current-column))
716 (defun c-backward-to-noncomment (lim)
719 (skip-chars-backward " \t\n\f" lim)
720 (setq opoint (point))
721 (if (and (>= (point) (+ 2 lim))
724 (looking-at "\\*/")))
725 (search-backward "/*" lim 'move)
726 (setq stop (or (<= (point) lim)
729 (skip-chars-forward " \t")
730 (not (looking-at "#")))))
731 (or stop (beginning-of-line))))))
733 (defun c-backward-to-start-of-continued-exp (lim)
734 (if (memq (preceding-char) '(?\) ?\"))
738 (goto-char (1+ lim)))
739 (skip-chars-forward " \t"))
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))))
745 (case-fold-search nil))
746 (while (and (not (bobp)) (not (zerop if-level)))
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)))
754 (goto-char limit))))))
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))))
764 (let ((next-start (point)))
766 ;; Move back one token or one brace or paren group.
768 ;; If we find an open-brace, we lose.
769 (error (setq done 'fail)))
772 ;; If we reached a `do', we win.
773 (if (looking-at "do\\b")
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.)
781 (or (and (not first) (= (preceding-char) ?}))
782 (search-forward ";" next-start t
784 (/= (preceding-char) ?}))
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)
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."
802 (let ((here (point)) state)
805 (setq state (parse-partial-sexp (point) here nil nil)))
806 (if (or (nth 3 state) (nth 4 state))
807 (forward-sentence (- count))
809 (c-beginning-of-statement-1)
810 (setq count (1- count)))
812 (c-end-of-statement-1)
813 (setq count (1+ count))))))
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."
821 (c-beginning-of-statement (- count)))
823 (defun c-beginning-of-statement-1 ()
824 (let ((last-begin (point))
828 (while (and (not (bobp))
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))))))
837 (defun c-end-of-statement-1 ()
840 (while (and (not (eobp))
846 (not (re-search-forward "[;{}]" end t)))))))
847 (re-search-backward "[;}]")
851 (backward-up-list -1)
854 (search-forward ";" end 'move))))))
856 (defun mark-c-function ()
857 "Put mark at end of C function, point at beginning."
863 (backward-paragraph))
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."
870 (let* ((indent-stack (list nil))
871 (opoint (point)) ;; May be altered below.
875 ;; Find previous fcn-start.
876 (save-excursion (forward-char 1)
878 (setq funbeg (point)))
879 ;; Try to find containing open,
880 ;; but don't scan past that fcn-start.
882 (narrow-to-region funbeg (point))
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)
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
899 ;; If the braces don't match, get an error right away.
902 ;; Realign the comment on the first line, even though we don't reindent it.
905 (and (re-search-forward
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.
911 (parse-partial-sexp beg (point)
913 (and (not (nth 3 new-state)) (not (nth 5 new-state))))
914 (progn (indent-for-comment) (beginning-of-line)))))
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))))
929 (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
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))
937 (if (or (nth 3 state))
939 (setq inner-loop-done t)))
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)))
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)
969 (skip-chars-forward " \t")
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
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.
991 (c-backward-to-start-of-continued-exp (car contain-stack))
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)
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))
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]")
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) ?\#)
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
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.
1039 (parse-partial-sexp beg (point)
1041 (and (not (nth 3 new-state)) (not (nth 5 new-state))))
1042 (progn (indent-for-comment) (beginning-of-line)))))))))))
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 ()
1050 (while (and (not win)
1051 (re-search-forward comment-start-skip
1052 (save-excursion (end-of-line) (point))
1054 ;; Make sure the comment start is not quoted.
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))))))
1062 ;; Indent every line whose first char is between START and END inclusive.
1063 (defun c-indent-region (start end)
1066 (let ((endmark (copy-marker end)))
1067 (and (bolp) (not (eolp))
1069 (indent-c-exp endmark)
1070 (set-marker endmark nil))))
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))))
1083 (error "Invalid C indentation style `%s'" style))
1086 (make-local-variable (car (car vars))))
1087 (set (car (car vars)) (cdr (car vars)))
1088 (setq vars (cdr vars)))))
1090 ;;; This page handles insertion and removal of backslashes for C macros.
1092 (defvar c-backslash-column 48
1093 "*Minimum column for end-of-line backslashes of macro definitions.")
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.
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")
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)
1114 (if (= (preceding-char) ?\\)
1115 (progn (forward-char -1)
1116 (skip-chars-backward " \t")))
1117 (setq column (max column (1+ (current-column))))
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.
1126 (while (and (< (point) endmark) (eolp))
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.
1134 (< (point) endmark)))
1135 (if (not delete-flag)
1136 (c-append-backslash column)
1137 (c-delete-backslash))
1139 (move-marker endmark nil))))
1141 (defun c-append-backslash (column)
1143 ;; Note that "\\\\" is needed to get one backslash.
1144 (if (= (preceding-char) ?\\)
1145 (progn (forward-char -1)
1146 (delete-horizontal-space)
1151 (defun c-delete-backslash ()
1154 (if (looking-at "\\\\")
1155 (delete-region (1+ (point))
1156 (progn (skip-chars-backward " \t") (point)))))
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."
1165 (let* ((forward (< count 0))
1166 (increment (if forward -1 1))
1167 (search-function (if forward 're-search-forward 're-search-backward))
1172 (if forward (end-of-line))
1173 (let ((depth 0) found)
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\\)"
1188 (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")))
1189 ;; Update depth according to what we found.
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.
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))))
1204 (error "No containing preprocessor conditional"))
1205 (goto-char (setq new found)))
1206 (setq count (- count increment))))
1210 ;;; c-mode.el ends here