1 ;;; cc-cmds.el --- user level commands for CC Mode
3 ;; Copyright (C) 1985, 1987, 1992, 1993, 1994, 1995, 1996, 1997, 1998,
4 ;; 1999, 2000, 2001, 2002, 2003, 2004, 2005, 2006, 2007, 2008, 2009,
5 ;; 2010, 2011, 2012, 2013 Free Software Foundation, Inc.
7 ;; Authors: 2003- Alan Mackenzie
8 ;; 1998- Martin Stjernholm
9 ;; 1992-1999 Barry A. Warsaw
10 ;; 1987 Dave Detlefs and Stewart Clamen
11 ;; 1985 Richard M. Stallman
12 ;; Maintainer: bug-cc-mode@gnu.org
13 ;; Created: 22-Apr-1997 (split from cc-mode.el)
14 ;; Version: See cc-mode.el
15 ;; Keywords: c languages oop
17 ;; This file is part of GNU Emacs.
19 ;; GNU Emacs is free software; you can redistribute it and/or modify
20 ;; it under the terms of the GNU General Public License as published by
21 ;; the Free Software Foundation; either version 3, or (at your option)
24 ;; GNU Emacs is distributed in the hope that it will be useful,
25 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
26 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
27 ;; GNU General Public License for more details.
29 ;; You should have received a copy of the GNU General Public License
30 ;; along with this program; see the file COPYING. If not, see
31 ;; <http://www.gnu.org/licenses/>.
39 (if (and (boundp 'byte-compile-dest-file)
40 (stringp byte-compile-dest-file))
41 (cons (file-name-directory byte-compile-dest-file) load-path)
43 (load "cc-bytecomp" nil t)))
47 (cc-require 'cc-engine)
49 ;; Silence the compiler.
50 (cc-bytecomp-defun delete-forward-p) ; XEmacs
51 (cc-bytecomp-defvar filladapt-mode) ; c-fill-paragraph contains a kludge
52 ; which looks at this.
53 (cc-bytecomp-defun c-forward-subword)
54 (cc-bytecomp-defun c-backward-subword)
56 ;; Indentation / Display syntax functions
57 (defvar c-fix-backslashes t)
59 (defun c-indent-line (&optional syntax quiet ignore-point-pos)
60 "Indent the current line according to the syntactic context,
61 if `c-syntactic-indentation' is non-nil. Optional SYNTAX is the
62 syntactic information for the current line. Be silent about syntactic
63 errors if the optional argument QUIET is non-nil, even if
64 `c-report-syntactic-errors' is non-nil. Normally the position of
65 point is used to decide where the old indentation is on a lines that
66 is otherwise empty \(ignoring any line continuation backslash), but
67 that's not done if IGNORE-POINT-POS is non-nil. Returns the amount of
68 indentation change \(in columns)."
70 (let ((line-cont-backslash (save-excursion
72 (eq (char-before) ?\\)))
73 (c-fix-backslashes c-fix-backslashes)
76 (when (and (not ignore-point-pos)
79 (looking-at (if line-cont-backslash
80 ;; Don't use "\\s " - ^L doesn't count as WS
84 (<= (point) (match-end 1)))
85 ;; Delete all whitespace after point if there's only whitespace
86 ;; on the line, so that any code that does back-to-indentation
87 ;; or similar gets the current column in this case. If this
88 ;; removes a line continuation backslash it'll be restored
90 (unless c-auto-align-backslashes
91 ;; Should try to keep the backslash alignment
94 (goto-char (match-end 0))
95 (setq bs-col (1- (current-column)))))
96 (delete-region (point) (match-end 0))
97 (setq c-fix-backslashes t))
98 (if c-syntactic-indentation
100 (or (let ((c-parsing-error nil)
103 (and (boundp 'c-syntactic-context)
104 c-syntactic-context))))
105 (c-save-buffer-state (indent)
106 (unless c-syntactic-context
107 (setq c-syntactic-context (c-guess-basic-syntax)))
108 (setq indent (c-get-syntactic-indentation
109 c-syntactic-context))
110 (and (not (c-echo-parsing-error quiet))
111 c-echo-syntactic-information-p
112 (message "syntax: %s, indent: %d"
113 c-syntactic-context indent))
114 (setq shift-amt (- indent (current-indentation))))
115 (c-shift-line-indentation shift-amt)
116 (run-hooks 'c-special-indent-hook)
121 (while (and (= (forward-line -1) 0)
122 (if (looking-at "\\s *\\\\?$")
124 (setq indent (current-indentation))
126 (setq shift-amt (- indent (current-indentation)))
127 (c-shift-line-indentation shift-amt)))
128 (when (and c-fix-backslashes line-cont-backslash)
133 (when c-auto-align-backslashes
134 ;; Realign the line continuation backslash.
135 (c-backslash-region (point) (point) nil t))))
138 (defun c-newline-and-indent (&optional newline-arg)
139 "Insert a newline and indent the new line.
140 This function fixes line continuation backslashes if inside a macro,
141 and takes care to set the indentation before calling
142 `indent-according-to-mode', so that lineup functions like
143 `c-lineup-dont-change' works better."
145 ;; TODO: Backslashes before eol in comments and literals aren't
147 (let ((c-macro-start (c-query-macro-start))
148 ;; Avoid calling c-backslash-region from c-indent-line if it's
149 ;; called during the newline call, which can happen due to
150 ;; c-electric-continued-statement, for example. We also don't
151 ;; want any backslash alignment from indent-according-to-mode.
152 (c-fix-backslashes nil)
153 has-backslash insert-backslash
158 (while (and (looking-at "[ \t]*\\\\?$")
159 (= (forward-line -1) 0)))
160 (setq col (current-indentation)))
162 (if (and (eolp) (eq (char-before) ?\\))
163 (setq insert-backslash t
165 (setq has-backslash (eq (char-before (c-point 'eol)) ?\\))))
166 (newline newline-arg)
171 ;; The backslash stayed on the previous line. Insert one
172 ;; before calling c-backslash-region, so that
173 ;; bs-col-after-end in it works better. Fixup the
174 ;; backslashes on the newly inserted line.
177 (c-backslash-region (point) (point) nil t))
178 ;; The backslash moved to the new line, if there was any. Let
179 ;; c-backslash-region fix a backslash on the previous line,
180 ;; and the one that might be on the new line.
181 ;; c-auto-align-backslashes is intentionally ignored here;
182 ;; maybe the moved backslash should be left alone if it's set,
183 ;; but we fix both lines on the grounds that the old backslash
184 ;; has been moved anyway and is now in a different context.
185 (c-backslash-region start (if has-backslash (point) start) nil t)))
186 (when c-syntactic-indentation
187 ;; Reindent syntactically. The indentation done above is not
188 ;; wasted, since c-indent-line might look at the current
190 (let ((c-syntactic-context (c-save-buffer-state nil
191 (c-guess-basic-syntax))))
192 ;; We temporarily insert another line break, so that the
193 ;; lineup functions will see the line as empty. That makes
194 ;; e.g. c-lineup-cpp-define more intuitive since it then
195 ;; proceeds to the preceding line in this case.
197 (delete-horizontal-space)
198 (setq start (- (point-max) (point)))
202 (indent-according-to-mode))
203 (goto-char (- (point-max) start))
206 ;; Must align the backslash again after reindentation. The
207 ;; c-backslash-region call above can't be optimized to ignore
208 ;; this line, since it then won't align correctly with the
209 ;; lines below if the first line in the macro is broken.
210 (c-backslash-region (point) (point) nil t)))))
212 (defun c-show-syntactic-information (arg)
213 "Show syntactic information for current line.
214 With universal argument, inserts the analysis as a comment on that line."
216 (let* ((c-parsing-error nil)
217 (syntax (if (boundp 'c-syntactic-context)
218 ;; Use `c-syntactic-context' in the same way as
219 ;; `c-indent-line', to be consistent.
221 (c-save-buffer-state nil
222 (c-guess-basic-syntax)))))
223 (if (not (consp arg))
225 (message "Syntactic analysis: %s" syntax)
229 (setq elem (pop syntax))
230 (when (setq pos (c-langelem-pos elem))
231 (push (c-put-overlay pos (1+ pos)
234 (when (setq pos (c-langelem-2nd-pos elem))
235 (push (c-put-overlay pos (1+ pos)
236 'face 'secondary-selection)
240 (c-delete-overlay (pop ols)))))
242 (insert-and-inherit (format "%s" syntax))
244 (c-keep-region-active))
246 (defun c-syntactic-information-on-region (from to)
247 "Insert a comment with the syntactic analysis on every line in the region."
251 (narrow-to-region from to)
252 (goto-char (point-min))
254 (c-show-syntactic-information '(0))
258 ;; Minor mode functions.
259 (defun c-update-modeline ()
260 (let ((fmt (format "/%s%s%s%s"
261 (if c-electric-flag "l" "")
262 (if (and c-electric-flag c-auto-newline)
264 (if c-hungry-delete-key "h" "")
266 ;; cc-subword might not be loaded.
267 (boundp 'c-subword-mode)
268 (symbol-value 'c-subword-mode))
271 (bare-mode-name (if (string-match "\\(^[^/]*\\)/" mode-name)
272 (substring mode-name (match-beginning 1) (match-end 1))
274 ;; (setq c-submode-indicators
275 ;; (if (> (length fmt) 1)
278 (if (> (length fmt) 1)
279 (concat bare-mode-name fmt)
281 (force-mode-line-update)))
283 (defun c-toggle-syntactic-indentation (&optional arg)
284 "Toggle syntactic indentation.
285 Optional numeric ARG, if supplied, turns on syntactic indentation when
286 positive, turns it off when negative, and just toggles it when zero or
289 When syntactic indentation is turned on (the default), the indentation
290 functions and the electric keys indent according to the syntactic
291 context keys, when applicable.
293 When it's turned off, the electric keys don't reindent, the indentation
294 functions indents every new line to the same level as the previous
295 nonempty line, and \\[c-indent-command] adjusts the indentation in steps
296 specified by `c-basic-offset'. The indentation style has no effect in
297 this mode, nor any of the indentation associated variables,
298 e.g. `c-special-indent-hook'.
300 This command sets the variable `c-syntactic-indentation'."
302 (setq c-syntactic-indentation
303 (c-calculate-state arg c-syntactic-indentation))
304 (c-keep-region-active))
306 (defun c-toggle-auto-newline (&optional arg)
307 "Toggle auto-newline feature.
308 Optional numeric ARG, if supplied, turns on auto-newline when
309 positive, turns it off when negative, and just toggles it when zero or
312 Turning on auto-newline automatically enables electric indentation.
314 When the auto-newline feature is enabled (indicated by \"/la\" on the
315 mode line after the mode name) newlines are automatically inserted
316 after special characters such as brace, comma, semi-colon, and colon."
319 (c-calculate-state arg (and c-auto-newline c-electric-flag)))
320 (if c-auto-newline (setq c-electric-flag t))
322 (c-keep-region-active))
324 (defalias 'c-toggle-auto-state 'c-toggle-auto-newline)
325 (make-obsolete 'c-toggle-auto-state 'c-toggle-auto-newline nil)
327 (defun c-toggle-hungry-state (&optional arg)
328 "Toggle hungry-delete-key feature.
329 Optional numeric ARG, if supplied, turns on hungry-delete when
330 positive, turns it off when negative, and just toggles it when zero or
333 When the hungry-delete-key feature is enabled (indicated by \"/h\" on
334 the mode line after the mode name) the delete key gobbles all preceding
335 whitespace in one fell swoop."
337 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
339 (c-keep-region-active))
341 (defun c-toggle-auto-hungry-state (&optional arg)
342 "Toggle auto-newline and hungry-delete-key features.
343 Optional numeric ARG, if supplied, turns on auto-newline and
344 hungry-delete when positive, turns them off when negative, and just
345 toggles them when zero or left out.
347 See `c-toggle-auto-newline' and `c-toggle-hungry-state' for details."
349 (setq c-auto-newline (c-calculate-state arg c-auto-newline))
350 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
352 (c-keep-region-active))
354 (defun c-toggle-electric-state (&optional arg)
355 "Toggle the electric indentation feature.
356 Optional numeric ARG, if supplied, turns on electric indentation when
357 positive, turns it off when negative, and just toggles it when zero or
360 (setq c-electric-flag (c-calculate-state arg c-electric-flag))
362 (c-keep-region-active))
367 (defun c-electric-backspace (arg)
368 "Delete the preceding character or whitespace.
369 If `c-hungry-delete-key' is non-nil (indicated by \"/h\" on the mode
370 line) then all preceding whitespace is consumed. If however a prefix
371 argument is supplied, or `c-hungry-delete-key' is nil, or point is
372 inside a literal then the function in the variable
373 `c-backspace-function' is called."
375 (if (c-save-buffer-state ()
376 (or (not c-hungry-delete-key)
379 (funcall c-backspace-function (prefix-numeric-value arg))
380 (c-hungry-delete-backwards)))
382 (defun c-hungry-delete-backwards ()
383 "Delete the preceding character or all preceding whitespace
384 back to the previous non-whitespace character.
385 See also \\[c-hungry-delete-forward]."
387 (let ((here (point)))
389 (if (/= (point) here)
390 (delete-region (point) here)
391 (funcall c-backspace-function 1))))
393 (defalias 'c-hungry-backspace 'c-hungry-delete-backwards)
395 (defun c-electric-delete-forward (arg)
396 "Delete the following character or whitespace.
397 If `c-hungry-delete-key' is non-nil (indicated by \"/h\" on the mode
398 line) then all following whitespace is consumed. If however a prefix
399 argument is supplied, or `c-hungry-delete-key' is nil, or point is
400 inside a literal then the function in the variable `c-delete-function'
403 (if (c-save-buffer-state ()
404 (or (not c-hungry-delete-key)
407 (funcall c-delete-function (prefix-numeric-value arg))
408 (c-hungry-delete-forward)))
410 (defun c-hungry-delete-forward ()
411 "Delete the following character or all following whitespace
412 up to the next non-whitespace character.
413 See also \\[c-hungry-delete-backwards]."
415 (let ((here (point)))
417 (if (/= (point) here)
418 (delete-region (point) here)
419 (funcall c-delete-function 1))))
421 ;; This function is only used in XEmacs.
422 (defun c-electric-delete (arg)
423 "Deletes preceding or following character or whitespace.
424 This function either deletes forward as `c-electric-delete-forward' or
425 backward as `c-electric-backspace', depending on the configuration: If
426 the function `delete-forward-p' is defined and returns non-nil, it
427 deletes forward. Otherwise it deletes backward.
429 Note: This is the way in XEmacs to choose the correct action for the
430 \[delete] key, whichever key that means. Other flavors don't use this
431 function to control that."
433 (if (and (fboundp 'delete-forward-p)
435 (c-electric-delete-forward arg)
436 (c-electric-backspace arg)))
438 ;; This function is only used in XEmacs.
439 (defun c-hungry-delete ()
440 "Delete a non-whitespace char, or all whitespace up to the next non-whitespace char.
441 The direction of deletion depends on the configuration: If the
442 function `delete-forward-p' is defined and returns non-nil, it deletes
443 forward using `c-hungry-delete-forward'. Otherwise it deletes
444 backward using `c-hungry-backspace'.
446 Note: This is the way in XEmacs to choose the correct action for the
447 \[delete] key, whichever key that means. Other flavors don't use this
448 function to control that."
450 (if (and (fboundp 'delete-forward-p)
452 (c-hungry-delete-forward)
453 (c-hungry-delete-backwards)))
455 (defun c-electric-pound (arg)
457 If `c-electric-flag' is set, handle it specially according to the variable
458 `c-electric-pound-behavior'. If a numeric ARG is supplied, or if point is
459 inside a literal or a macro, nothing special happens."
461 (if (c-save-buffer-state ()
463 (not c-electric-flag)
464 (not (memq 'alignleft c-electric-pound-behavior))
466 (skip-chars-backward " \t")
469 (and (= (forward-line -1) 0)
471 (eq (char-before) ?\\))))
473 ;; do nothing special
474 (self-insert-command (prefix-numeric-value arg))
475 ;; place the pound character at the left edge
476 (let ((pos (- (point-max) (point)))
479 (delete-horizontal-space)
480 (insert (c-last-command-char))
482 (goto-char (- (point-max) pos)))
485 (defun c-point-syntax ()
486 ;; Return the syntactic context of the construct at point. (This is NOT
487 ;; nec. the same as the s.c. of the line point is on). N.B. This won't work
488 ;; between the `#' of a cpp thing and what follows (see c-opt-cpp-prefix).
489 (c-save-buffer-state (;; shut this up too
490 (c-echo-syntactic-information-p nil)
492 (c-tentative-buffer-changes
493 ;; insert a newline to isolate the construct at point for syntactic
496 ;; In AWK (etc.) or in a macro, make sure this CR hasn't changed
497 ;; the syntax. (There might already be an escaped NL there.)
500 (c-skip-ws-backward (c-point 'bopl))
505 (and (c-beginning-of-macro)
506 (progn (c-end-of-macro)
511 (let ((c-syntactic-indentation-in-macros t)
512 (c-auto-newline-analysis t))
513 ;; Turn on syntactic macro analysis to help with auto
515 (setq syntax (c-guess-basic-syntax))
519 (defun c-brace-newlines (syntax)
520 ;; A brace stands at point. SYNTAX is the syntactic context of this brace
521 ;; (not necessarily the same as the S.C. of the line it is on). Return
522 ;; NEWLINES, the list containing some combination of the symbols `before'
523 ;; and `after' saying where newlines should be inserted.
526 ;; This is the list of brace syntactic symbols that can hang.
527 ;; If any new ones are added to c-offsets-alist, they should be
528 ;; added here as well.
530 ;; The order of this list is important; if SYNTAX has several
531 ;; elements, the element that "wins" is the earliest in SYMS.
532 '(arglist-cont-nonempty ; e.g. an array literal.
533 class-open class-close defun-open defun-close
534 inline-open inline-close
535 brace-list-open brace-list-close
536 brace-list-intro brace-entry-open
537 block-open block-close
538 substatement-open statement-case-open
539 extern-lang-open extern-lang-close
540 namespace-open namespace-close
541 module-open module-close
542 composition-open composition-close
543 inexpr-class-open inexpr-class-close
544 ;; `statement-cont' is here for the case with a brace
545 ;; list opener inside a statement. C.f. CASE B.2 in
546 ;; `c-guess-continued-construct'.
549 (c-echo-syntactic-information-p nil)
550 symb-newlines) ; e.g. (substatement-open . (after))
553 ;; Do not try to insert newlines around a special
554 ;; (Pike-style) brace list.
555 (if (and c-special-brace-lists
557 (c-safe (if (= (char-before) ?{)
560 (c-looking-at-special-brace-list))))
562 ;; Seek the matching entry in c-hanging-braces-alist.
565 ;; Substitute inexpr-class and class-open or
566 ;; class-close with inexpr-class-open or
567 ;; inexpr-class-close.
568 (if (assq 'inexpr-class syntax)
569 (cond ((assq 'class-open syntax)
570 '((inexpr-class-open)))
571 ((assq 'class-close syntax)
572 '((inexpr-class-close)))
575 c-hanging-braces-alist)
576 '(ignore before after)))) ; Default, when not in c-h-b-l.
578 ;; If syntax is a function symbol, then call it using the
579 ;; defined semantics.
580 (if (and (not (consp (cdr symb-newlines)))
581 (functionp (cdr symb-newlines)))
582 (let ((c-syntactic-context syntax))
583 (funcall (cdr symb-newlines)
586 (cdr symb-newlines))))
588 (defun c-try-one-liner ()
589 ;; Point is just after a newly inserted }. If the non-whitespace
590 ;; content of the braces is a single line of code, compact the whole
591 ;; construct to a single line, if this line isn't too long. The Right
592 ;; Thing is done with comments.
594 ;; Point will be left after the }, regardless of whether the clean-up is
595 ;; done. Return NON-NIL if the clean-up happened, NIL if it didn't.
598 (pos (- (point-max) (point)))
599 mbeg1 mend1 mbeg4 mend4
600 eol-col cmnt-pos cmnt-col cmnt-gap)
605 ;; Avoid backtracking over a very large block. The one we
606 ;; deal with here can never be more than three lines.
607 (narrow-to-region (save-excursion
611 (and (c-safe (c-backward-sexp))
614 (narrow-to-region (point) (1- here)) ; innards of {.}
616 (cc-eval-when-compile
618 "\\(" ; (match-beginning 1)
619 "[ \t]*\\([\r\n][ \t]*\\)?" ; WS with opt. NL
620 "\\)" ; (match-end 1)
621 "[^ \t\r\n]+\\([ \t]+[^ \t\r\n]+\\)*" ; non-WS
622 "\\(" ; (match-beginning 4)
623 "[ \t]*\\([\r\n][ \t]*\\)?" ; WS with opt. NL
624 "\\)\\'"))))))) ; (match-end 4) at EOB.
626 (if (c-tentative-buffer-changes
627 (setq mbeg1 (match-beginning 1) mend1 (match-end 1)
628 mbeg4 (match-beginning 4) mend4 (match-end 4))
629 (backward-char) ; back over the `}'
631 (setq cmnt-pos (and (c-backward-single-comment)
632 (- (point) (- mend1 mbeg1)))))
633 (delete-region mbeg4 mend4)
634 (delete-region mbeg1 mend1)
635 (setq eol-col (save-excursion (end-of-line) (current-column)))
637 ;; Necessary to put the closing brace before any line
638 ;; oriented comment to keep it syntactically significant.
639 ;; This isn't necessary for block comments, but the result
640 ;; looks nicer anyway.
642 (delete-char 1) ; the `}' has blundered into a comment
644 (setq cmnt-col (1+ (current-column)))
645 (setq cmnt-pos (1+ cmnt-pos)) ; we're inserting a `}'
647 (insert-char ?\} 1) ; reinsert the `}' before the comment.
648 (setq cmnt-gap (- cmnt-col (current-column)))
649 (when (zerop cmnt-gap)
650 (insert-char ?\ 1) ; Put a space before a bare comment.
653 (or (null c-max-one-liner-length)
654 (zerop c-max-one-liner-length)
655 (<= eol-col c-max-one-liner-length)
656 ;; Can we trim space before comment to make the line fit?
658 (< (- eol-col cmnt-gap) c-max-one-liner-length)
659 (progn (goto-char cmnt-pos)
660 (backward-delete-char-untabify
661 (- eol-col c-max-one-liner-length))
663 (goto-char (- (point-max) pos))))))
665 (defun c-electric-brace (arg)
668 If `c-electric-flag' is non-nil, the brace is not inside a literal and a
669 numeric ARG hasn't been supplied, the command performs several electric
672 \(a) If the auto-newline feature is turned on (indicated by \"/la\" on
673 the mode line) newlines are inserted before and after the brace as
674 directed by the settings in `c-hanging-braces-alist'.
676 \(b) Any auto-newlines are indented. The original line is also
677 reindented unless `c-syntactic-indentation' is nil.
679 \(c) If auto-newline is turned on, various newline cleanups based on the
680 settings of `c-cleanup-list' are done."
683 (let (safepos literal
684 ;; We want to inhibit blinking the paren since this would be
685 ;; most disruptive. We'll blink it ourselves later on.
686 (old-blink-paren blink-paren-function)
687 blink-paren-function case-fold-search)
689 (c-save-buffer-state ()
690 (setq safepos (c-safe-position (point) (c-parse-state))
691 literal (c-in-literal safepos)))
693 ;; Insert the brace. Note that expand-abbrev might reindent
694 ;; the line here if there's a preceding "else" or something.
695 (self-insert-command (prefix-numeric-value arg))
697 (when (and c-electric-flag (not literal) (not arg))
698 (if (not (looking-at "[ \t]*\\\\?$"))
699 (if c-syntactic-indentation
700 (indent-according-to-mode))
702 (let ( ;; shut this up too
703 (c-echo-syntactic-information-p nil)
705 ln-syntax br-syntax syntax) ; Syntactic context of the original line,
706 ; of the brace itself, of the line the brace ends up on.
707 (c-save-buffer-state ((c-syntactic-indentation-in-macros t)
708 (c-auto-newline-analysis t))
709 (setq ln-syntax (c-guess-basic-syntax)))
710 (if c-syntactic-indentation
711 (c-indent-line ln-syntax))
715 (setq br-syntax (c-point-syntax)
716 newlines (c-brace-newlines br-syntax))
718 ;; Insert the BEFORE newline, if wanted, and reindent the newline.
719 (if (and (memq 'before newlines)
720 (> (current-column) (current-indentation)))
721 (if c-syntactic-indentation
722 ;; Only a plain newline for now - it's indented
723 ;; after the cleanups when the line has its final
726 (c-newline-and-indent)))
729 ;; `syntax' is the syntactic context of the line which ends up
730 ;; with the brace on it.
731 (setq syntax (if (memq 'before newlines) br-syntax ln-syntax))
733 ;; Do all appropriate clean ups
735 (pos (- (point-max) (point)))
739 ;; `}': clean up empty defun braces
740 (when (c-save-buffer-state ()
741 (and (memq 'empty-defun-braces c-cleanup-list)
742 (eq (c-last-command-char) ?\})
743 (c-intersect-lists '(defun-close class-close inline-close)
748 (eq (char-before) ?\{))
749 ;; make sure matching open brace isn't in a comment
750 (not (c-in-literal))))
751 (delete-region (point) (1- here))
752 (setq here (- (point-max) pos)))
755 ;; `}': compact to a one-liner defun?
758 (and (eq (c-last-command-char) ?\})
759 (memq 'one-liner-defun c-cleanup-list)
760 (c-intersect-lists '(defun-close) syntax)
762 (setq here (- (point-max) pos))))
764 ;; `{': clean up brace-else-brace and brace-elseif-brace
765 (when (eq (c-last-command-char) ?\{)
767 ((and (memq 'brace-else-brace c-cleanup-list)
770 "\\([ \t\n]\\|\\\\\n\\)*"
772 "\\([ \t\n]\\|\\\\\n\\)*"
776 (delete-region (match-beginning 0) (match-end 0))
777 (insert-and-inherit "} else {"))
778 ((and (memq 'brace-elseif-brace c-cleanup-list)
780 (goto-char (1- here))
784 (eq (char-before) ?\)))
785 (zerop (c-save-buffer-state nil (c-backward-token-2 1 t)))
786 (eq (char-after) ?\()
791 "\\([ \t\n]\\|\\\\\n\\)*"
793 "\\([ \t\n]\\|\\\\\n\\)+"
795 "\\([ \t\n]\\|\\\\\n\\)*"
798 ;(eq (match-end 0) tmp);
800 (delete-region mbeg mend)
804 (goto-char (- (point-max) pos))
806 ;; Indent the line after the cleanups since it might
807 ;; very well indent differently due to them, e.g. if
808 ;; c-indent-one-line-block is used together with the
809 ;; one-liner-defun cleanup.
810 (when c-syntactic-indentation
813 ;; does a newline go after the brace?
814 (if (memq 'after newlines)
815 (c-newline-and-indent))
819 (and (eq (c-last-command-char) ?\})
820 (not executing-kbd-macro)
823 (c-save-buffer-state nil
824 (c-backward-syntactic-ws safepos))
825 (funcall old-blink-paren)))))
827 (defun c-electric-slash (arg)
828 "Insert a slash character.
830 If the slash is inserted immediately after the comment prefix in a c-style
831 comment, the comment might get closed by removing whitespace and possibly
832 inserting a \"*\". See the variable `c-cleanup-list'.
834 Indent the line as a comment, if:
836 1. The slash is second of a \"//\" line oriented comment introducing
837 token and we are on a comment-only-line, or
839 2. The slash is part of a \"*/\" token that closes a block oriented
842 If a numeric ARG is supplied, point is inside a literal, or
843 `c-syntactic-indentation' is nil or `c-electric-flag' is nil, indentation
846 (let ((literal (c-save-buffer-state () (c-in-literal)))
849 (c-echo-syntactic-information-p nil))
851 ;; comment-close-slash cleanup? This DOESN'T need `c-electric-flag' or
852 ;; `c-syntactic-indentation' set.
855 (memq 'comment-close-slash c-cleanup-list)
856 (eq (c-last-command-char) ?/)
857 (looking-at (concat "[ \t]*\\("
858 (regexp-quote comment-end) "\\)?$"))
859 ; (eq c-block-comment-ender "*/") ; C-style comments ALWAYS end in */
862 (narrow-to-region (point-min) (point))
863 (back-to-indentation)
864 (looking-at (concat c-current-comment-prefix "[ \t]*$")))))
865 (delete-region (progn (forward-line 0) (point))
866 (progn (end-of-line) (point)))
867 (insert-char ?* 1)) ; the / comes later. ; Do I need a t (retain sticky properties) here?
869 (setq indentp (and (not arg)
870 c-syntactic-indentation
872 (eq (c-last-command-char) ?/)
873 (eq (char-before) (if literal ?* ?/))))
874 (self-insert-command (prefix-numeric-value arg))
876 (indent-according-to-mode))))
878 (defun c-electric-star (arg)
879 "Insert a star character.
880 If `c-electric-flag' and `c-syntactic-indentation' are both non-nil, and
881 the star is the second character of a C style comment starter on a
882 comment-only-line, indent the line as a comment. If a numeric ARG is
883 supplied, point is inside a literal, or `c-syntactic-indentation' is nil,
884 this indentation is inhibited."
887 (self-insert-command (prefix-numeric-value arg))
888 ;; if we are in a literal, or if arg is given do not reindent the
889 ;; current line, unless this star introduces a comment-only line.
890 (if (c-save-buffer-state ()
891 (and c-syntactic-indentation
894 (eq (c-in-literal) 'c)
895 (eq (char-before) ?*)
898 (skip-chars-backward "*")
899 (if (eq (char-before) ?/)
901 (skip-chars-backward " \t")
903 (let (c-echo-syntactic-information-p) ; shut this up
904 (indent-according-to-mode))
907 (defun c-electric-semi&comma (arg)
908 "Insert a comma or semicolon.
910 If `c-electric-flag' is non-nil, point isn't inside a literal and a
911 numeric ARG hasn't been supplied, the command performs several electric
914 \(a) When the auto-newline feature is turned on (indicated by \"/la\" on
915 the mode line) a newline might be inserted. See the variable
916 `c-hanging-semi&comma-criteria' for how newline insertion is determined.
918 \(b) Any auto-newlines are indented. The original line is also
919 reindented unless `c-syntactic-indentation' is nil.
921 \(c) If auto-newline is turned on, a comma following a brace list or a
922 semicolon following a defun might be cleaned up, depending on the
923 settings of `c-cleanup-list'."
925 (let* (lim literal c-syntactic-context
928 (c-echo-syntactic-information-p nil))
930 (c-save-buffer-state ()
931 (setq lim (c-most-enclosing-brace (c-parse-state))
932 literal (c-in-literal lim)))
934 (self-insert-command (prefix-numeric-value arg))
936 (if (and c-electric-flag (not literal) (not arg))
937 ;; do all cleanups and newline insertions if c-auto-newline is on.
938 (if (or (not c-auto-newline)
939 (not (looking-at "[ \t]*\\\\?$")))
940 (if c-syntactic-indentation
942 ;; clean ups: list-close-comma or defun-close-semi
943 (let ((pos (- (point-max) (point))))
944 (if (c-save-buffer-state ()
946 (eq (c-last-command-char) ?,)
947 (memq 'list-close-comma c-cleanup-list))
949 (eq (c-last-command-char) ?\;)
950 (memq 'defun-close-semi c-cleanup-list)))
954 (eq (char-before) ?}))
955 ;; make sure matching open brace isn't in a comment
956 (not (c-in-literal lim))))
957 (delete-region (point) here))
958 (goto-char (- (point-max) pos)))
960 (when c-syntactic-indentation
961 (setq c-syntactic-context (c-guess-basic-syntax))
962 (c-indent-line c-syntactic-context))
963 ;; check to see if a newline should be added
964 (let ((criteria c-hanging-semi&comma-criteria)
965 answer add-newline-p)
967 (setq answer (funcall (car criteria)))
968 ;; only nil value means continue checking
970 (setq criteria (cdr criteria))
972 ;; only 'stop specifically says do not add a newline
973 (setq add-newline-p (not (eq answer 'stop)))
976 (c-newline-and-indent))
979 (defun c-electric-colon (arg)
982 If `c-electric-flag' is non-nil, the colon is not inside a literal and a
983 numeric ARG hasn't been supplied, the command performs several electric
986 \(a) If the auto-newline feature is turned on (indicated by \"/la\" on
987 the mode line) newlines are inserted before and after the colon based on
988 the settings in `c-hanging-colons-alist'.
990 \(b) Any auto-newlines are indented. The original line is also
991 reindented unless `c-syntactic-indentation' is nil.
993 \(c) If auto-newline is turned on, whitespace between two colons will be
994 \"cleaned up\" leaving a scope operator, if this action is set in
998 (let* ((bod (c-point 'bod))
999 (literal (c-save-buffer-state () (c-in-literal bod)))
1000 newlines is-scope-op
1002 (c-echo-syntactic-information-p nil))
1003 (self-insert-command (prefix-numeric-value arg))
1004 ;; Any electric action?
1005 (if (and c-electric-flag (not literal) (not arg))
1006 ;; Unless we're at EOL, only re-indentation happens.
1007 (if (not (looking-at "[ \t]*\\\\?$"))
1008 (if c-syntactic-indentation
1009 (indent-according-to-mode))
1011 ;; scope-operator clean-up?
1012 (let ((pos (- (point-max) (point)))
1014 (if (c-save-buffer-state () ; Why do we need this? [ACM, 2003-03-12]
1016 (memq 'scope-operator c-cleanup-list)
1017 (eq (char-before) ?:)
1020 (c-skip-ws-backward)
1021 (eq (char-before) ?:))
1022 (not (c-in-literal))
1023 (not (eq (char-after (- (point) 2)) ?:))))
1025 (delete-region (point) (1- here))
1026 (setq is-scope-op t)))
1027 (goto-char (- (point-max) pos)))
1029 ;; indent the current line if it's done syntactically.
1030 (if c-syntactic-indentation
1031 ;; Cannot use the same syntax analysis as we find below,
1032 ;; since that's made with c-syntactic-indentation-in-macros
1034 (indent-according-to-mode))
1036 ;; Calculate where, if anywhere, we want newlines.
1037 (c-save-buffer-state
1038 ((c-syntactic-indentation-in-macros t)
1039 (c-auto-newline-analysis t)
1040 ;; Turn on syntactic macro analysis to help with auto newlines
1042 (syntax (c-guess-basic-syntax))
1044 ;; Translate substatement-label to label for this operation.
1046 (if (eq (car (car elem)) 'substatement-label)
1047 (setcar (car elem) 'label))
1048 (setq elem (cdr elem)))
1049 ;; some language elements can only be determined by checking
1050 ;; the following line. Let's first look for ones that can be
1051 ;; found when looking on the line with the colon
1054 (or (c-lookup-lists '(case-label label access-label)
1055 syntax c-hanging-colons-alist)
1056 (c-lookup-lists '(member-init-intro inher-intro)
1060 (c-guess-basic-syntax)
1062 c-hanging-colons-alist)))))
1063 ;; does a newline go before the colon? Watch out for already
1064 ;; non-hung colons. However, we don't unhang them because that
1065 ;; would be a cleanup (and anti-social).
1066 (if (and (memq 'before newlines)
1069 (skip-chars-backward ": \t")
1071 (let ((pos (- (point-max) (point))))
1073 (c-newline-and-indent)
1074 (goto-char (- (point-max) pos))))
1075 ;; does a newline go after the colon?
1076 (if (and (memq 'after (cdr-safe newlines))
1078 (c-newline-and-indent))
1081 (defun c-electric-lt-gt (arg)
1082 "Insert a \"<\" or \">\" character.
1083 If the current language uses angle bracket parens (e.g. template
1084 arguments in C++), try to find out if the inserted character is a
1085 paren and give it paren syntax if appropriate.
1087 If `c-electric-flag' and `c-syntactic-indentation' are both non-nil, the
1088 line will be reindented if the inserted character is a paren or if it
1089 finishes a C++ style stream operator in C++ mode. Exceptions are when a
1090 numeric argument is supplied, or the point is inside a literal."
1093 (let ((c-echo-syntactic-information-p nil)
1094 final-pos found-delim case-fold-search)
1096 (self-insert-command (prefix-numeric-value arg))
1097 (setq final-pos (point))
1099 ;;;; 2010-01-31: There used to be code here to put a syntax-table text
1100 ;;;; property on the new < or > and its mate (if any) when they are template
1101 ;;;; parens. This is now done in an after-change function.
1103 ;; Indent the line if appropriate.
1104 (when (and c-electric-flag c-syntactic-indentation c-recognize-<>-arglists)
1106 (if (eq (c-last-command-char) ?<)
1107 ;; If a <, basically see if it's got "template" before it .....
1111 (progn (c-beginning-of-current-token) (point))))
1113 (c-backward-token-2)
1114 (looking-at c-opt-<>-sexp-key)))
1115 ;; ..... or is a C++ << operator.
1116 (and (c-major-mode-is 'c++-mode)
1118 (goto-char (1- final-pos))
1119 (c-beginning-of-current-token)
1121 (>= (match-end 0) final-pos)))
1123 ;; It's a >. Either a template/generic terminator ...
1124 (or (c-get-char-property (1- final-pos) 'syntax-table)
1125 ;; or a C++ >> operator.
1126 (and (c-major-mode-is 'c++-mode)
1128 (goto-char (1- final-pos))
1129 (c-beginning-of-current-token)
1131 (>= (match-end 0) final-pos))))))
1133 (goto-char final-pos)
1135 (indent-according-to-mode)
1136 (when (and (eq (char-before) ?>)
1137 (not executing-kbd-macro)
1138 blink-paren-function)
1139 ;; From now (2016-01-01), the syntax-table text properties on < and >
1140 ;; are applied in an after-change function, not during redisplay. Hence
1141 ;; we no longer need to call (sit-for 0) for blink paren to work.
1142 (funcall blink-paren-function)))))
1144 (defun c-electric-paren (arg)
1145 "Insert a parenthesis.
1147 If `c-syntactic-indentation' and `c-electric-flag' are both non-nil, the
1148 line is reindented unless a numeric ARG is supplied, or the parenthesis
1149 is inserted inside a literal.
1151 Whitespace between a function name and the parenthesis may get added or
1152 removed; see the variable `c-cleanup-list'.
1154 Also, if `c-electric-flag' and `c-auto-newline' are both non-nil, some
1155 newline cleanups are done if appropriate; see the variable `c-cleanup-list'."
1157 (let ((literal (c-save-buffer-state () (c-in-literal)))
1159 (c-echo-syntactic-information-p nil)
1161 (self-insert-command (prefix-numeric-value arg))
1163 (if (and (not arg) (not literal))
1164 (let* ( ;; We want to inhibit blinking the paren since this will
1165 ;; be most disruptive. We'll blink it ourselves
1167 (old-blink-paren blink-paren-function)
1168 blink-paren-function)
1169 (if (and c-syntactic-indentation c-electric-flag)
1170 (indent-according-to-mode))
1172 ;; If we're at EOL, check for new-line clean-ups.
1173 (when (and c-electric-flag c-auto-newline
1174 (looking-at "[ \t]*\\\\?$"))
1176 ;; clean up brace-elseif-brace
1178 (and (memq 'brace-elseif-brace c-cleanup-list)
1179 (eq (c-last-command-char) ?\()
1182 "\\([ \t\n]\\|\\\\\n\\)*"
1184 "\\([ \t\n]\\|\\\\\n\\)+"
1186 "\\([ \t\n]\\|\\\\\n\\)*"
1190 (not (c-save-buffer-state () (c-in-literal))))
1191 (delete-region (match-beginning 0) (match-end 0))
1192 (insert-and-inherit "} else if ("))
1194 ;; clean up brace-catch-brace
1196 (and (memq 'brace-catch-brace c-cleanup-list)
1197 (eq (c-last-command-char) ?\()
1200 "\\([ \t\n]\\|\\\\\n\\)*"
1202 "\\([ \t\n]\\|\\\\\n\\)*"
1206 (not (c-save-buffer-state () (c-in-literal))))
1207 (delete-region (match-beginning 0) (match-end 0))
1208 (insert-and-inherit "} catch (")))
1210 ;; Check for clean-ups at function calls. These two DON'T need
1211 ;; `c-electric-flag' or `c-syntactic-indentation' set.
1212 ;; Point is currently just after the inserted paren.
1213 (let (beg (end (1- (point))))
1216 ;; space-before-funcall clean-up?
1217 ((and (memq 'space-before-funcall c-cleanup-list)
1218 (eq (c-last-command-char) ?\()
1221 (skip-chars-backward " \t")
1223 (and (c-save-buffer-state () (c-on-identifier))
1224 ;; Don't add a space into #define FOO()....
1225 (not (and (c-beginning-of-macro)
1226 (c-forward-over-cpp-define-id)
1227 (eq (point) beg))))))
1229 (delete-region beg end)
1233 ;; compact-empty-funcall clean-up?
1234 ((c-save-buffer-state ()
1235 (and (memq 'compact-empty-funcall c-cleanup-list)
1236 (eq (c-last-command-char) ?\))
1238 (c-safe (backward-char 2))
1239 (when (looking-at "()")
1241 (skip-chars-backward " \t")
1243 (c-on-identifier)))))
1244 (delete-region beg end))))
1245 (and (eq last-input-event ?\))
1246 (not executing-kbd-macro)
1248 (funcall old-blink-paren))))))
1250 (defun c-electric-continued-statement ()
1251 "Reindent the current line if appropriate.
1253 This function is used to reindent the line after a keyword which
1254 continues an earlier statement is typed, e.g. an \"else\" or the
1255 \"while\" in a do-while block.
1257 The line is reindented if there is nothing but whitespace before the
1258 keyword on the line, the keyword is not inserted inside a literal, and
1259 `c-electric-flag' and `c-syntactic-indentation' are both non-nil."
1260 (let (;; shut this up
1261 (c-echo-syntactic-information-p nil))
1262 (when (c-save-buffer-state ()
1263 (and c-electric-flag
1264 c-syntactic-indentation
1265 (not (eq (c-last-command-char) ?_))
1267 (skip-syntax-backward "w")
1270 (not (c-in-literal (c-point 'bod)))))
1271 ;; Have to temporarily insert a space so that
1272 ;; c-guess-basic-syntax recognizes the keyword. Follow the
1273 ;; space with a nonspace to avoid messing up any whitespace
1274 ;; sensitive meddling that might be done, e.g. by
1275 ;; `c-backslash-region'.
1276 (insert-and-inherit " x")
1278 (indent-according-to-mode)
1279 (delete-char -2)))))
1282 ;; "nomenclature" functions + c-scope-operator.
1283 (defun c-forward-into-nomenclature (&optional arg)
1284 "Compatibility alias for `c-forward-subword'."
1286 (require 'cc-subword)
1287 (c-forward-subword arg))
1288 (make-obsolete 'c-forward-into-nomenclature 'c-forward-subword nil)
1290 (defun c-backward-into-nomenclature (&optional arg)
1291 "Compatibility alias for `c-backward-subword'."
1293 (require 'cc-subword)
1294 (c-backward-subword arg))
1295 (make-obsolete 'c-backward-into-nomenclature 'c-backward-subword nil)
1297 (defun c-scope-operator ()
1298 "Insert a double colon scope operator at point.
1299 No indentation or other \"electric\" behavior is performed."
1301 (insert-and-inherit "::"))
1304 ;; Movement (etc.) by defuns.
1305 (defun c-in-function-trailer-p (&optional lim)
1306 ;; Return non-nil if point is between the closing brace and the semicolon of
1307 ;; a brace construct which needs a semicolon, e.g. within the "variables"
1308 ;; portion of a declaration like "struct foo {...} bar ;".
1310 ;; Return the position of the main declaration. Otherwise, return nil.
1311 ;; Point is assumed to be at the top level and outside of any macro or
1314 ;; If LIM is non-nil, it is the bound on a the backward search for the
1315 ;; beginning of the declaration.
1317 ;; This function might do hidden buffer changes.
1318 (and c-opt-block-decls-with-vars-key
1320 (c-syntactic-skip-backward "^;}" lim)
1321 (let ((eo-block (point))
1323 (and (eq (char-before) ?\})
1324 (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1326 ;; Look for struct or union or ... If we find one, it might
1327 ;; be the return type of a function, or the like. Exclude
1329 (c-syntactic-re-search-forward
1330 (concat "[;=\(\[{]\\|\\("
1331 c-opt-block-decls-with-vars-key
1334 (match-beginning 1) ; Is there a "struct" etc., somewhere?
1335 (not (eq (char-before) ?_))
1336 (c-syntactic-re-search-forward "[;=\(\[{]" eo-block t t t)
1337 (eq (char-before) ?\{)
1340 (defun c-where-wrt-brace-construct ()
1341 ;; Determine where we are with respect to functions (or other brace
1342 ;; constructs, included in the term "function" in the rest of this comment).
1343 ;; Point is assumed to be outside any macro or literal.
1344 ;; This is used by c-\(beginning\|end\)-of-defun.
1346 ;; Return one of these symbols:
1347 ;; at-header : we're at the start of a function's header.
1348 ;; in-header : we're inside a function's header, this extending right
1349 ;; up to the brace. This bit includes any k&r declarations.
1350 ;; in-block : we're inside a function's brace block.
1351 ;; in-trailer : we're in the area between the "}" and ";" of something
1352 ;; like "struct foo {...} bar, baz;".
1353 ;; at-function-end : we're just after the closing brace (or semicolon) that
1354 ;; terminates the function.
1355 ;; outwith-function: we're not at or in any function. Being inside a
1356 ;; non-brace construct also counts as 'outwith-function'.
1358 ;; This function might do hidden buffer changes.
1361 decl-result brace-decl-p
1363 (paren-state (c-parse-state))
1364 (least-enclosing (c-least-enclosing-brace paren-state)))
1367 ((and least-enclosing
1368 (eq (char-after least-enclosing) ?\{))
1370 ((c-in-function-trailer-p)
1372 ((and (not least-enclosing)
1374 (consp (car paren-state))
1375 (eq start (cdar paren-state)))
1378 ;; Find the start of the current declaration. NOTE: If we're in the
1379 ;; variables after a "struct/eval" type block, we don't get to the
1380 ;; real declaration here - we detect and correct for this later.
1382 ;;If we're in the parameters' parens, move back out of them.
1383 (if least-enclosing (goto-char least-enclosing))
1384 ;; Kluge so that c-beginning-of-decl-1 won't go back if we're already
1385 ;; at a declaration.
1386 (if (or (and (eolp) (not (eobp))) ; EOL is matched by "\\s>"
1387 (not (c-looking-at-non-alphnumspace)))
1389 (setq kluge-start (point))
1391 (car (c-beginning-of-decl-1
1392 ;; NOTE: If we're in a K&R region, this might be the start
1393 ;; of a parameter declaration, not the actual function.
1394 ;; It might also leave us at a label or "label" like
1396 (and least-enclosing ; LIMIT for c-b-of-decl-1
1397 (c-safe-position least-enclosing paren-state)))))
1399 ;; Has the declaration we've gone back to got braces?
1400 (or (eq decl-result 'label)
1403 (and (c-syntactic-re-search-forward "[;{]" nil t t)
1404 (or (eq (char-before) ?\{)
1405 (and c-recognize-knr-p
1406 ;; Might have stopped on the
1407 ;; ';' in a K&R argdecl. In
1408 ;; that case the declaration
1409 ;; should contain a block.
1410 (c-in-knr-argdecl)))))))
1413 ((or (eq decl-result 'label) ; e.g. "private:" or invalid syntax.
1414 (= (point) kluge-start)) ; might be BOB or unbalanced parens.
1416 ((eq decl-result 'same)
1418 (if (eq (point) start)
1422 ((eq decl-result 'previous)
1423 (if (and (not brace-decl-p)
1424 (c-in-function-trailer-p))
1428 "c-where-wrt-brace-construct: c-beginning-of-decl-1 returned %s"
1431 (defun c-backward-to-nth-BOF-{ (n where)
1432 ;; Skip to the opening brace of the Nth function before point. If
1433 ;; point is inside a function, this counts as the first. Point must be
1434 ;; outside any comment/string or macro.
1436 ;; N must be strictly positive.
1437 ;; WHERE describes the position of point, one of the symbols `at-header',
1438 ;; `in-header', `in-block', `in-trailer', `at-function-end',
1439 ;; `outwith-function' as returned by c-where-wrt-brace-construct.
1441 ;; If we run out of functions, leave point at BOB. Return zero on success,
1442 ;; otherwise the number of {s still to go.
1444 ;; This function may do hidden buffer changes
1446 ;; What we do to go back the first defun depends on where we start.
1448 ((eq where 'in-block)
1449 (goto-char (c-least-enclosing-brace (c-parse-state)))
1451 ((eq where 'in-header)
1452 (c-syntactic-re-search-forward "{")
1455 ((memq where '(at-header outwith-function at-function-end in-trailer))
1456 (c-syntactic-skip-backward "^}")
1457 (when (eq (char-before) ?\})
1460 (t (error "Unknown `where' %s in c-backward-to-nth-EOF-{" where)))
1462 ;; Each time round the loop, go back to a "{" at the outermost level.
1463 (while (and (> n 0) (not (bobp)))
1464 (c-parse-state) ; This call speeds up the following one
1465 ; by a factor of ~6. Hmmm. 2006/4/5.
1466 (c-syntactic-skip-backward "^}")
1467 (when (eq (char-before) ?\})
1472 (defun c-narrow-to-most-enclosing-decl-block (&optional inclusive)
1473 ;; If we are inside a decl-block (in the sense of c-looking-at-decl-block),
1474 ;; i.e. something like namespace{} or extern{}, narrow to the insides of
1475 ;; that block (NOT including the enclosing braces) if INCLUSIVE is nil,
1476 ;; otherwise include the braces. If the closing brace is missing,
1477 ;; (point-max) is used instead.
1478 (let ((paren-state (c-parse-state))
1480 (setq encl-decl (and paren-state (c-most-enclosing-decl-block paren-state)))
1485 (progn (goto-char encl-decl)
1486 (c-beginning-of-decl-1)
1490 (goto-char encl-decl)
1491 (or (c-safe (forward-list)
1497 (defun c-widen-to-enclosing-decl-scope (paren-state orig-point-min orig-point-max)
1498 ;; Narrow the buffer to the innermost declaration scope (e.g. a class, a
1499 ;; namespace or the "whole buffer") recorded in PAREN-STATE, the bounding
1500 ;; braces NOT being included in the resulting region. On no account may the
1501 ;; final region exceed that bounded by ORIG-POINT-MIN, ORIG-POINT-MAX.
1502 ;; PAREN-STATE is a list of buffer positions in the style of
1503 ;; (c-parse-state), one of which will be that of the desired opening brace,
1506 ;; Return the position of the enclosing opening brace, or nil
1507 (let (encl-decl) ; putative position of decl-scope's opening brace.
1509 (narrow-to-region orig-point-min orig-point-max)
1510 (setq encl-decl (and paren-state
1511 (c-most-enclosing-decl-block paren-state))))
1515 (narrow-to-region (1+ encl-decl)
1517 (goto-char encl-decl)
1518 (or (c-safe (forward-list)
1522 (narrow-to-region orig-point-min orig-point-max)
1526 (defmacro c-while-widening-to-decl-block (condition)
1527 ;; Repeatedly evaluate CONDITION until it returns nil. After each
1528 ;; evaluation, if `c-defun-tactic' is set appropriately, widen to innards
1529 ;; of the next enclosing declaration block (e.g. namespace, class), or the
1530 ;; buffer's original restriction.
1532 ;; This is a very special purpose macro, which assumes the existence of
1533 ;; several variables. It is for use only in c-beginning-of-defun and
1537 (eq c-defun-tactic 'go-outward)
1539 (setq paren-state (c-whack-state-after lim paren-state))
1540 (setq lim (c-widen-to-enclosing-decl-scope
1541 paren-state orig-point-min orig-point-max))
1542 (setq where 'in-block))))
1544 (defun c-beginning-of-defun (&optional arg)
1545 "Move backward to the beginning of a defun.
1546 Every top level declaration that contains a brace paren block is
1547 considered to be a defun.
1549 With a positive argument, move backward that many defuns. A negative
1550 argument -N means move forward to the Nth following beginning. Return
1551 t unless search stops due to beginning or end of buffer.
1553 Unlike the built-in `beginning-of-defun' this tries to be smarter
1554 about finding the char with open-parenthesis syntax that starts the
1558 (or arg (setq arg 1))
1560 (c-save-buffer-state
1561 (beginning-of-defun-function end-of-defun-function
1563 (paren-state (copy-tree (c-parse-state))) ; This must not share list
1564 ; structure with other users of c-state-cache.
1565 (orig-point-min (point-min)) (orig-point-max (point-max))
1566 lim ; Position of { which has been widened to.
1567 where pos case-fold-search)
1570 (if (eq c-defun-tactic 'go-outward)
1571 (setq lim (c-widen-to-enclosing-decl-scope ; e.g. class, namespace.
1572 paren-state orig-point-min orig-point-max)))
1574 ;; Move back out of any macro/comment/string we happen to be in.
1575 (c-beginning-of-macro)
1576 (setq pos (c-literal-limits))
1577 (if pos (goto-char (car pos)))
1579 (setq where (c-where-wrt-brace-construct))
1582 ;; Move forward to the closing brace of a function.
1584 (if (memq where '(at-function-end outwith-function))
1585 (setq arg (1+ arg)))
1587 (c-while-widening-to-decl-block
1588 (< (setq arg (- (c-forward-to-nth-EOF-} (- arg) where))) 0)))
1589 ;; Move forward to the next opening brace....
1590 (when (and (= arg 0)
1592 (c-while-widening-to-decl-block
1593 (not (c-syntactic-re-search-forward "{" nil 'eob)))
1594 (eq (char-before) ?{)))
1596 ;; ... and backward to the function header.
1597 (c-beginning-of-decl-1)
1600 ;; Move backward to the opening brace of a function, making successively
1601 ;; larger portions of the buffer visible as necessary.
1603 (c-while-widening-to-decl-block
1604 (> (setq arg (c-backward-to-nth-BOF-{ arg where)) 0)))
1607 ;; Go backward to this function's header.
1608 (c-beginning-of-decl-1)
1611 ;; We're now there, modulo comments and whitespace.
1612 ;; Try to be line oriented; position point at the closest
1613 ;; preceding boi that isn't inside a comment, but if we hit
1614 ;; the previous declaration then we use the current point
1616 (while (and (/= (point) (c-point 'boi))
1617 (c-backward-single-comment)))
1618 (if (/= (point) (c-point 'boi))
1621 (c-keep-region-active)
1624 (defun c-forward-to-nth-EOF-} (n where)
1625 ;; Skip to the closing brace of the Nth function after point. If
1626 ;; point is inside a function, this counts as the first. Point must be
1627 ;; outside any comment/string or macro.
1629 ;; N must be strictly positive.
1630 ;; WHERE describes the position of point, one of the symbols `at-header',
1631 ;; `in-header', `in-block', `in-trailer', `at-function-end',
1632 ;; `outwith-function' as returned by c-where-wrt-brace-construct.
1634 ;; If we run out of functions, leave point at EOB. Return zero on success,
1635 ;; otherwise the number of }s still to go.
1637 ;; This function may do hidden buffer changes.
1640 ;; What we do to go forward over the first defun depends on where we
1641 ;; start. We go to the closing brace of that defun, even when we go
1642 ;; backwards to it (in a "struct foo {...} bar ;").
1644 ((eq where 'in-block)
1645 (goto-char (c-least-enclosing-brace (c-parse-state)))
1648 ((eq where 'in-trailer)
1649 (c-syntactic-skip-backward "^}")
1651 ((memq where '(at-function-end outwith-function at-header in-header))
1652 (when (c-syntactic-re-search-forward "{" nil 'eob)
1656 (t (error "c-forward-to-nth-EOF-}: `where' is %s" where)))
1658 ;; Each time round the loop, go forward to a "}" at the outermost level.
1659 (while (and (> n 0) (not (eobp)))
1660 ;(c-parse-state) ; This call speeds up the following one by a factor
1661 ; of ~6. Hmmm. 2006/4/5.
1662 (when (c-syntactic-re-search-forward "{" nil 'eob)
1668 (defun c-end-of-defun (&optional arg)
1669 "Move forward to the end of a top level declaration.
1670 With argument, do it that many times. Negative argument -N means move
1671 back to Nth preceding end. Returns t unless search stops due to
1672 beginning or end of buffer.
1674 An end of a defun occurs right after the close-parenthesis that matches
1675 the open-parenthesis that starts a defun; see `beginning-of-defun'."
1677 (or arg (setq arg 1))
1679 (c-save-buffer-state
1680 (beginning-of-defun-function end-of-defun-function
1682 (paren-state (copy-tree (c-parse-state))) ; This must not share list
1683 ; structure with other users of c-state-cache.
1684 (orig-point-min (point-min)) (orig-point-max (point-max))
1686 where pos case-fold-search)
1689 (if (eq c-defun-tactic 'go-outward)
1690 (setq lim (c-widen-to-enclosing-decl-scope ; e.g. class, namespace
1691 paren-state orig-point-min orig-point-max)))
1693 ;; Move back out of any macro/comment/string we happen to be in.
1694 (c-beginning-of-macro)
1695 (setq pos (c-literal-limits))
1696 (if pos (goto-char (car pos)))
1698 (setq where (c-where-wrt-brace-construct))
1701 ;; Move backwards to the } of a function
1703 (if (memq where '(at-header outwith-function))
1704 (setq arg (1+ arg)))
1706 (c-while-widening-to-decl-block
1707 (< (setq arg (- (c-backward-to-nth-BOF-{ (- arg) where))) 0)))
1709 (c-while-widening-to-decl-block
1710 (progn (c-syntactic-skip-backward "^}")
1711 (not (eq (char-before) ?}))))))
1713 ;; Move forward to the } of a function
1715 (c-while-widening-to-decl-block
1716 (> (setq arg (c-forward-to-nth-EOF-} arg where)) 0))))
1718 ;; Do we need to move forward from the brace to the semicolon?
1720 (if (c-in-function-trailer-p) ; after "}" of struct/enum, etc.
1721 (c-syntactic-re-search-forward ";"))
1724 ;; We're there now, modulo comments and whitespace.
1725 ;; Try to be line oriented; position point after the next
1726 ;; newline that isn't inside a comment, but if we hit the
1727 ;; next declaration then we use the current point instead.
1728 (while (and (not (bolp))
1729 (not (looking-at "\\s *$"))
1730 (c-forward-single-comment)))
1732 ((looking-at "\\s *$")
1737 (c-keep-region-active)
1740 (defun c-defun-name ()
1741 "Return the name of the current defun, or NIL if there isn't one.
1742 \"Defun\" here means a function, or other top level construct
1743 with a brace block."
1745 (c-save-buffer-state
1746 (beginning-of-defun-function end-of-defun-function
1747 where pos name-end case-fold-search)
1752 ;; Move back out of any macro/comment/string we happen to be in.
1753 (c-beginning-of-macro)
1754 (setq pos (c-literal-limits))
1755 (if pos (goto-char (car pos)))
1757 (setq where (c-where-wrt-brace-construct))
1759 ;; Move to the beginning of the current defun, if any, if we're not
1761 (if (eq where 'outwith-function)
1763 (unless (eq where 'at-header)
1764 (c-backward-to-nth-BOF-{ 1 where)
1765 (c-beginning-of-decl-1))
1767 ;; Pick out the defun name, according to the type of defun.
1769 ;; struct, union, enum, or similar:
1770 ((and (looking-at c-type-prefix-key)
1771 (progn (c-forward-token-2 2) ; over "struct foo "
1772 (or (eq (char-after) ?\{)
1773 (looking-at c-symbol-key)))) ; "struct foo bar ..."
1774 (save-match-data (c-forward-token-2))
1775 (when (eq (char-after) ?\{)
1776 (c-backward-token-2)
1777 (looking-at c-symbol-key))
1778 (match-string-no-properties 0))
1780 ((looking-at "DEFUN\\s-*(") ;"DEFUN\\_>") think of XEmacs!
1781 ;; DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory, ...) ==> Ffile_name_directory
1782 ;; DEFUN(POSIX::STREAM-LOCK, stream lockp &key BLOCK SHARED START LENGTH) ==> POSIX::STREAM-LOCK
1784 (c-forward-syntactic-ws)
1785 (when (eq (char-after) ?\")
1787 (c-forward-token-2)) ; over the comma and following WS.
1788 (buffer-substring-no-properties
1792 (c-backward-syntactic-ws)
1796 ;; Normal function or initializer.
1797 (when (c-syntactic-re-search-forward "[{(]" nil t)
1799 (c-backward-syntactic-ws)
1800 (when (eq (char-before) ?\=) ; struct foo bar = {0, 0} ;
1801 (c-backward-token-2)
1802 (c-backward-syntactic-ws))
1803 (setq name-end (point))
1804 (c-backward-token-2)
1805 (buffer-substring-no-properties (point) name-end)))))))))
1807 (defun c-declaration-limits (near)
1808 ;; Return a cons of the beginning and end positions of the current
1809 ;; top level declaration or macro. If point is not inside any then
1810 ;; nil is returned, unless NEAR is non-nil in which case the closest
1811 ;; following one is chosen instead (if there is any). The end
1812 ;; position is at the next line, providing there is one before the
1815 ;; This function might do hidden buffer changes.
1818 (when (eq c-defun-tactic 'go-outward)
1819 (c-narrow-to-most-enclosing-decl-block t) ; e.g. class, namespace
1820 (or (save-restriction
1821 (c-narrow-to-most-enclosing-decl-block nil)
1823 ;; Note: Some code duplication in `c-beginning-of-defun' and
1824 ;; `c-end-of-defun'.
1826 (let ((start (point))
1827 (paren-state (c-parse-state))
1830 (goto-char (c-least-enclosing-brace paren-state))
1831 ;; If we moved to the outermost enclosing paren
1832 ;; then we can use c-safe-position to set the
1833 ;; limit. Can't do that otherwise since the
1834 ;; earlier paren pair on paren-state might very
1835 ;; well be part of the declaration we should go
1837 (setq lim (c-safe-position (point) paren-state))
1839 ;; At top level. Make sure we aren't inside a literal.
1840 (setq pos (c-literal-limits
1841 (c-safe-position (point) paren-state)))
1842 (if pos (goto-char (car pos))))
1844 (when (c-beginning-of-macro)
1853 (when (or (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1855 ;; We moved back over the previous defun. Skip to the next
1856 ;; one. Not using c-forward-syntactic-ws here since we
1857 ;; should not skip a macro. We can also be directly after
1858 ;; the block in a `c-opt-block-decls-with-vars-key'
1859 ;; declaration, but then we won't move significantly far
1862 (c-forward-comments)
1864 (when (and near (c-beginning-of-macro))
1872 (if (eobp) (throw 'exit nil))
1874 ;; Check if `c-beginning-of-decl-1' put us after the block in a
1875 ;; declaration that doesn't end there. We're searching back and
1876 ;; forth over the block here, which can be expensive.
1878 (if (and c-opt-block-decls-with-vars-key
1880 (c-backward-syntactic-ws)
1881 (eq (char-before) ?}))
1882 (eq (car (c-beginning-of-decl-1))
1886 (and (> (point) pos)
1887 (setq end-pos (point)))))
1891 (if (and (not near) (> (point) start))
1894 ;; Try to be line oriented; position the limits at the
1895 ;; closest preceding boi, and after the next newline, that
1896 ;; isn't inside a comment, but if we hit a neighboring
1897 ;; declaration then we instead use the exact declaration
1898 ;; limit in that direction.
1901 (while (and (/= (point) (c-point 'boi))
1902 (c-backward-single-comment)))
1903 (if (/= (point) (c-point 'boi))
1911 (while (and (not (bolp))
1912 (not (looking-at "\\s *$"))
1913 (c-forward-single-comment)))
1916 ((looking-at "\\s *$")
1922 (goto-char (point-min))
1923 (c-forward-decl-or-cast-1 -1 nil nil)
1924 (eq (char-after) ?\{)
1925 (cons (point-min) (point-max))))))))
1927 (defun c-mark-function ()
1928 "Put mark at end of the current top-level declaration or macro, point at beginning.
1929 If point is not inside any then the closest following one is
1930 chosen. Each successive call of this command extends the marked
1931 region by one function.
1933 A mark is left where the command started.
1935 As opposed to \\[c-beginning-of-defun] and \\[c-end-of-defun], this
1936 function does not require the declaration to contain a brace block."
1937 ;; Middle sentence of doc-string was: A mark is left where the command
1938 ;; started, unless the region is already active \(in Transient Mark mode).
1939 ;; FIXME!!! for transient-mark/zemacs sometime. (2012-03-08.)
1942 (let (decl-limits case-fold-search)
1943 (c-save-buffer-state nil
1944 ;; We try to be line oriented, unless there are several
1945 ;; declarations on the same line.
1946 (if (looking-at c-syntactic-eol)
1947 (c-backward-token-2 1 nil (c-point 'bol)))
1948 (setq decl-limits (c-declaration-limits t)))
1950 (if (not decl-limits)
1951 (error "Cannot find any declaration")
1952 (let* ((extend-region-p
1953 (and (eq this-command 'c-mark-function)
1954 (eq last-command 'c-mark-function)))
1955 (push-mark-p (and (eq this-command 'c-mark-function)
1956 (not extend-region-p)
1957 ;; (not (and transient-mark-mode mark-active))
1958 ;; FIXME!!!, sometime (2012-03-08.)
1960 (if push-mark-p (push-mark (point)))
1963 (exchange-point-and-mark)
1964 (setq decl-limits (c-declaration-limits t))
1965 (when (not decl-limits)
1966 (exchange-point-and-mark)
1967 (error "Cannot find any declaration"))
1968 (goto-char (cdr decl-limits))
1969 (exchange-point-and-mark))
1970 (goto-char (car decl-limits))
1971 (push-mark (cdr decl-limits) nil t))))))
1973 (defun c-cpp-define-name ()
1974 "Return the name of the current CPP macro, or NIL if we're not in one."
1976 (let (case-fold-search)
1978 (and c-opt-cpp-macro-define-start
1979 (c-beginning-of-macro)
1980 (looking-at c-opt-cpp-macro-define-start)
1981 (match-string-no-properties 1)))))
1984 ;; Movement by statements.
1985 (defun c-in-comment-line-prefix-p ()
1986 ;; Point is within a comment. Is it also within a comment-prefix?
1987 ;; Space at BOL which precedes a comment-prefix counts as part of it.
1989 ;; This function might do hidden buffer changes.
1990 (let ((here (point)))
1993 (skip-chars-forward " \t")
1994 (and (looking-at c-current-comment-prefix)
1995 (/= (match-beginning 0) (match-end 0))
1996 (< here (match-end 0))))))
1998 (defun c-narrow-to-comment-innards (range)
1999 ;; Narrow to the "inside" of the comment (block) defined by range, as
2002 ;; A c-style block comment has its opening "/*" and its closing "*/" (if
2003 ;; present) removed. A c++-style line comment retains its opening "//" but
2004 ;; has any final NL removed. If POINT is currently outwith these innards,
2005 ;; move it to the appropriate boundary.
2007 ;; This narrowing simplifies the sentence movement functions, since it
2008 ;; eliminates awkward things at the boundaries of the comment (block).
2010 ;; This function might do hidden buffer changes.
2011 (let* ((lit-type (c-literal-type range))
2012 (beg (if (eq lit-type 'c) (+ (car range) 2) (car range)))
2013 (end (if (eq lit-type 'c)
2014 (if (and (eq (char-before (cdr range)) ?/)
2015 (eq (char-before (1- (cdr range))) ?*))
2018 (if (eq (cdr range) (point-max))
2020 (- (cdr range) 1)))))
2022 (goto-char end)) ; This would be done automatically by ...
2024 (goto-char beg)) ; ... narrow-to-region but is not documented.
2025 (narrow-to-region beg end)))
2027 (defun c-beginning-of-sentence-in-comment (range)
2028 ;; Move backwards to the "beginning of a sentence" within the comment
2029 ;; defined by RANGE, a cons of its starting and ending positions. If we
2030 ;; find a BOS, return NIL. Otherwise, move point to just before the start
2031 ;; of the comment and return T.
2033 ;; The BOS is either text which follows a regexp match of sentence-end,
2034 ;; or text which is a beginning of "paragraph".
2035 ;; Comment-prefixes are treated like WS when calculating BOSes or BOPs.
2037 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2038 ;; It is not a general function, but is intended only for calling from
2039 ;; c-move-over-sentence. Not all preconditions have been explicitly stated.
2041 ;; This function might do hidden buffer changes.
2043 (let ((start-point (point)))
2045 (c-narrow-to-comment-innards range) ; This may move point back.
2046 (let* ((here (point))
2048 (here-filler ; matches WS and comment-prefixes at point.
2049 (concat "\\=\\(^[ \t]*\\(" c-current-comment-prefix "\\)"
2050 "\\|[ \t\n\r\f]\\)*"))
2051 (prefix-at-bol-here ; matches WS and prefix at BOL, just before point
2052 (concat "^[ \t]*\\(" c-current-comment-prefix "\\)[ \t\n\r\f]*\\="))
2053 ;; First, find the previous paragraph start, if any.
2054 (par-beg ; point where non-WS/non-prefix text of paragraph starts.
2056 (forward-paragraph -1) ; uses cc-mode values of
2057 ; paragraph-\(start\|separate\)
2058 (if (> (re-search-forward here-filler nil t) here)
2060 (when (>= (point) here)
2061 (forward-paragraph -2)
2062 (if (> (re-search-forward here-filler nil t) here)
2066 ;; Now seek successively earlier sentence ends between PAR-BEG and
2067 ;; HERE, until the "start of sentence" following it is earlier than
2068 ;; HERE, or we hit PAR-BEG. Beware of comment prefixes!
2069 (while (and (re-search-backward (c-sentence-end) par-beg 'limit)
2071 (goto-char (match-end 0)) ; tentative beginning of sentence
2072 (or (>= (point) here)
2073 (and (not (bolp)) ; Found a non-blank comment-prefix?
2075 (if (re-search-backward prefix-at-bol-here nil t)
2076 (/= (match-beginning 1) (match-end 1)))))
2077 (progn ; Skip the crud to find a real b-o-s.
2078 (if (c-in-comment-line-prefix-p)
2079 (beginning-of-line))
2080 (re-search-forward here-filler) ; always succeeds.
2081 (>= (point) here))))
2083 (re-search-forward here-filler)))
2085 (if (< (point) start-point)
2087 (goto-char (car range))
2090 (defun c-end-of-sentence-in-comment (range)
2091 ;; Move forward to the "end of a sentence" within the comment defined by
2092 ;; RANGE, a cons of its starting and ending positions (enclosing the opening
2093 ;; comment delimiter and the terminating */ or newline). If we find an EOS,
2094 ;; return NIL. Otherwise, move point to just after the end of the comment
2097 ;; The EOS is just after the non-WS part of the next match of the regexp
2098 ;; sentence-end. Typically, this is just after one of [.!?]. If there is
2099 ;; no sentence-end match following point, any WS before the end of the
2100 ;; comment will count as EOS, providing we're not already in it.
2102 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2103 ;; It is not a general function, but is intended only for calling from
2104 ;; c-move-over-sentence.
2106 ;; This function might do hidden buffer changes.
2108 (let ((start-point (point))
2109 ;; (lit-type (c-literal-type range)) ; Commented out, 2005/11/23, ACM
2112 (c-narrow-to-comment-innards range) ; This might move point forwards.
2113 (let* ((here (point))
2114 (par-end ; EOL position of last text in current/next paragraph.
2116 ;; The cc-mode values of paragraph-\(start\|separate\), set
2117 ;; in c-setup-paragraph-variables, are used in the
2119 (forward-paragraph 1)
2120 (if (eq (preceding-char) ?\n) (forward-char -1))
2121 (when (<= (point) here) ; can happen, e.g., when HERE is at EOL.
2123 (forward-paragraph 2)
2124 (if (eq (preceding-char) ?\n) (forward-char -1)))
2129 (concat "^[ \t]*\\(" c-current-comment-prefix "\\)\\=")))
2130 ;; Go forward one "comment-prefix which looks like sentence-end"
2131 ;; each time round the following:
2132 (while (and (re-search-forward (c-sentence-end) par-end 'limit)
2135 (skip-chars-backward " \t\n")
2136 (or (and (not (bolp))
2137 (re-search-backward prefix-at-bol-here nil t)
2138 (/= (match-beginning 1) (match-end 1)))
2139 (<= (point) here))))
2142 ;; Take special action if we're up against the end of a comment (of
2143 ;; either sort): Leave point just after the last non-ws text.
2144 (if (eq (point) (point-max))
2145 (while (or (/= (skip-chars-backward " \t\n") 0)
2146 (and (re-search-backward prefix-at-bol-here nil t)
2147 (/= (match-beginning 1) (match-end 1))))))))
2149 (if (> (point) start-point)
2151 (goto-char (cdr range))
2154 (defun c-beginning-of-sentence-in-string (range)
2155 ;; Move backwards to the "beginning of a sentence" within the string defined
2156 ;; by RANGE, a cons of its starting and ending positions (enclosing the
2157 ;; string quotes). If we find a BOS, return NIL. Otherwise, move point to
2158 ;; just before the start of the string and return T.
2160 ;; The BOS is either the text which follows a regexp match of sentence-end
2161 ;; or text which is a beginning of "paragraph". For the purposes of
2162 ;; determining paragraph boundaries, escaped newlines are treated as
2163 ;; ordinary newlines.
2165 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2166 ;; It is not a general function, but is intended only for calling from
2167 ;; c-move-over-sentence.
2169 ;; This function might do hidden buffer changes.
2171 (let* ((here (point)) last
2172 (end (1- (cdr range)))
2173 (here-filler ; matches WS and escaped newlines at point.
2174 "\\=\\([ \t\n\r\f]\\|\\\\[\n\r]\\)*")
2175 ;; Enhance paragraph-start and paragraph-separate also to recognize
2176 ;; blank lines terminated by escaped EOLs. IT MAY WELL BE that
2177 ;; these values should be customizable user options, or something.
2178 (paragraph-start c-string-par-start)
2179 (paragraph-separate c-string-par-separate)
2181 (par-beg ; beginning of current (or previous) paragraph.
2184 (narrow-to-region (1+ (car range)) end)
2185 (forward-paragraph -1) ; uses above values of
2186 ; paragraph-\(start\|separate\)
2187 (if (> (re-search-forward here-filler nil t) here)
2189 (when (>= (point) here)
2190 (forward-paragraph -2)
2191 (if (> (re-search-forward here-filler nil t) here)
2194 ;; Now see if we can find a sentence end after PAR-BEG.
2195 (while (and (re-search-backward c-sentence-end-with-esc-eol par-beg 'limit)
2197 (goto-char (match-end 0))
2201 here-filler end t) ; always succeeds. Use end rather
2202 ; than here, in case point starts
2203 ; beyond the closing quote.
2204 (>= (point) here))))
2206 (re-search-forward here-filler here t)
2207 (if (< (point) here)
2209 (goto-char (car range))
2212 (defun c-end-of-sentence-in-string (range)
2213 ;; Move forward to the "end of a sentence" within the string defined by
2214 ;; RANGE, a cons of its starting and ending positions. If we find an EOS,
2215 ;; return NIL. Otherwise, move point to just after the end of the string
2218 ;; The EOS is just after the non-WS part of the next match of the regexp
2219 ;; sentence-end. Typically, this is just after one of [.!?]. If there is
2220 ;; no sentence-end match following point, any WS before the end of the
2221 ;; string will count as EOS, providing we're not already in it.
2223 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2224 ;; It is not a general function, but is intended only for calling from
2225 ;; c-move-over-sentence.
2227 ;; This function might do hidden buffer changes.
2229 (let* ((here (point))
2231 ;; Enhance paragraph-start and paragraph-separate to recognize
2232 ;; blank lines terminated by escaped EOLs.
2233 (paragraph-start c-string-par-start)
2234 (paragraph-separate c-string-par-separate)
2236 (par-end ; EOL position of last text in current/next paragraph.
2239 (narrow-to-region (car range) (1- (cdr range)))
2240 ;; The above values of paragraph-\(start\|separate\) are used
2241 ;; in the following.
2242 (forward-paragraph 1)
2244 ;; (re-search-backward filler-here nil t) would find an empty
2245 ;; string. Therefore we simulate it by the following:
2246 (while (or (/= (skip-chars-backward " \t\n\r\f") 0)
2247 (re-search-backward "\\\\\\($\\)\\=" nil t)))
2248 (unless (> (point) here)
2250 (forward-paragraph 1)
2251 (while (or (/= (skip-chars-backward " \t\n\r\f") 0)
2252 (re-search-backward "\\\\\\($\\)\\=" nil t))))
2254 ;; Try to go forward a sentence.
2255 (when (re-search-forward c-sentence-end-with-esc-eol par-end 'limit)
2257 (while (or (/= (skip-chars-backward " \t\n") 0)
2258 (re-search-backward "\\\\\\($\\)\\=" nil t))))
2259 ;; Did we move a sentence, or did we hit the end of the string?
2260 (if (> (point) here)
2262 (goto-char (cdr range))
2265 (defun c-ascertain-preceding-literal ()
2266 ;; Point is not in a literal (i.e. comment or string (include AWK regexp)).
2267 ;; If a literal is the next thing (aside from whitespace) to be found before
2268 ;; point, return a cons of its start.end positions (enclosing the
2269 ;; delimiters). Otherwise return NIL.
2271 ;; This function might do hidden buffer changes.
2273 (c-collect-line-comments
2274 (let ((here (point))
2276 (if (c-backward-single-comment)
2277 (cons (point) (progn (c-forward-single-comment) (point)))
2279 ;; to prevent `looking-at' seeing a " at point.
2280 (narrow-to-region (point-min) here)
2283 ;; An EOL can act as an "open string" terminator in AWK.
2284 (looking-at c-ws*-string-limit-regexp)
2286 (progn (backward-char)
2287 (looking-at c-string-limit-regexp))))
2288 (goto-char (match-end 0)) ; just after the string terminator.
2290 (c-safe (c-backward-sexp 1) ; move back over the string.
2291 (cons (point) pos)))))))))
2293 (defun c-ascertain-following-literal ()
2294 ;; Point is not in a literal (i.e. comment or string (include AWK regexp)).
2295 ;; If a literal is the next thing (aside from whitespace) following point,
2296 ;; return a cons of its start.end positions (enclosing the delimiters).
2297 ;; Otherwise return NIL.
2299 ;; This function might do hidden buffer changes.
2301 (c-collect-line-comments
2304 (if (looking-at c-string-limit-regexp) ; string-delimiter.
2305 (cons (point) (or (c-safe (progn (c-forward-sexp 1) (point)))
2308 (if (c-forward-single-comment)
2309 (cons pos (point))))))))
2311 (defun c-after-statement-terminator-p () ; Should we pass in LIM here?
2312 ;; Does point immediately follow a statement "terminator"? A virtual
2313 ;; semicolon is regarded here as such. So is an opening brace ;-)
2315 ;; This function might do hidden buffer changes.
2318 (and (looking-at "[;{}]")
2319 (not (and c-special-brace-lists ; Pike special brace lists.
2320 (eq (char-after) ?{)
2321 (c-looking-at-special-brace-list)))))
2323 ;; The following (for macros) is not strict about exactly where we are
2324 ;; wrt white space at the end of the macro. Doesn't seem to matter too
2325 ;; much. ACM 2004/3/29.
2328 (if (c-beginning-of-macro)
2329 (setq eom (progn (c-end-of-macro)
2333 (c-forward-comments)
2334 (>= (point) eom))))))
2336 (defun c-back-over-illiterals (macro-start)
2337 ;; Move backwards over code which isn't a literal (i.e. comment or string),
2338 ;; stopping before reaching BOB or a literal or the boundary of a
2339 ;; preprocessor statement or the "beginning of a statement". MACRO-START is
2340 ;; the position of the '#' beginning the current preprocessor directive, or
2341 ;; NIL if we're not in such.
2343 ;; Return a cons (A.B), where
2344 ;; A is NIL if we moved back to a BOS (and know it), T otherwise (we
2345 ;; didn't move, or we hit a literal, or we're not sure about BOS).
2346 ;; B is MACRO-BOUNDARY if we are about to cross the boundary out of or
2347 ;; into a macro, otherwise LITERAL if we've hit a literal, otherwise NIL
2349 ;; The total collection of returned values is as follows:
2350 ;; (nil . nil): Found a BOS whilst remaining inside the illiterals.
2351 ;; (t . literal): No BOS found: only a comment/string. We _might_ be at
2352 ;; a BOS - the caller must check this.
2353 ;; (nil . macro-boundary): only happens with non-nil macro-start. We've
2354 ;; moved and reached the opening # of the macro.
2355 ;; (t . macro-boundary): Every other circumstance in which we're at a
2356 ;; macro-boundary. We might be at a BOS.
2358 ;; Point is left either at the beginning-of-statement, or at the last non-ws
2359 ;; code before encountering the literal/BOB or macro-boundary.
2361 ;; Note that this function moves within either preprocessor commands
2362 ;; (macros) or normal code, but will not cross a boundary between the two,
2363 ;; or between two distinct preprocessor commands.
2365 ;; Stop before `{' and after `;', `{', `}' and `};' when not followed by `}'
2366 ;; or `)', but on the other side of the syntactic ws. Move by sexps and
2367 ;; move into parens. Also stop before `#' when it's at boi on a line.
2369 ;; This function might do hidden buffer changes.
2371 (let ((here (point))
2372 last) ; marks the position of non-ws code, what'll be BOS if, say, a
2373 ; semicolon precedes it.
2375 (while t ;; We go back one "token" each iteration of the loop.
2378 ;; Stop at the token after a comment.
2379 ((c-backward-single-comment) ; Also functions as backwards-ws.
2381 (throw 'done '(t . literal)))
2383 ;; If we've gone back over a LF, we might have moved into or out of
2384 ;; a preprocessor line.
2385 ((and (save-excursion
2387 (re-search-forward "\\(^\\|[^\\]\\)[\n\r]" last t))
2389 (< (point) macro-start)
2390 (c-beginning-of-macro)))
2392 ;; Return a car of NIL ONLY if we've hit the opening # of a macro.
2393 (throw 'done (cons (or (eq (point) here)
2397 ;; Have we found a virtual semicolon? If so, stop, unless the next
2398 ;; statement is where we started from.
2399 ((and (c-at-vsemi-p)
2401 (not (memq (char-after last) '(?\) ?})))) ; we've moved back from ) or }
2403 (throw 'done '(nil . nil)))
2405 ;; Hit the beginning of the buffer/region?
2409 (throw 'done '(nil . nil)))
2411 ;; Move back a character.
2412 ((progn (backward-char) nil))
2414 ;; Stop at "{" (unless it's a PIKE special brace list.)
2415 ((eq (char-after) ?\{)
2416 (if (and c-special-brace-lists
2417 (c-looking-at-special-brace-list))
2418 (skip-syntax-backward "w_") ; Speedup only.
2421 (throw 'done '(nil . nil))))
2423 ;; Have we reached the start of a macro? This always counts as
2424 ;; BOS. (N.B. I don't think (eq (point) here) can ever be true
2425 ;; here. FIXME!!! ACM 2004/3/29)
2426 ((and macro-start (eq (point) macro-start))
2427 (throw 'done (cons (eq (point) here) 'macro-boundary)))
2429 ;; Stop at token just after "}" or ";".
2430 ((looking-at "[;}]")
2431 ;; If we've gone back over ;, {, or }, we're done.
2432 (if (or (= here last)
2433 (memq (char-after last) '(?\) ?}))) ; we've moved back from ) or }
2434 (if (and (eq (char-before) ?}) ; If };, treat them as a unit.
2435 (eq (char-after) ?\;))
2437 (goto-char last) ; To the statement starting after the ; or }.
2438 (throw 'done '(nil . nil))))
2440 ;; Stop at the token after a string.
2441 ((looking-at c-string-limit-regexp) ; Just gone back over a string terminator?
2443 (throw 'done '(t . literal)))
2445 ;; Nothing special: go back word characters.
2446 (t (skip-syntax-backward "w_")) ; Speedup only.
2449 (defun c-forward-over-illiterals (macro-end allow-early-stop)
2450 ;; Move forwards over code, stopping before reaching EOB or a literal
2451 ;; (i.e. a comment/string) or the boundary of a preprocessor statement or
2452 ;; the "end of a statement". MACRO-END is the position of the EOL/EOB which
2453 ;; terminates the current preprocessor directive, or NIL if we're not in
2456 ;; ALLOW-EARLY-STOP is non-nil if it is permissible to return without moving
2457 ;; forward at all, should we encounter a `{'. This is an ugly kludge, but
2458 ;; seems unavoidable. Depending on the context this function is called
2459 ;; from, we _sometimes_ need to stop there. Currently (2004/4/3),
2460 ;; ALLOW-EARLY-STOP is applied only to open braces, not to virtual
2461 ;; semicolons, or anything else.
2463 ;; Return a cons (A.B), where
2464 ;; A is NIL if we moved forward to an EOS, or stay at one (when
2465 ;; ALLOW-EARLY-STOP is set), T otherwise (we hit a literal).
2466 ;; B is 'MACRO-BOUNDARY if we are about to cross the boundary out of or
2467 ;; into a macro, otherwise 'LITERAL if we've hit a literal, otherwise NIL
2469 ;; Point is left either after the end-of-statement, or at the last non-ws
2470 ;; code before encountering the literal, or the # of the preprocessor
2471 ;; statement, or at EOB [or just after last non-WS stuff??].
2473 ;; As a clarification of "after the end-of-statement", if a comment or
2474 ;; whitespace follows a completed AWK statement, that statement is treated
2475 ;; as ending just after the last non-ws character before the comment.
2477 ;; Note that this function moves within either preprocessor commands
2478 ;; (macros) or normal code, but not both within the same invocation.
2480 ;; Stop before `{', `}', and `#' when it's at boi on a line, but on the
2481 ;; other side of the syntactic ws, and after `;', `}' and `};'. Only
2482 ;; stop before `{' if at top level or inside braces, though. Move by
2483 ;; sexps and move into parens. Also stop at eol of lines with `#' at
2486 ;; This function might do hidden buffer changes.
2487 (let ((here (point))
2490 (while t ;; We go one "token" forward each time round this loop.
2493 ;; If we've moved forward to a virtual semicolon, we're done.
2494 (if (and (> last here) ; Should we check ALLOW-EARLY-STOP, here? 2004/4/3
2496 (throw 'done '(nil . nil)))
2500 ;; Gone past the end of a macro?
2501 ((and macro-end (> (point) macro-end))
2503 (throw 'done (cons (eq (point) here) 'macro-boundary)))
2505 ;; About to hit a comment?
2506 ((save-excursion (c-forward-single-comment))
2508 (throw 'done '(t . literal)))
2514 (throw 'done '(nil . nil)))
2516 ;; If we encounter a '{', stop just after the previous token.
2517 ((and (eq (char-after) ?{)
2518 (not (and c-special-brace-lists
2519 (c-looking-at-special-brace-list)))
2520 (or allow-early-stop (/= here last))
2521 (save-excursion ; Is this a check that we're NOT at top level?
2522 ;;;; NO! This seems to check that (i) EITHER we're at the top level; OR (ii) The next enclosing
2523 ;;;; level of bracketing is a '{'. HMM. Doesn't seem to make sense.
2524 ;;;; 2003/8/8 This might have something to do with the GCC extension "Statement Expressions", e.g.
2525 ;;;; while ({stmt1 ; stmt2 ; exp ;}). This form excludes such Statement Expressions.
2526 (or (not (c-safe (up-list -1) t))
2527 (= (char-after) ?{))))
2529 (throw 'done '(nil . nil)))
2531 ;; End of a PIKE special brace list? If so, step over it and continue.
2532 ((and c-special-brace-lists
2533 (eq (char-after) ?})
2535 (and (c-safe (up-list -1) t)
2536 (c-looking-at-special-brace-list))))
2538 (skip-syntax-forward "w_")) ; Speedup only.
2540 ;; Have we got a '}' after having moved? If so, stop after the
2542 ((and (eq (char-after) ?})
2545 (throw 'done '(nil . nil)))
2547 ;; Stop if we encounter a preprocessor line. Continue if we
2549 ((and c-opt-cpp-prefix
2551 (eq (char-after) ?#)
2552 (= (point) (c-point 'boi)))
2553 (if (= (point) here) ; Not a macro, therefore naked #.
2555 (throw 'done '(t . macro-boundary))))
2557 ;; Stop after a ';', '}', or "};"
2558 ((looking-at ";\\|};?")
2559 (goto-char (match-end 0))
2560 (throw 'done '(nil . nil)))
2562 ;; Found a string (this subsumes AWK regexps)?
2563 ((looking-at c-string-limit-regexp)
2565 (throw 'done '(t . literal)))
2568 (forward-char) ; Can't fail - we checked (eobp) earlier on.
2569 (skip-syntax-forward "w_") ; Speedup only.
2570 (when (and macro-end (> (point) macro-end))
2572 (throw 'done (cons (eq (point) here) 'macro-boundary))))
2575 (defun c-one-line-string-p (range)
2576 ;; Is the literal defined by RANGE a string contained in a single line?
2578 ;; This function might do hidden buffer changes.
2580 (goto-char (car range))
2581 (and (looking-at c-string-limit-regexp)
2582 (progn (skip-chars-forward "^\n" (cdr range))
2583 (eq (point) (cdr range))))))
2585 (defun c-beginning-of-statement (&optional count lim sentence-flag)
2586 "Go to the beginning of the innermost C statement.
2587 With prefix arg, go back N - 1 statements. If already at the
2588 beginning of a statement then go to the beginning of the closest
2589 preceding one, moving into nested blocks if necessary (use
2590 \\[backward-sexp] to skip over a block). If within or next to a
2591 comment or multiline string, move by sentences instead of statements.
2593 When called from a program, this function takes 3 optional args: the
2594 repetition count, a buffer position limit which is the farthest back
2595 to search for the syntactic context, and a flag saying whether to do
2596 sentence motion in or near comments and multiline strings.
2598 Note that for use in programs, `c-beginning-of-statement-1' is
2599 usually better. It has much better defined semantics than this one,
2600 which is intended for interactive use, and might therefore change to
2601 be more \"DWIM:ey\"."
2602 (interactive (list (prefix-numeric-value current-prefix-arg)
2605 (c-end-of-statement (- count) lim sentence-flag)
2606 (c-save-buffer-state
2607 ((count (or count 1))
2608 last ; start point for going back ONE chunk. Updated each chunk movement.
2610 (save-excursion (and (not (bobp)) (c-beginning-of-macro) (point))))
2611 res ; result from sub-function call
2612 not-bos ; "not beginning-of-statement"
2613 (range (c-collect-line-comments (c-literal-limits lim)))) ; (start.end) of current literal or NIL
2615 ;; Go back one statement at each iteration of the following loop.
2616 (while (and (/= count 0)
2617 (or (not lim) (> (point) lim)))
2618 ;; Go back one "chunk" each time round the following loop, stopping
2619 ;; when we reach a statement boundary, etc.
2622 (cond ; Each arm of this cond returns NIL on reaching a desired
2623 ; statement boundary, non-NIL otherwise.
2628 (range ; point is within or approaching a literal.
2630 ;; Single line string or sentence-flag is null => skip the
2632 ((or (null sentence-flag)
2633 (c-one-line-string-p range))
2634 (goto-char (car range))
2635 (setq range (c-ascertain-preceding-literal))
2636 ;; N.B. The following is essentially testing for an AWK regexp
2638 ;; Was the previous non-ws thing an end of statement?
2641 (c-backward-comments)
2642 (c-backward-syntactic-ws))
2643 (not (or (bobp) (c-after-statement-terminator-p)))))
2645 ;; Comment inside a statement or a multi-line string.
2646 (t (when (setq res ; returns non-nil when we go out of the literal
2647 (if (eq (c-literal-type range) 'string)
2648 (c-beginning-of-sentence-in-string range)
2649 (c-beginning-of-sentence-in-comment range)))
2650 (setq range (c-ascertain-preceding-literal)))
2653 ;; Non-literal code.
2654 (t (setq res (c-back-over-illiterals macro-fence))
2655 (setq not-bos ; "not reached beginning-of-statement".
2656 (or (= (point) last)
2657 (memq (char-after) '(?\) ?\}))
2660 ;; We're at a tentative BOS. The next form goes
2661 ;; back over WS looking for an end of previous
2663 (not (save-excursion
2665 (c-backward-comments)
2666 (c-backward-syntactic-ws))
2667 (or (bobp) (c-after-statement-terminator-p)))))))
2668 ;; Are we about to move backwards into or out of a
2669 ;; preprocessor command? If so, locate its beginning.
2670 (when (eq (cdr res) 'macro-boundary)
2675 (progn (c-skip-ws-backward) (c-beginning-of-macro))
2677 ;; Are we about to move backwards into a literal?
2678 (when (memq (cdr res) '(macro-boundary literal))
2679 (setq range (c-ascertain-preceding-literal)))
2681 (setq last (point)))
2683 (if (/= count 0) (setq count (1- count))))
2684 (c-keep-region-active))))
2686 (defun c-end-of-statement (&optional count lim sentence-flag)
2687 "Go to the end of the innermost C statement.
2688 With prefix arg, go forward N - 1 statements. Move forward to the end
2689 of the next statement if already at end, and move into nested blocks
2690 \(use \\[forward-sexp] to skip over a block). If within or next to a
2691 comment or multiline string, move by sentences instead of statements.
2693 When called from a program, this function takes 3 optional args: the
2694 repetition count, a buffer position limit which is the farthest back
2695 to search for the syntactic context, and a flag saying whether to do
2696 sentence motion in or near comments and multiline strings."
2697 (interactive (list (prefix-numeric-value current-prefix-arg)
2699 (setq count (or count 1))
2700 (if (< count 0) (c-beginning-of-statement (- count) lim sentence-flag)
2702 (c-save-buffer-state
2703 (here ; start point for going forward ONE statement. Updated each statement.
2706 (and (not (eobp)) (c-beginning-of-macro)
2707 (progn (c-end-of-macro) (point)))))
2709 (range (c-collect-line-comments (c-literal-limits lim)))) ; (start.end) of current literal or NIL
2711 ;; Go back/forward one statement at each iteration of the following loop.
2712 (while (and (/= count 0)
2713 (or (not lim) (< (point) lim)))
2714 (setq here (point)) ; ONLY HERE is HERE updated
2716 ;; Go forward one "chunk" each time round the following loop, stopping
2717 ;; when we reach a statement boundary, etc.
2719 (cond ; Each arm of this cond returns NIL on reaching a desired
2720 ; statement boundary, non-NIL otherwise.
2725 (range ; point is within a literal.
2727 ;; sentence-flag is null => skip the entire literal.
2728 ;; or a Single line string.
2729 ((or (null sentence-flag)
2730 (c-one-line-string-p range))
2731 (goto-char (cdr range))
2732 (setq range (c-ascertain-following-literal))
2733 ;; Is there a virtual semicolon here (e.g. for AWK)?
2734 (not (c-at-vsemi-p)))
2736 ;; Comment or multi-line string.
2737 (t (when (setq res ; gets non-nil when we go out of the literal
2738 (if (eq (c-literal-type range) 'string)
2739 (c-end-of-sentence-in-string range)
2740 (c-end-of-sentence-in-comment range)))
2741 (setq range (c-ascertain-following-literal)))
2742 ;; If we've just come forward out of a literal, check for
2743 ;; vsemi. (N.B. AWK can't have a vsemi after a comment, but
2744 ;; some other language may do in the future)
2746 (not (c-at-vsemi-p))))))
2748 ;; Non-literal code.
2749 (t (setq res (c-forward-over-illiterals macro-fence
2751 ;; Are we about to move forward into or out of a
2752 ;; preprocessor command?
2753 (when (eq (cdr res) 'macro-boundary)
2760 (progn (c-skip-ws-forward)
2761 (c-beginning-of-macro))
2762 (progn (c-end-of-macro)
2765 (c-beginning-of-macro)
2766 (progn (c-end-of-macro) (point)))))))
2767 ;; Are we about to move forward into a literal?
2768 (when (memq (cdr res) '(macro-boundary literal))
2769 (setq range (c-ascertain-following-literal)))
2772 (if (/= count 0) (setq count (1- count))))
2773 (c-keep-region-active))))
2776 ;; set up electric character functions to work with pending-del,
2777 ;; (a.k.a. delsel) mode. All symbols get the t value except
2778 ;; the functions which delete, which gets 'supersede, and (from Emacs
2779 ;; 25) `c-electric-brace' and `c-electric-paren' get special handling
2780 ;; so as to work gracefully with `electric-pair-mode'.
2784 (put sym 'delete-selection t) ; for delsel (Emacs)
2785 (put sym 'pending-delete t))) ; for pending-del (XEmacs)
2789 c-electric-semi&comma
2795 (put sym 'delete-selection (if (fboundp 'delete-selection-uses-region-p)
2796 'delete-selection-uses-region-p
2798 (put sym 'pending-delete t)))
2801 (put 'c-electric-delete 'delete-selection 'supersede) ; delsel
2802 (put 'c-electric-delete 'pending-delete 'supersede) ; pending-del
2803 (put 'c-electric-backspace 'delete-selection 'supersede) ; delsel
2804 (put 'c-electric-backspace 'pending-delete 'supersede) ; pending-del
2805 (put 'c-electric-delete-forward 'delete-selection 'supersede) ; delsel
2806 (put 'c-electric-delete-forward 'pending-delete 'supersede) ; pending-del
2809 ;; Inserting/indenting comments
2810 (defun c-calc-comment-indent (entry)
2811 ;; This function might do hidden buffer changes.
2813 (setq entry (or (assq entry c-indent-comment-alist)
2814 (assq 'other c-indent-comment-alist)
2815 '(default . (column . nil)))))
2816 (let ((action (car (cdr entry)))
2817 (value (cdr (cdr entry)))
2818 (col (current-column)))
2819 (cond ((eq action 'space)
2821 ((eq action 'column)
2822 (unless value (setq value comment-column))
2824 ;; Do not pad with one space if we're at bol.
2826 (max (1+ col) value)))
2832 (let ((lim (c-literal-limits (c-point 'bol) t)))
2834 (goto-char (car lim))
2835 (when (looking-at "/[/*]") ; FIXME!!! Adapt for AWK! (ACM, 2005/11/18)
2836 ;; Found comment to align with.
2838 ;; Do not pad with one space if we're at bol.
2840 (max (1+ col) (current-column))))))))
2841 ;; Recurse to handle value as a new spec.
2842 (c-calc-comment-indent (cdr entry)))))))
2844 (defun c-comment-indent ()
2845 "Used by `indent-for-comment' to create and indent comments.
2846 See `c-indent-comment-alist' for a description."
2849 (c-save-buffer-state
2850 ((eot (let ((lim (c-literal-limits (c-point 'bol) t)))
2851 (or (when (consp lim)
2852 (goto-char (car lim))
2853 (when (looking-at "/[/*]")
2854 (skip-chars-backward " \t")
2857 (skip-chars-backward " \t")
2860 (cond ((looking-at "^/[/*]")
2862 ((progn (beginning-of-line)
2865 ((progn (back-to-indentation)
2866 (and (eq (char-after) ?})
2867 (eq (point) (1- eot))))
2869 ((and (looking-at "#[ \t]*\\(endif\\|else\\)")
2870 (eq (match-end 0) eot))
2875 (if (and (memq line-type '(anchored-comment empty-line))
2876 c-indent-comments-syntactically-p)
2877 (let ((c-syntactic-context (c-guess-basic-syntax)))
2878 ;; BOGOSITY ALERT: if we're looking at the eol, its
2879 ;; because indent-for-comment hasn't put the comment-start
2880 ;; in the buffer yet. this will screw up the syntactic
2881 ;; analysis so we kludge in the necessary info. Another
2882 ;; kludge is that if we're at the bol, then we really want
2883 ;; to ignore any anchoring as specified by
2884 ;; c-comment-only-line-offset since it doesn't apply here.
2886 (c-add-syntax 'comment-intro))
2887 (let ((c-comment-only-line-offset
2888 (if (consp c-comment-only-line-offset)
2889 c-comment-only-line-offset
2890 (cons c-comment-only-line-offset
2891 c-comment-only-line-offset))))
2892 (c-get-syntactic-indentation c-syntactic-context)))
2894 (c-calc-comment-indent line-type)))))
2897 ;; used by outline-minor-mode
2898 (defun c-outline-level ()
2899 (let (buffer-invisibility-spec);; This so that `current-column' DTRT
2900 ;; in otherwise-hidden text.
2902 (skip-chars-forward "\t ")
2906 ;; Movement by CPP conditionals.
2907 (defun c-up-conditional (count)
2908 "Move back to the containing preprocessor conditional, leaving mark behind.
2909 A prefix argument acts as a repeat count. With a negative argument,
2910 move forward to the end of the containing preprocessor conditional.
2912 \"#elif\" is treated like \"#else\" followed by \"#if\", so the
2913 function stops at them when going backward, but not when going
2916 (let ((new-point (c-scan-conditionals (- count) -1)))
2918 (goto-char new-point))
2919 (c-keep-region-active))
2921 (defun c-up-conditional-with-else (count)
2922 "Move back to the containing preprocessor conditional, including \"#else\".
2923 Just like `c-up-conditional', except it also stops at \"#else\"
2926 (let ((new-point (c-scan-conditionals (- count) -1 t)))
2928 (goto-char new-point))
2929 (c-keep-region-active))
2931 (defun c-down-conditional (count)
2932 "Move forward into the next preprocessor conditional, leaving mark behind.
2933 A prefix argument acts as a repeat count. With a negative argument,
2934 move backward into the previous preprocessor conditional.
2936 \"#elif\" is treated like \"#else\" followed by \"#if\", so the
2937 function stops at them when going forward, but not when going
2940 (let ((new-point (c-scan-conditionals count 1)))
2942 (goto-char new-point))
2943 (c-keep-region-active))
2945 (defun c-down-conditional-with-else (count)
2946 "Move forward into the next preprocessor conditional, including \"#else\".
2947 Just like `c-down-conditional', except it also stops at \"#else\"
2950 (let ((new-point (c-scan-conditionals count 1 t)))
2952 (goto-char new-point))
2953 (c-keep-region-active))
2955 (defun c-backward-conditional (count &optional target-depth with-else)
2956 "Move back across a preprocessor conditional, leaving mark behind.
2957 A prefix argument acts as a repeat count. With a negative argument,
2958 move forward across a preprocessor conditional.
2960 The optional arguments TARGET-DEPTH and WITH-ELSE are historical,
2961 and have the same meanings as in `c-scan-conditionals'. If you
2962 are calling c-forward-conditional from a program, you might want
2963 to call `c-scan-conditionals' directly instead."
2965 (let ((new-point (c-scan-conditionals (- count) target-depth with-else)))
2967 (goto-char new-point))
2968 (c-keep-region-active))
2970 (defun c-forward-conditional (count &optional target-depth with-else)
2971 "Move forward across a preprocessor conditional, leaving mark behind.
2972 A prefix argument acts as a repeat count. With a negative argument,
2973 move backward across a preprocessor conditional.
2975 If there aren't enough conditionals after \(or before) point, an
2978 \"#elif\" is treated like \"#else\" followed by \"#if\", except that
2979 the nesting level isn't changed when tracking subconditionals.
2981 The optional arguments TARGET-DEPTH and WITH-ELSE are historical,
2982 and have the same meanings as in `c-scan-conditionals'. If you
2983 are calling c-forward-conditional from a program, you might want
2984 to call `c-scan-conditionals' directly instead."
2986 (let ((new-point (c-scan-conditionals count target-depth with-else)))
2988 (goto-char new-point)))
2990 (defun c-scan-conditionals (count &optional target-depth with-else)
2991 "Scan forward across COUNT preprocessor conditionals.
2992 With a negative argument, scan backward across preprocessor
2993 conditionals. Return the end position. Point is not moved.
2995 If there aren't enough preprocessor conditionals, throw an error.
2997 \"#elif\" is treated like \"#else\" followed by \"#if\", except that
2998 the nesting level isn't changed when tracking subconditionals.
3000 The optional argument TARGET-DEPTH specifies the wanted nesting depth
3001 after each scan. E.g. if TARGET-DEPTH is -1, the end position will be
3002 outside the enclosing conditional. A non-integer non-nil TARGET-DEPTH
3005 If the optional argument WITH-ELSE is non-nil, \"#else\" directives
3006 are treated as conditional clause limits. Normally they are ignored."
3007 (let* ((forward (> count 0))
3008 (increment (if forward -1 1))
3009 (search-function (if forward 're-search-forward 're-search-backward))
3010 new case-fold-search)
3011 (unless (integerp target-depth)
3012 (setq target-depth (if target-depth -1 0)))
3016 ;; subdepth is the depth in "uninteresting" subtrees,
3017 ;; i.e. those that takes us farther from the target
3018 ;; depth instead of closer.
3022 ;; Find the "next" significant line in the proper direction.
3023 (while (and (not found)
3024 ;; Rather than searching for a # sign that
3025 ;; comes at the beginning of a line aside from
3026 ;; whitespace, search first for a string
3027 ;; starting with # sign. Then verify what
3028 ;; precedes it. This is faster on account of
3029 ;; the fastmap feature of the regexp matcher.
3030 (funcall search-function
3031 "#[ \t]*\\(if\\|elif\\|endif\\|else\\)"
3034 ;; Now verify it is really a preproc line.
3035 (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\|else\\)")
3036 (let (dchange (directive (match-string 1)))
3037 (cond ((string= directive "if")
3038 (setq dchange (- increment)))
3039 ((string= directive "endif")
3040 (setq dchange increment))
3042 ;; When we're not in an "uninteresting"
3043 ;; subtree, we might want to act on "elif"
3045 (if (cond (with-else
3046 ;; Always move toward the target depth.
3048 (if (> target-depth 0) 1 -1)))
3049 ((string= directive "elif")
3050 (setq dchange (- increment))))
3051 ;; Ignore the change if it'd take us
3052 ;; into an "uninteresting" subtree.
3053 (if (eq (> dchange 0) (<= target-depth 0))
3054 (setq dchange nil)))))
3056 (when (or (/= subdepth 0)
3057 (eq (> dchange 0) (<= target-depth 0)))
3058 (setq subdepth (+ subdepth dchange)))
3059 (setq depth (+ depth dchange))
3060 ;; If we are trying to move across, and we find an
3061 ;; end before we find a beginning, get an error.
3062 (if (and (< depth target-depth) (< dchange 0))
3064 "No following conditional at this level"
3065 "No previous conditional at this level"))))
3066 ;; When searching forward, start from next line so
3067 ;; that we don't find the same line again.
3068 (if forward (forward-line 1))
3069 ;; We found something if we've arrived at the
3071 (if (and dchange (= depth target-depth))
3072 (setq found (point))))
3074 (if forward (forward-line 1)))))
3076 (error "No containing preprocessor conditional"))
3077 (goto-char (setq new found)))
3078 (setq count (+ count increment))))
3079 (c-keep-region-active)
3083 ;; commands to indent lines, regions, defuns, and expressions
3084 (defun c-indent-command (&optional arg)
3085 "Indent current line as C code, and/or insert some whitespace.
3087 If `c-tab-always-indent' is t, always just indent the current line.
3088 If nil, indent the current line only if point is at the left margin or
3089 in the line's indentation; otherwise insert some whitespace[*]. If
3090 other than nil or t, then some whitespace[*] is inserted only within
3091 literals (comments and strings), but the line is always reindented.
3093 If `c-syntactic-indentation' is t, indentation is done according to
3094 the syntactic context. A numeric argument, regardless of its value,
3095 means indent rigidly all the lines of the expression starting after
3096 point so that this line becomes properly indented. The relative
3097 indentation among the lines of the expression is preserved.
3099 If `c-syntactic-indentation' is nil, the line is just indented one
3100 step according to `c-basic-offset'. In this mode, a numeric argument
3101 indents a number of such steps, positive or negative, and an empty
3102 prefix argument is equivalent to -1.
3104 [*] The amount and kind of whitespace inserted is controlled by the
3105 variable `c-insert-tab-function', which is called to do the actual
3106 insertion of whitespace. Normally the function in this variable
3107 just inserts a tab character, or the equivalent number of spaces,
3108 depending on the variable `indent-tabs-mode'."
3111 (let ((indent-function
3112 (if c-syntactic-indentation
3113 (symbol-function 'indent-according-to-mode)
3115 (let ((c-macro-start c-macro-start)
3116 (steps (if (equal arg '(4))
3118 (prefix-numeric-value arg))))
3119 (c-shift-line-indentation (* steps c-basic-offset))
3120 (when (and c-auto-align-backslashes
3123 (eq (char-before) ?\\))
3124 (c-query-and-set-macro-start))
3125 ;; Realign the line continuation backslash if inside a macro.
3126 (c-backslash-region (point) (point) nil t)))
3128 (if (and c-syntactic-indentation arg)
3129 ;; If c-syntactic-indentation and got arg, always indent this
3130 ;; line as C and shift remaining lines of expression the same
3132 (let ((shift-amt (save-excursion
3133 (back-to-indentation)
3137 (setq shift-amt (- (save-excursion
3138 (back-to-indentation)
3142 (if (eq c-tab-always-indent t)
3143 (beginning-of-line)) ; FIXME!!! What is this here for? ACM 2005/10/31
3151 (indent-code-rigidly beg end shift-amt "#")))
3152 ;; Else use c-tab-always-indent to determine behavior.
3154 ;; CASE 1: indent when at column zero or in line's indentation,
3155 ;; otherwise insert a tab
3156 ((not c-tab-always-indent)
3158 (skip-chars-backward " \t")
3160 (funcall c-insert-tab-function)
3161 (funcall indent-function)))
3162 ;; CASE 2: just indent the line
3163 ((eq c-tab-always-indent t)
3164 (funcall indent-function))
3165 ;; CASE 3: if in a literal, insert a tab, but always indent the
3168 (if (c-save-buffer-state () (c-in-literal))
3169 (funcall c-insert-tab-function))
3170 (funcall indent-function)
3173 (defun c-indent-exp (&optional shutup-p)
3174 "Indent each line in the balanced expression following point syntactically.
3175 If optional SHUTUP-P is non-nil, no errors are signaled if no
3176 balanced expression is found."
3178 (let ((here (point-marker))
3180 (set-marker-insertion-type here t)
3182 (let ((start (save-restriction
3183 ;; Find the closest following open paren that
3184 ;; ends on another line.
3185 (narrow-to-region (point-min) (c-point 'eol))
3186 (let (beg (end (point)))
3187 (while (and (setq beg (c-down-list-forward end))
3188 (setq end (c-up-list-forward beg))))
3190 (eq (char-syntax (char-before beg)) ?\()
3195 (error "Cannot find start of balanced expression to indent"))
3197 (setq end (c-safe (scan-sexps (point) 1)))
3200 (error "Cannot find end of balanced expression to indent"))
3203 (c-indent-region (point) end)))))
3205 (set-marker here nil))))
3207 (defun c-indent-defun ()
3208 "Indent the current top-level declaration or macro syntactically.
3209 In the macro case this also has the effect of realigning any line
3210 continuation backslashes, unless `c-auto-align-backslashes' is nil."
3212 (let ((here (point-marker)) decl-limits case-fold-search)
3215 (c-save-buffer-state nil
3216 ;; We try to be line oriented, unless there are several
3217 ;; declarations on the same line.
3218 (if (looking-at c-syntactic-eol)
3219 (c-backward-token-2 1 nil (c-point 'bol))
3220 (c-forward-token-2 0 nil (c-point 'eol)))
3221 (setq decl-limits (c-declaration-limits nil)))
3223 (c-indent-region (car decl-limits)
3224 (cdr decl-limits))))
3226 (set-marker here nil))))
3228 (defun c-indent-region (start end &optional quiet)
3229 "Indent syntactically every line whose first char is between START
3230 and END inclusive. If the optional argument QUIET is non-nil then no
3231 syntactic errors are reported, even if `c-report-syntactic-errors' is
3235 (skip-chars-backward " \t\n\r\f\v")
3238 ;; Advance to first nonblank line.
3240 (skip-chars-forward " \t\n\r\f\v")
3241 (setq start (point))
3243 (setq c-parsing-error
3244 (or (let ((endmark (copy-marker end))
3245 (c-parsing-error nil)
3246 ;; shut up any echo msgs on indiv lines
3247 (c-echo-syntactic-information-p nil)
3248 (ml-macro-start ; Start pos of multi-line macro.
3249 (and (c-save-buffer-state ()
3250 (save-excursion (c-beginning-of-macro)))
3251 (eq (char-before (c-point 'eol)) ?\\)
3253 (c-fix-backslashes nil)
3257 (c-progress-init start end 'c-indent-region)
3259 (while (and (bolp) ;; One line each time round the loop.
3261 (< (point) endmark))
3265 (unless (or (looking-at "\\s *$")
3266 (and ml-macro-start (looking-at "\\s *\\\\$")))
3267 ;; Get syntax and indent.
3268 (c-save-buffer-state nil
3269 (setq syntax (c-guess-basic-syntax)))
3270 (c-indent-line syntax t t))
3273 ;; End of current multi-line macro?
3274 (when (and c-auto-align-backslashes
3275 (not (eq (char-before (c-point 'eol)) ?\\)))
3276 ;; Fixup macro backslashes.
3277 (c-backslash-region ml-macro-start (c-point 'bonl) nil)
3278 (setq ml-macro-start nil))
3279 ;; New multi-line macro?
3280 (if (and (assq 'cpp-macro syntax)
3281 (eq (char-before (c-point 'eol)) ?\\))
3282 (setq ml-macro-start (point))))
3286 (if (and ml-macro-start c-auto-align-backslashes)
3287 (c-backslash-region ml-macro-start (c-point 'bopl) nil t)))
3288 (set-marker endmark nil)
3289 (c-progress-fini 'c-indent-region))
3290 (c-echo-parsing-error quiet))
3293 (defun c-fn-region-is-active-p ()
3294 ;; Function version of the macro for use in places that aren't
3295 ;; compiled, e.g. in the menus.
3296 (c-region-is-active-p))
3298 (defun c-indent-line-or-region ()
3299 "When the region is active, indent it syntactically. Otherwise
3300 indent the current line syntactically."
3301 ;; Emacs has a variable called mark-active, XEmacs uses region-active-p
3303 (if (c-region-is-active-p)
3304 (c-indent-region (region-beginning) (region-end))
3308 ;; for progress reporting
3309 (defvar c-progress-info nil)
3311 (defun c-progress-init (start end context)
3314 ((not c-progress-interval))
3315 ;; Start the progress update messages. If this Emacs doesn't have
3316 ;; a built-in timer, just be dumb about it.
3317 ((not (fboundp 'current-time))
3318 (message "Indenting region... (this may take a while)"))
3319 ;; If progress has already been initialized, do nothing. otherwise
3320 ;; initialize the counter with a vector of:
3321 ;; [start end lastsec context]
3323 (t (setq c-progress-info (vector start
3327 (nth 1 (current-time))
3329 (message "Indenting region..."))
3332 (defun c-progress-update ()
3333 (if (not (and c-progress-info c-progress-interval))
3335 (let ((now (nth 1 (current-time)))
3336 (start (aref c-progress-info 0))
3337 (end (aref c-progress-info 1))
3338 (lastsecs (aref c-progress-info 2)))
3339 ;; should we update? currently, update happens every 2 seconds,
3340 ;; what's the right value?
3341 (if (< c-progress-interval (- now lastsecs))
3343 (message "Indenting region... (%d%% complete)"
3344 (/ (* 100 (- (point) start)) (- end start)))
3345 (aset c-progress-info 2 now)))
3348 (defun c-progress-fini (context)
3349 (if (not c-progress-interval)
3351 (if (or (eq context (aref c-progress-info 3))
3354 (set-marker (aref c-progress-info 1) nil)
3355 (setq c-progress-info nil)
3356 (message "Indenting region... done")))))
3360 ;;; This page handles insertion and removal of backslashes for C macros.
3362 (defun c-backslash-region (from to delete-flag &optional line-mode)
3363 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3364 With no argument, inserts backslashes and aligns existing backslashes.
3365 With an argument, deletes the backslashes. The backslash alignment is
3366 done according to the settings in `c-backslash-column',
3367 `c-backslash-max-column' and `c-auto-align-backslashes'.
3369 This function does not modify blank lines at the start of the region.
3370 If the region ends at the start of a line and the macro doesn't
3371 continue below it, the backslash (if any) at the end of the previous
3374 You can put the region around an entire macro definition and use this
3375 command to conveniently insert and align the necessary backslashes."
3376 (interactive "*r\nP")
3377 (let ((endmark (make-marker))
3378 ;; Keep the backslash trimming functions from changing the
3379 ;; whitespace around point, since in this case it's only the
3380 ;; position of point that tells the indentation of the line.
3381 (point-pos (if (save-excursion
3382 (skip-chars-backward " \t")
3383 (and (bolp) (looking-at "[ \t]*\\\\?$")))
3386 column longest-line-col bs-col-after-end)
3389 (if (and (not line-mode) (bobp))
3390 ;; Nothing to do if to is at bob, since we should back up
3391 ;; and there's no line to back up to.
3393 (when (and (not line-mode) (bolp))
3394 ;; Do not back up the to line if line-mode is set, to make
3395 ;; e.g. c-newline-and-indent consistent regardless whether
3396 ;; the (newline) call leaves point at bol or not.
3401 (set-marker endmark (point))
3403 (c-delete-backslashes-forward endmark point-pos))
3404 ;; Set bs-col-after-end to the column of any backslash
3405 ;; following the region, or nil if there is none.
3406 (setq bs-col-after-end
3407 (and (progn (end-of-line)
3408 (eq (char-before) ?\\))
3409 (= (forward-line 1) 0)
3410 (progn (end-of-line)
3411 (eq (char-before) ?\\))
3412 (1- (current-column))))
3414 ;; Back up the to line if line-mode is set, since the line
3415 ;; after the newly inserted line break should not be
3416 ;; touched in c-newline-and-indent.
3417 (setq to (max from (or (c-safe (c-point 'eopl)) from)))
3418 (unless bs-col-after-end
3419 ;; Set bs-col-after-end to non-nil in any case, since we
3420 ;; do not want to delete the backslash at the last line.
3421 (setq bs-col-after-end t)))
3423 (not c-auto-align-backslashes))
3425 ;; Compute the smallest column number past the ends of all
3427 (setq longest-line-col 0)
3429 (if bs-col-after-end
3430 ;; Include one more line in the max column
3431 ;; calculation, since the to line will be backslashed
3435 (while (and (>= (point) from)
3437 (if (eq (char-before) ?\\)
3439 (skip-chars-backward " \t")
3440 (setq longest-line-col (max longest-line-col
3441 (1+ (current-column))))
3445 ;; Try to align with surrounding backslashes.
3448 (if (and (not (bobp))
3449 (progn (backward-char)
3450 (eq (char-before) ?\\)))
3452 (setq column (1- (current-column)))
3453 (if (numberp bs-col-after-end)
3454 ;; Both a preceding and a following backslash.
3455 ;; Choose the greatest of them.
3456 (setq column (max column bs-col-after-end)))
3458 ;; No preceding backslash. Try to align with one
3459 ;; following the region. Disregard the backslash at the
3460 ;; to line since it's likely to be bogus (e.g. when
3461 ;; called from c-newline-and-indent).
3462 (if (numberp bs-col-after-end)
3463 (setq column bs-col-after-end))
3464 ;; Don't modify blank lines at start of region.
3466 (while (and (< (point) to) (bolp) (eolp))
3468 (if (and column (< column longest-line-col))
3469 ;; Don't try to align with surrounding backslashes if
3470 ;; any line is too long.
3473 ;; Impose minimum limit and tab width alignment only if
3474 ;; we can't align with surrounding backslashes.
3475 (if (> (% longest-line-col tab-width) 0)
3476 (setq longest-line-col
3477 (* (/ (+ longest-line-col tab-width -1)
3480 (setq column (max c-backslash-column
3482 ;; Always impose maximum limit.
3483 (setq column (min column c-backslash-max-column)))
3484 (if bs-col-after-end
3485 ;; Add backslashes on all lines if the macro continues
3486 ;; after the to line.
3488 (set-marker endmark to)
3489 (c-append-backslashes-forward endmark column point-pos))
3490 ;; Add backslashes on all lines except the last, and
3491 ;; remove any on the last line.
3496 (set-marker endmark (1- (point)))))
3498 (c-append-backslashes-forward endmark column point-pos)
3499 ;; The function above leaves point on the line
3500 ;; following endmark.
3501 (set-marker endmark (point)))
3502 (set-marker endmark to))
3503 (c-delete-backslashes-forward endmark point-pos)))))
3504 (set-marker endmark nil)
3505 (if (markerp point-pos)
3506 (set-marker point-pos nil))))
3508 (defun c-append-backslashes-forward (to-mark column point-pos)
3509 (let ((state (parse-partial-sexp (c-point 'bol) (point))))
3513 (<= (point) to-mark)
3515 (let ((start (point)) (inserted nil) end col)
3517 (unless (eq (char-before) ?\\)
3520 (setq state (parse-partial-sexp
3521 start (point) nil nil state))
3523 (setq col (current-column))
3525 ;; Avoid unnecessary changes of the buffer.
3526 (cond ((and (not inserted) (nth 3 state))
3527 ;; Don't realign backslashes in string literals
3528 ;; since that would change them.
3535 (skip-chars-backward
3536 " \t" (if (>= (point) point-pos) point-pos))
3540 ((and (= col column)
3541 (memq (char-before) '(?\ ?\t))))
3545 (or (/= (skip-chars-backward
3546 " \t" (if (>= (point) point-pos) point-pos))
3548 (/= (char-after) ?\ )))
3549 (delete-region (point) end)
3550 (indent-to column 1)))
3552 (zerop (forward-line 1)))
3553 (bolp))) ; forward-line has funny behavior at eob.
3555 ;; Make sure there are backslashes with at least one space in
3559 (<= (point) to-mark)
3561 (let ((start (point)))
3563 (setq state (parse-partial-sexp
3564 start (point) nil nil state))
3566 (if (eq (char-before) ?\\)
3567 (unless (nth 3 state)
3569 (unless (and (memq (char-before) '(?\ ?\t))
3570 (/= (point) point-pos))
3573 (if (and (memq (char-before) '(?\ ?\t))
3574 (/= (point) point-pos))
3578 (zerop (forward-line 1)))
3579 (bolp)))))) ; forward-line has funny behavior at eob.
3581 (defun c-delete-backslashes-forward (to-mark point-pos)
3583 (and (<= (point) to-mark)
3586 (if (eq (char-before) ?\\)
3589 (progn (backward-char)
3590 (skip-chars-backward " \t" (if (>= (point) point-pos)
3593 (zerop (forward-line 1)))
3594 (bolp)))) ; forward-line has funny behavior at eob.
3598 ;;; Line breaking and paragraph filling.
3600 (defvar c-auto-fill-prefix t)
3601 (defvar c-lit-limits nil)
3602 (defvar c-lit-type nil)
3604 ;; The filling code is based on a simple theory; leave the intricacies
3605 ;; of the text handling to the currently active mode for that
3606 ;; (e.g. adaptive-fill-mode or filladapt-mode) and do as little as
3607 ;; possible to make them work correctly wrt the comment and string
3608 ;; separators, one-line paragraphs etc. Unfortunately, when it comes
3609 ;; to it, there's quite a lot of special cases to handle which makes
3610 ;; the code anything but simple. The intention is that it will work
3611 ;; with any well-written text filling package that preserves a fill
3614 ;; We temporarily mask comment starters and enders as necessary for
3615 ;; the filling code to do its job on a seemingly normal text block.
3616 ;; We do _not_ mask the fill prefix, so it's up to the filling code to
3617 ;; preserve it correctly (especially important when filling C++ style
3618 ;; line comments). By default, we set up and use adaptive-fill-mode,
3619 ;; which is standard in all supported Emacs flavors.
3621 (defun c-guess-fill-prefix (lit-limits lit-type)
3622 ;; Determine the appropriate comment fill prefix for a block or line
3623 ;; comment. Return a cons of the prefix string and the column where
3624 ;; it ends. If fill-prefix is set, it'll override. Note that this
3625 ;; function also uses the value of point in some heuristics.
3627 ;; This function might do hidden buffer changes.
3629 (let* ((here (point))
3630 (prefix-regexp (concat "[ \t]*\\("
3631 c-current-comment-prefix
3633 (comment-start-regexp (if (eq lit-type 'c++)
3635 comment-start-skip))
3636 prefix-line comment-prefix res comment-text-end)
3640 (setq res (cons fill-prefix
3641 ;; Ugly way of getting the column after the fill
3642 ;; prefix; it'd be nice with a current-column
3643 ;; that works on strings..
3644 (let ((start (point)))
3647 (insert-and-inherit "\n" fill-prefix)
3649 (delete-region start (point)))))))
3653 ;; Set fallback for comment-prefix if none is found.
3654 (setq comment-prefix "// "
3655 comment-text-end (cdr lit-limits))
3658 (if (> (point) (car lit-limits))
3659 ;; The current line is not the comment starter, so the
3660 ;; comment has more than one line, and it can therefore be
3661 ;; used to find the comment fill prefix.
3662 (setq prefix-line (point))
3664 (goto-char (car lit-limits))
3665 (if (and (= (forward-line 1) 0)
3666 (< (point) (cdr lit-limits)))
3667 ;; The line after the comment starter is inside the
3668 ;; comment, so we can use it.
3669 (setq prefix-line (point))
3671 ;; The comment is only one line. Take the comment prefix
3672 ;; from it and keep the indentation.
3673 (goto-char (car lit-limits))
3674 (if (looking-at prefix-regexp)
3675 (goto-char (match-end 0))
3677 (skip-chars-forward " \t"))
3680 (if (eq (c-point 'boi) (car lit-limits))
3681 ;; There is only whitespace before the comment
3682 ;; starter; take the prefix straight from this line.
3683 (setq str (buffer-substring-no-properties
3684 (c-point 'bol) (point))
3685 col (current-column))
3687 ;; There is code before the comment starter, so we
3688 ;; have to temporarily insert and indent a new line to
3689 ;; get the right space/tab mix in the indentation.
3690 (let ((prefix-len (- (point) (car lit-limits)))
3694 (goto-char (car lit-limits))
3695 (indent-to (prog1 (current-column)
3698 (forward-char prefix-len)
3699 (setq str (buffer-substring-no-properties
3700 (c-point 'bol) (point))
3701 col (current-column)))
3702 (delete-region (car lit-limits) tmp))))
3705 (if (or (string-match "\\s \\'" str) (not (eolp)))
3707 ;; The prefix ends the line with no whitespace
3708 ;; after it. Default to a single space.
3709 (cons (concat str " ") (1+ col))))
3713 (setq comment-text-end
3715 (goto-char (- (cdr lit-limits) 2))
3716 (if (looking-at "\\*/") (point) (cdr lit-limits))))
3720 (if (and (> (point) (car lit-limits))
3721 (not (and (looking-at "[ \t]*\\*/")
3722 (eq (cdr lit-limits) (match-end 0)))))
3723 ;; The current line is not the comment starter and
3724 ;; contains more than just the ender, so it's good enough
3725 ;; to be used for the comment fill prefix.
3726 (setq prefix-line (point))
3727 (goto-char (car lit-limits))
3729 (cond ((or (/= (forward-line 1) 0)
3730 (>= (point) (cdr lit-limits))
3731 (and (looking-at "[ \t]*\\*/")
3732 (eq (cdr lit-limits) (match-end 0)))
3733 (and (looking-at prefix-regexp)
3734 (<= (1- (cdr lit-limits)) (match-end 0))))
3735 ;; The comment is either one line or the next line contains
3736 ;; just the comment ender. In this case we have no
3737 ;; information about a suitable comment prefix, so we resort
3738 ;; to c-block-comment-prefix.
3739 (setq comment-prefix (or c-block-comment-prefix "")))
3742 ;; The point was on the comment opener line, so we might want
3743 ;; to treat this as a not yet closed comment.
3745 (if (and (match-beginning 1)
3746 (/= (match-beginning 1) (match-end 1)))
3747 ;; Above `prefix-regexp' matched a nonempty prefix on the
3748 ;; second line, so let's use it. Normally it should do
3749 ;; to set `prefix-line' and let the code below pick up
3750 ;; the whole prefix, but if there's no text after the
3751 ;; match then it will probably fall back to no prefix at
3752 ;; all if the comment isn't closed yet, so in that case
3753 ;; it's better to force use of the prefix matched now.
3754 (if (= (match-end 0) (c-point 'eol))
3755 (setq comment-prefix (match-string 1))
3756 (setq prefix-line (point)))
3758 ;; There's no nonempty prefix on the line after the
3759 ;; comment opener. If the line is empty, or if the
3760 ;; text on it has less or equal indentation than the
3761 ;; comment starter we assume it's an unclosed
3762 ;; comment starter, i.e. that
3763 ;; `c-block-comment-prefix' should be used.
3764 ;; Otherwise we assume it's a closed comment where
3765 ;; the prefix really is the empty string.
3766 ;; E.g. this is an unclosed comment:
3777 ;; (Looking for the presence of the comment closer
3778 ;; rarely works since it's probably the closer of
3779 ;; some comment further down when the comment
3780 ;; really is unclosed.)
3781 (if (<= (save-excursion (back-to-indentation)
3783 (save-excursion (goto-char (car lit-limits))
3785 (setq comment-prefix (or c-block-comment-prefix ""))
3786 (setq prefix-line (point)))))
3789 ;; Otherwise the line after the comment starter is good
3790 ;; enough to find the prefix in.
3791 (setq prefix-line (point))))
3793 (when comment-prefix
3794 ;; Haven't got the comment prefix on any real line that we
3795 ;; can take it from, so we have to temporarily insert
3796 ;; `comment-prefix' on a line and indent it to find the
3797 ;; correct column and the correct mix of tabs and spaces.
3799 (let (tmp-pre tmp-post)
3803 (goto-char (car lit-limits))
3804 (if (looking-at comment-start-regexp)
3805 (goto-char (min (match-end 0)
3808 (skip-chars-forward " \t"))
3810 (when (eq (char-syntax (char-before)) ?\ )
3811 ;; If there's ws on the current line, we'll use it
3812 ;; instead of what's ending comment-prefix.
3813 (setq comment-prefix
3814 (concat (substring comment-prefix
3818 (buffer-substring-no-properties
3820 (skip-chars-backward " \t")
3824 (setq tmp-pre (point-marker))
3826 ;; We insert an extra non-whitespace character
3827 ;; before the line break and after comment-prefix in
3828 ;; case it's "" or ends with whitespace.
3829 (insert-and-inherit "x\n" comment-prefix "x")
3830 (setq tmp-post (point-marker))
3832 (indent-according-to-mode)
3834 (goto-char (1- tmp-post))
3835 (cons (buffer-substring-no-properties
3836 (c-point 'bol) (point))
3840 (delete-region tmp-pre tmp-post)
3841 (set-marker tmp-pre nil)
3842 (set-marker tmp-post nil))))))))))
3844 (or res ; Found a good prefix above.
3847 ;; prefix-line is the bol of a line on which we should try
3848 ;; to find the prefix.
3849 (let* (fb-string fb-endpos ; Contains any fallback prefix found.
3852 (when (and (looking-at prefix-regexp)
3853 (<= (match-end 0) comment-text-end))
3854 (unless (eq (match-end 0) (c-point 'eol))
3855 ;; The match is fine if there's text after it.
3856 (throw 'found (cons (buffer-substring-no-properties
3857 (match-beginning 0) (match-end 0))
3858 (progn (goto-char (match-end 0))
3859 (current-column)))))
3861 ;; This match is better than nothing, so let's
3862 ;; remember it in case nothing better is found
3864 (setq fb-string (buffer-substring-no-properties
3865 (match-beginning 0) (match-end 0))
3866 fb-endpos (match-end 0)))
3870 ;; Search for a line which has text after the prefix
3871 ;; so that we get the proper amount of whitespace
3872 ;; after it. We start with the current line, then
3873 ;; search backwards, then forwards.
3875 (goto-char prefix-line)
3876 (when (and (funcall test-line)
3877 (or (/= (match-end 1) (match-end 0))
3878 ;; The whitespace is sucked up by the
3879 ;; first [ \t]* glob if the prefix is empty.
3880 (and (= (match-beginning 1) (match-end 1))
3881 (/= (match-beginning 0) (match-end 0)))))
3882 ;; If the current line doesn't have text but do
3883 ;; have whitespace after the prefix, we'll use it.
3884 (throw 'found (cons fb-string
3885 (progn (goto-char fb-endpos)
3886 (current-column)))))
3888 (if (eq lit-type 'c++)
3889 ;; For line comments we can search up to and
3890 ;; including the first line.
3891 (while (and (zerop (forward-line -1))
3892 (>= (point) (car lit-limits)))
3893 (funcall test-line))
3894 ;; For block comments we must stop before the
3896 (while (and (zerop (forward-line -1))
3897 (> (point) (car lit-limits)))
3898 (funcall test-line)))
3900 (goto-char prefix-line)
3901 (while (and (zerop (forward-line 1))
3902 (< (point) (cdr lit-limits)))
3903 (funcall test-line))
3905 (goto-char prefix-line)
3909 ;; A good line wasn't found, but at least we have a
3910 ;; fallback that matches the comment prefix regexp.
3911 (cond ((or (string-match "\\s \\'" fb-string)
3913 (goto-char fb-endpos)
3915 ;; There are ws or text after the prefix, so
3917 (cons fb-string (current-column)))
3920 ;; Check if there's any whitespace padding
3921 ;; on the comment start line that we can
3922 ;; use after the prefix.
3923 (goto-char (car lit-limits))
3924 (if (looking-at comment-start-regexp)
3925 (goto-char (match-end 0))
3927 (skip-chars-forward " \t"))
3929 (eq (char-syntax (char-before)) ?\ )))
3931 (setq fb-string (buffer-substring-no-properties
3933 (skip-chars-backward " \t")
3936 (goto-char fb-endpos)
3937 (skip-chars-backward " \t")
3939 (let ((tmp (point)))
3940 ;; Got to mess in the buffer once again to
3941 ;; ensure the column gets correct. :P
3944 (insert-and-inherit fb-string)
3945 (cons (buffer-substring-no-properties
3949 (delete-region tmp (point)))))
3952 ;; Last resort: Just add a single space after
3954 (cons (concat fb-string " ")
3955 (progn (goto-char fb-endpos)
3956 (1+ (current-column)))))))
3958 ;; The line doesn't match the comment prefix regexp.
3960 ;; We have a fallback for line comments that we must use.
3961 (cons (concat (buffer-substring-no-properties
3962 prefix-line (c-point 'boi))
3964 (progn (back-to-indentation)
3965 (+ (current-column) (length comment-prefix))))
3967 ;; Assume we are dealing with a "free text" block
3968 ;; comment where the lines doesn't have any comment
3969 ;; prefix at all and we should just fill it as
3974 (defun c-mask-paragraph (fill-paragraph apply-outside-literal fun &rest args)
3975 ;; Calls FUN with ARGS ar arguments while the current paragraph is
3976 ;; masked to allow adaptive filling to work correctly. That
3977 ;; includes narrowing the buffer and, if point is inside a comment,
3978 ;; masking the comment starter and ender appropriately.
3980 ;; FILL-PARAGRAPH is non-nil if called for whole paragraph filling.
3981 ;; The position of point is then less significant when doing masking
3984 ;; If APPLY-OUTSIDE-LITERAL is nil then the function will be called
3985 ;; only if the point turns out to be inside a comment or a string.
3987 ;; Note that this function does not do any hidden buffer changes.
3990 ;; beg and end limit the region to narrow. end is a marker.
3992 ;; tmp-pre and tmp-post mark strings that are temporarily
3993 ;; inserted at the start and end of the region. tmp-pre is a
3994 ;; cons of the positions of the prepended string. tmp-post is
3995 ;; a marker pointing to the single character of the appended
3998 ;; If hang-ender-stuck isn't nil, the comment ender is
3999 ;; hanging. In that case it's set to the number of spaces
4000 ;; that should be between the text and the ender.
4002 ;; auto-fill-spaces is the exact sequence of whitespace between a
4003 ;; comment's last word and the comment ender, temporarily replaced
4004 ;; with 'x's before calling FUN when FILL-PARAGRAPH is nil.
4007 (c-lit-limits c-lit-limits)
4008 (c-lit-type c-lit-type))
4010 ;; Restore point on undo. It's necessary since we do a lot of
4011 ;; hidden inserts and deletes below that should be as transparent
4013 (if (and buffer-undo-list (not (eq buffer-undo-list t)))
4014 (setq buffer-undo-list (cons (point) buffer-undo-list)))
4016 ;; Determine the limits and type of the containing literal (if any):
4017 ;; C-LIT-LIMITS, C-LIT-TYPE; and the limits of the current paragraph:
4019 (c-save-buffer-state ()
4021 ;; Widen to catch comment limits correctly.
4023 (unless c-lit-limits
4024 (setq c-lit-limits (c-literal-limits nil fill-paragraph)))
4025 (setq c-lit-limits (c-collect-line-comments c-lit-limits))
4027 (setq c-lit-type (c-literal-type c-lit-limits))))
4030 (unless (c-safe (backward-char)
4034 (forward-paragraph))
4035 (setq end (point-marker)))
4037 (unless (c-safe (forward-char)
4038 (backward-paragraph)
4041 (backward-paragraph))
4042 (setq beg (point))))
4046 ;; For each of the possible types of text (string, C comment ...)
4047 ;; determine BEG and END, the region we will narrow to. If we're in
4048 ;; a literal, constrain BEG and END to the limits of this literal.
4050 ;; For some of these text types, particularly a block comment, we
4051 ;; may need to massage whitespace near literal delimiters, so that
4052 ;; these don't get filled inappropriately.
4055 ((eq c-lit-type 'c++) ; Line comment.
4057 ;; Limit to the comment or paragraph end, whichever
4059 (set-marker end (min end (cdr c-lit-limits)))
4061 (when (<= beg (car c-lit-limits))
4062 ;; The region includes the comment starter, so we must
4064 (goto-char (car c-lit-limits))
4065 (back-to-indentation)
4066 (if (eq (point) (car c-lit-limits))
4067 ;; Include the first line in the region.
4068 (setq beg (c-point 'bol))
4069 ;; The first line contains code before the
4070 ;; comment. We must fake a line that doesn't.
4073 (setq apply-outside-literal t))
4075 ((eq c-lit-type 'c) ; Block comment.
4077 (or (> end (cdr c-lit-limits))
4078 (and (= end (cdr c-lit-limits))
4079 (eq (char-before end) ?/)
4080 (eq (char-before (1- end)) ?*)
4082 (> (- (cdr c-lit-limits) (car c-lit-limits)) 3)))
4083 ;; There is a comment ender, and the region includes it. If
4084 ;; it's on its own line, it stays on its own line. If it's got
4085 ;; company on the line, it keeps (at least one word of) it.
4086 ;; "=====*/" counts as a comment ender here, but "===== */"
4087 ;; doesn't and "foo*/" doesn't.
4090 (goto-char (cdr c-lit-limits))
4092 ;; The following conjunct was added to avoid an
4093 ;; "Invalid search bound (wrong side of point)"
4094 ;; error in the subsequent re-search. Maybe
4095 ;; another fix would be needed (2007-12-08).
4096 ; (or (<= (- (cdr c-lit-limits) 2) (point))
4097 ; 2010-10-17 Construct removed.
4098 ; (or (< (- (cdr c-lit-limits) 2) (point))
4100 (search-forward-regexp
4101 (concat "\\=[ \t]*\\(" c-current-comment-prefix "\\)")
4102 (- (cdr c-lit-limits) 2) t)
4103 (not (search-forward-regexp
4105 (- (cdr c-lit-limits) 2) 'limit))
4106 ;; The comment ender IS on its own line. Exclude this
4107 ;; line from the filling.
4108 (set-marker end (c-point 'bol))));)
4110 ;; The comment ender is hanging. Replace all space between it
4111 ;; and the last word either by one or two 'x's (when
4112 ;; FILL-PARAGRAPH is non-nil), or a row of x's the same width
4113 ;; as the whitespace (when auto filling), and include it in
4114 ;; the region. We'll change them back to whitespace
4115 ;; afterwards. The effect of this is to glue the comment
4116 ;; ender to the last word in the comment during filling.
4117 (let* ((ender-start (save-excursion
4118 (goto-char (cdr c-lit-limits))
4119 (skip-syntax-backward "^w ")
4121 (ender-column (save-excursion
4122 (goto-char ender-start)
4124 (point-rel (- ender-start here))
4125 (sentence-ends-comment
4127 (goto-char ender-start)
4128 (and (search-backward-regexp
4129 (c-sentence-end) (c-point 'bol) t)
4130 (goto-char (match-end 0))
4131 (looking-at "[ \t]*")
4132 (= (match-end 0) ender-start))))
4136 ;; Insert a CR after the "*/", adjust END
4137 (goto-char (cdr c-lit-limits))
4138 (setq tmp-post (point-marker))
4140 (set-marker end (point))
4142 (forward-line -1) ; last line of the comment
4143 (if (and (looking-at (concat "[ \t]*\\(\\("
4144 c-current-comment-prefix
4146 (eq ender-start (match-end 0)))
4147 ;; The comment ender is prefixed by nothing but a
4148 ;; comment line prefix. IS THIS POSSIBLE? (ACM,
4149 ;; 2006/4/28). Remove it along with surrounding ws.
4150 (setq spaces (- (match-end 1) (match-end 2)))
4151 (goto-char ender-start))
4152 (skip-chars-backward " \t\r\n") ; Surely this can be
4153 ; " \t"? "*/" is NOT alone on the line (ACM, 2005/8/18)
4155 ;; What's being tested here? 2006/4/20. FIXME!!!
4156 (if (/= (point) ender-start)
4158 (if (<= here (point))
4159 ;; Don't adjust point below if it's
4160 ;; before the string we replace.
4161 (setq point-rel -1))
4162 ;; Keep one or two spaces between the
4163 ;; text and the ender, depending on how
4164 ;; many there are now.
4166 (setq spaces (- ender-column (current-column))))
4167 (setq auto-fill-spaces (c-delete-and-extract-region
4168 (point) ender-start))
4169 ;; paragraph filling condenses multiple spaces to
4170 ;; single or double spaces. auto-fill doesn't.
4175 (if (and sentence-ends-comment
4176 sentence-end-double-space)
4179 ;; Insert the filler first to keep marks right.
4180 (insert-char ?x spaces t)
4181 (setq hang-ender-stuck spaces)
4183 (and (>= point-rel 0)
4184 (- (point) (min point-rel spaces)))))
4185 (setq point-rel nil)))
4188 ;; Point was in the middle of the string we
4189 ;; replaced above, so put it back in the same
4190 ;; relative position, counting from the end.
4191 (goto-char point-rel)))
4194 (when (<= beg (car c-lit-limits))
4195 ;; The region includes the comment starter.
4197 (goto-char (car c-lit-limits))
4198 (if (looking-at (concat "\\(" comment-start-skip "\\)$"))
4199 ;; Begin with the next line.
4200 (setq beg (c-point 'bonl))
4201 ;; Fake the fill prefix in the first line.
4204 (setq apply-outside-literal t))
4206 ((eq c-lit-type 'string) ; String.
4208 (when (>= end (cdr c-lit-limits))
4209 (goto-char (1- (cdr c-lit-limits)))
4210 (setq tmp-post (point-marker))
4212 (set-marker end (point)))
4213 (when (<= beg (car c-lit-limits))
4214 (goto-char (1+ (car c-lit-limits)))
4215 (setq beg (if (looking-at "\\\\$")
4216 ;; Leave the start line if it's
4217 ;; nothing but an escaped newline.
4220 (setq apply-outside-literal t))
4222 ((eq c-lit-type 'pound) ; Macro
4223 ;; Narrow to the macro limits if they are nearer than the
4224 ;; paragraph limits. Don't know if this is necessary but
4225 ;; do it for completeness sake (doing auto filling at all
4226 ;; inside macros is bogus to begin with since the line
4227 ;; continuation backslashes aren't handled).
4229 (c-save-buffer-state ()
4230 (c-beginning-of-macro)
4237 (set-marker end (point))))))
4240 ;; Try to avoid comments and macros in the paragraph to
4241 ;; avoid that the adaptive fill mode gets the prefix from
4243 (c-save-buffer-state nil
4246 (c-forward-syntactic-ws end)
4250 (c-backward-syntactic-ws beg)
4252 (set-marker end (point))))))
4255 ;; Temporarily insert the fill prefix after the comment
4256 ;; starter so that the first line looks like any other
4257 ;; comment line in the narrowed region.
4258 (setq fill (c-save-buffer-state nil
4259 (c-guess-fill-prefix c-lit-limits c-lit-type)))
4260 (unless (string-match (concat "\\`[ \t]*\\("
4261 c-current-comment-prefix
4264 ;; Oops, the prefix doesn't match the comment prefix
4265 ;; regexp. This could produce very confusing
4266 ;; results with adaptive fill packages together with
4267 ;; the insert prefix magic below, since the prefix
4268 ;; often doesn't appear at all. So let's warn about
4271 Warning: Regexp from `c-comment-prefix-regexp' doesn't match the comment prefix %S"
4273 ;; Find the right spot on the line, break it, insert
4274 ;; the fill prefix and make sure we're back in the
4275 ;; same column by temporarily prefixing the first word
4276 ;; with a number of 'x'.
4278 (goto-char (car c-lit-limits))
4279 (if (looking-at (if (eq c-lit-type 'c++)
4280 c-current-comment-prefix
4281 comment-start-skip))
4282 (goto-char (match-end 0))
4284 (skip-chars-forward " \t"))
4285 (while (and (< (current-column) (cdr fill))
4288 (let ((col (current-column)))
4289 (setq beg (1+ (point))
4290 tmp-pre (list (point)))
4293 (insert-and-inherit "\n" (car fill))
4294 (insert-char ?x (- col (current-column)) t))
4295 (setcdr tmp-pre (point))))))
4297 (when apply-outside-literal
4298 ;; `apply-outside-literal' is always set to t here if
4299 ;; we're inside a literal.
4303 ;; Kludge: If the function that adapts the fill prefix
4304 ;; doesn't produce the required comment starter for
4305 ;; line comments, then force it by setting fill-prefix.
4306 (when (and (eq c-lit-type 'c++)
4307 ;; Kludge the kludge: filladapt-mode doesn't
4308 ;; have this problem, but it currently
4309 ;; doesn't override fill-context-prefix
4311 (not (and (boundp 'filladapt-mode)
4315 (or (fill-context-prefix beg end)
4317 (c-save-buffer-state nil
4318 (car (or fill (c-guess-fill-prefix
4319 c-lit-limits c-lit-type)))))))
4321 ;; Save the relative position of point if it's outside the
4322 ;; region we're going to narrow. Want to restore it in that
4323 ;; case, but otherwise it should be moved according to the
4325 (point-rel (cond ((< (point) beg) (- (point) beg))
4326 ((> (point) end) (- (point) end)))))
4328 ;; Preparations finally done! Now we can call the
4332 (narrow-to-region beg end)
4335 ;; Restore point if it was outside the region.
4337 (goto-char (+ beg point-rel))
4338 (goto-char (+ end point-rel))))))))
4340 (when (consp tmp-pre)
4341 (delete-region (car tmp-pre) (cdr tmp-pre)))
4345 (goto-char tmp-post)
4347 (when hang-ender-stuck
4348 ;; Preserve point even if it's in the middle of the string
4349 ;; we replace; save-excursion doesn't work in that case.
4351 (goto-char tmp-post)
4352 (skip-syntax-backward "^w ")
4353 (forward-char (- hang-ender-stuck))
4354 (if (or fill-paragraph (not auto-fill-spaces))
4355 (insert-char ?\ hang-ender-stuck t)
4356 (insert auto-fill-spaces)
4357 ;; (setq here (- here (- hang-ender-stuck (length auto-fill-spaces))))
4359 (delete-char hang-ender-stuck)
4361 (set-marker tmp-post nil))
4363 (set-marker end nil))))
4365 (defun c-fill-paragraph (&optional arg)
4366 "Like \\[fill-paragraph] but handles C and C++ style comments.
4367 If any of the current line is a comment or within a comment, fill the
4368 comment or the paragraph of it that point is in, preserving the
4369 comment indentation or line-starting decorations (see the
4370 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
4373 If point is inside multiline string literal, fill it. This currently
4374 does not respect escaped newlines, except for the special case when it
4375 is the very first thing in the string. The intended use for this rule
4376 is in situations like the following:
4378 char description[] = \"\\
4379 A very long description of something that you want to fill to make
4380 nicely formatted output.\"\;
4382 If point is in any other situation, i.e. in normal code, do nothing.
4384 Optional prefix ARG means justify paragraph as well."
4386 (let ((fill-paragraph-function
4387 ;; Avoid infinite recursion.
4388 (if (not (eq fill-paragraph-function 'c-fill-paragraph))
4389 fill-paragraph-function)))
4390 (c-mask-paragraph t nil 'fill-paragraph arg))
4391 ;; Always return t. This has the effect that if filling isn't done
4392 ;; above, it isn't done at all, and it's therefore effectively
4393 ;; disabled in normal code.
4396 (defun c-do-auto-fill ()
4397 ;; Do automatic filling if not inside a context where it should be
4399 (let ((c-auto-fill-prefix
4400 ;; The decision whether the line should be broken is actually
4401 ;; done in c-indent-new-comment-line, which do-auto-fill
4402 ;; calls to break lines. We just set this special variable
4403 ;; so that we'll know when we're called from there. It's
4404 ;; also used to detect whether fill-prefix is user set or
4405 ;; generated automatically by do-auto-fill.
4407 (c-mask-paragraph nil t 'do-auto-fill)))
4409 (defun c-indent-new-comment-line (&optional soft allow-auto-fill)
4410 "Break line at point and indent, continuing comment or macro if within one.
4411 If inside a comment and `comment-multi-line' is non-nil, the
4412 indentation and line prefix are preserved (see the
4413 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
4414 details). If inside a single line comment and `comment-multi-line' is
4415 nil, a new comment of the same type is started on the next line and
4416 indented as appropriate for comments. If inside a macro, a line
4417 continuation backslash is inserted and aligned as appropriate, and the
4418 new line is indented according to `c-syntactic-indentation'.
4420 If a fill prefix is specified, it overrides all the above."
4421 ;; allow-auto-fill is used from c-context-line-break to allow auto
4422 ;; filling to break the line more than once. Since this function is
4423 ;; used from auto-fill itself, that's normally disabled to avoid
4424 ;; unnecessary recursion.
4426 (let ((fill-prefix fill-prefix)
4429 (delete-horizontal-space)
4431 (insert-and-inherit ?\n)
4432 (newline (if allow-auto-fill nil 1)))))
4433 ;; Already know the literal type and limits when called from
4434 ;; c-context-line-break.
4435 (c-lit-limits c-lit-limits)
4436 (c-lit-type c-lit-type)
4437 (c-macro-start c-macro-start))
4439 (c-save-buffer-state ()
4440 (when (not (eq c-auto-fill-prefix t))
4441 ;; Called from do-auto-fill.
4442 (unless c-lit-limits
4443 (setq c-lit-limits (c-literal-limits nil nil t)))
4445 (setq c-lit-type (c-literal-type c-lit-limits)))
4446 (if (memq (cond ((c-query-and-set-macro-start) 'cpp)
4447 ((null c-lit-type) 'code)
4450 (setq fill-prefix t) ; Used as flag in the cond.
4451 (if (and (null c-auto-fill-prefix)
4453 (<= (c-point 'bol) (car c-lit-limits)))
4454 ;; The adaptive fill function has generated a prefix, but
4455 ;; we're on the first line in a block comment so it'll be
4456 ;; wrong. Ignore it to guess a better one below.
4457 (setq fill-prefix nil)
4458 (when (and (eq c-lit-type 'c++)
4459 (not (string-match (concat "\\`[ \t]*"
4460 c-line-comment-starter)
4461 (or fill-prefix ""))))
4462 ;; Kludge: If the function that adapted the fill prefix
4463 ;; doesn't produce the required comment starter for line
4464 ;; comments, then we ignore it.
4465 (setq fill-prefix nil)))
4468 (cond ((eq fill-prefix t)
4469 ;; A call from do-auto-fill which should be ignored.
4472 ;; A fill-prefix overrides anything.
4473 (funcall do-line-break)
4474 (insert-and-inherit fill-prefix))
4475 ((c-save-buffer-state ()
4476 (unless c-lit-limits
4477 (setq c-lit-limits (c-literal-limits)))
4479 (setq c-lit-type (c-literal-type c-lit-limits)))
4480 (memq c-lit-type '(c c++)))
4481 ;; Some sort of comment.
4482 (if (or comment-multi-line
4484 (goto-char (car c-lit-limits))
4486 (< (point) (cdr c-lit-limits))))
4487 ;; Inside a comment that should be continued.
4488 (let ((fill (c-save-buffer-state nil
4489 (c-guess-fill-prefix
4491 (c-collect-line-comments c-lit-limits))
4494 (start-col (current-column))
4496 (or (and (eq c-lit-type 'c)
4498 (goto-char (- (cdr c-lit-limits) 2))
4499 (if (looking-at "\\*/") (point))))
4500 (cdr c-lit-limits))))
4501 ;; Skip forward past the fill prefix in case
4502 ;; we're standing in it.
4504 ;; FIXME: This doesn't work well in cases like
4506 ;; /* Bla bla bla bla bla
4509 ;; If point is on the 'B' then the line will be
4510 ;; broken after "Bla b".
4512 ;; If we have an empty comment, /* */, the next
4513 ;; lot of code pushes point to the */. We fix
4514 ;; this by never allowing point to end up to the
4515 ;; right of where it started.
4516 (while (and (< (current-column) (cdr fill))
4519 (if (and (> (point) comment-text-end)
4520 (> (c-point 'bol) (car c-lit-limits)))
4522 ;; The skip takes us out of the (block)
4523 ;; comment; insert the fill prefix at bol
4524 ;; instead and keep the position.
4525 (setq pos (copy-marker pos t))
4527 (insert-and-inherit (car fill))
4528 (if soft (insert-and-inherit ?\n) (newline 1))
4530 (set-marker pos nil))
4531 ;; Don't break in the middle of a comment starter
4533 (cond ((> (point) comment-text-end)
4534 (goto-char comment-text-end))
4535 ((< (point) (+ (car c-lit-limits) 2))
4536 (goto-char (+ (car c-lit-limits) 2))))
4537 (funcall do-line-break)
4538 (insert-and-inherit (car fill))
4539 (if (> (current-column) start-col)
4540 (move-to-column start-col)))) ; can this hit the
4542 ;; Inside a comment that should be broken.
4543 (let ((comment-start comment-start)
4544 (comment-end comment-end)
4546 (if (eq c-lit-type 'c)
4547 (unless (string-match "[ \t]*/\\*" comment-start)
4548 (setq comment-start "/* " comment-end " */"))
4549 (unless (string-match "[ \t]*//" comment-start)
4550 (setq comment-start "// " comment-end "")))
4551 (setq col (save-excursion
4552 (back-to-indentation)
4554 (funcall do-line-break)
4555 (when (and comment-end (not (equal comment-end "")))
4557 (insert-and-inherit comment-end)
4559 ;; c-comment-indent may look at the current
4560 ;; indentation, so let's start out with the same
4561 ;; indentation as the previous one.
4563 (insert-and-inherit comment-start)
4564 (indent-for-comment))))
4565 ((c-query-and-set-macro-start)
4567 (unless (looking-at "[ \t]*\\\\$")
4568 ;; Do not clobber the alignment of the line continuation
4569 ;; slash; c-backslash-region might look at it.
4570 (delete-horizontal-space))
4571 ;; Got an asymmetry here: In normal code this command
4572 ;; doesn't indent the next line syntactically, and otoh a
4573 ;; normal syntactically indenting newline doesn't continue
4575 (c-newline-and-indent (if allow-auto-fill nil 1)))
4577 ;; Somewhere else in the code.
4578 (let ((col (save-excursion
4580 (while (and (looking-at "[ \t]*\\\\?$")
4581 (= (forward-line -1) 0)))
4582 (current-indentation))))
4583 (funcall do-line-break)
4584 (indent-to col))))))
4586 (defalias 'c-comment-line-break-function 'c-indent-new-comment-line)
4587 (make-obsolete 'c-comment-line-break-function 'c-indent-new-comment-line nil)
4589 ;; advice for indent-new-comment-line for older Emacsen
4590 (unless (boundp 'comment-line-break-function)
4591 (defvar c-inside-line-break-advice nil)
4592 (defadvice indent-new-comment-line (around c-line-break-advice
4593 activate preactivate)
4594 "Call `c-indent-new-comment-line' if in CC Mode."
4595 (if (or c-inside-line-break-advice
4596 (not c-buffer-is-cc-mode))
4598 (let ((c-inside-line-break-advice t))
4599 (c-indent-new-comment-line (ad-get-arg 0))))))
4601 (defun c-context-line-break ()
4602 "Do a line break suitable to the context.
4604 When point is outside a comment or macro, insert a newline and indent
4605 according to the syntactic context, unless `c-syntactic-indentation'
4606 is nil, in which case the new line is indented as the previous
4607 non-empty line instead.
4609 When point is inside the content of a preprocessor directive, a line
4610 continuation backslash is inserted before the line break and aligned
4611 appropriately. The end of the cpp directive doesn't count as inside
4614 When point is inside a comment, continue it with the appropriate
4615 comment prefix (see the `c-comment-prefix-regexp' and
4616 `c-block-comment-prefix' variables for details). The end of a
4617 C++-style line comment doesn't count as inside it.
4619 When point is inside a string, only insert a backslash when it is also
4620 inside a preprocessor directive."
4623 (let* (c-lit-limits c-lit-type
4624 (c-macro-start c-macro-start)
4627 (c-save-buffer-state ()
4628 (setq c-lit-limits (c-literal-limits nil nil t)
4629 c-lit-type (c-literal-type c-lit-limits))
4630 (when (eq c-lit-type 'c++)
4631 (setq c-lit-limits (c-collect-line-comments c-lit-limits)))
4632 (c-query-and-set-macro-start))
4635 ((or (eq c-lit-type 'c)
4636 (and (eq c-lit-type 'c++) ; C++ comment, but not at the very end of it.
4638 (skip-chars-forward " \t")
4640 (1- (cdr c-lit-limits))))
4641 (and (numberp c-macro-start) ; Macro, but not at the very end of
4642 ; it, not in a string, and not in the
4644 (not (eq c-lit-type 'string))
4645 (or (not (looking-at "\\s *$"))
4646 (eq (char-before) ?\\))
4648 (goto-char c-macro-start)
4649 (if (looking-at c-opt-cpp-start)
4650 (goto-char (match-end 0)))
4653 (let ((comment-multi-line t)
4655 (c-indent-new-comment-line nil t)))
4657 ((eq c-lit-type 'string)
4658 (if (and (numberp c-macro-start)
4659 (not (eq (char-before) ?\\)))
4663 (t (delete-horizontal-space)
4665 ;; c-indent-line may look at the current indentation, so let's
4666 ;; start out with the same indentation as the previous line.
4667 (let ((col (save-excursion
4670 (while (and (looking-at "[ \t]*\\\\?$")
4671 (= (forward-line -1) 0)))
4672 (current-indentation))))
4674 (indent-according-to-mode)))))
4676 (defun c-context-open-line ()
4677 "Insert a line break suitable to the context and leave point before it.
4678 This is the `c-context-line-break' equivalent to `open-line', which is
4679 normally bound to C-o. See `c-context-line-break' for the details."
4681 (let ((here (point)))
4684 ;; Temporarily insert a non-whitespace char to keep any
4685 ;; preceding whitespace intact.
4687 (c-context-line-break))
4692 (cc-provide 'cc-cmds)
4694 ;;; Local Variables:
4695 ;;; indent-tabs-mode: t
4698 ;;; cc-cmds.el ends here