1 ;;; cc-cmds.el --- user level commands for CC Mode
3 ;; Copyright (C) 1985, 1987, 1992-2016 Free Software Foundation, Inc.
5 ;; Authors: 2003- Alan Mackenzie
6 ;; 1998- Martin Stjernholm
7 ;; 1992-1999 Barry A. Warsaw
10 ;; 1985 Richard M. Stallman
11 ;; Maintainer: bug-cc-mode@gnu.org
12 ;; Created: 22-Apr-1997 (split from cc-mode.el)
13 ;; Keywords: c languages
16 ;; This file is part of GNU Emacs.
18 ;; GNU Emacs is free software: you can redistribute it and/or modify
19 ;; it under the terms of the GNU General Public License as published by
20 ;; the Free Software Foundation, either version 3 of the License, or
21 ;; (at your option) any later version.
23 ;; GNU Emacs is distributed in the hope that it will be useful,
24 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
25 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
26 ;; GNU General Public License for more details.
28 ;; You should have received a copy of the GNU General Public License
29 ;; along with GNU Emacs. If not, see <http://www.gnu.org/licenses/>.
37 (if (and (boundp 'byte-compile-dest-file)
38 (stringp byte-compile-dest-file))
39 (cons (file-name-directory byte-compile-dest-file) load-path)
41 (load "cc-bytecomp" nil t)))
45 (cc-require 'cc-engine)
47 ;; Silence the compiler.
48 (cc-bytecomp-defvar filladapt-mode) ; c-fill-paragraph contains a kludge
49 ; which looks at this.
51 ;; Indentation / Display syntax functions
52 (defvar c-fix-backslashes t)
54 (defun c-indent-line (&optional syntax quiet ignore-point-pos)
55 "Indent the current line according to the syntactic context,
56 if `c-syntactic-indentation' is non-nil. Optional SYNTAX is the
57 syntactic information for the current line. Be silent about syntactic
58 errors if the optional argument QUIET is non-nil, even if
59 `c-report-syntactic-errors' is non-nil. Normally the position of
60 point is used to decide where the old indentation is on a lines that
61 is otherwise empty \(ignoring any line continuation backslash), but
62 that's not done if IGNORE-POINT-POS is non-nil. Returns the amount of
63 indentation change \(in columns)."
65 (let ((line-cont-backslash (save-excursion
67 (eq (char-before) ?\\)))
68 (c-fix-backslashes c-fix-backslashes)
71 (when (and (not ignore-point-pos)
74 (looking-at (if line-cont-backslash
75 ;; Don't use "\\s " - ^L doesn't count as WS
79 (<= (point) (match-end 1)))
80 ;; Delete all whitespace after point if there's only whitespace
81 ;; on the line, so that any code that does back-to-indentation
82 ;; or similar gets the current column in this case. If this
83 ;; removes a line continuation backslash it'll be restored
85 (unless c-auto-align-backslashes
86 ;; Should try to keep the backslash alignment
89 (goto-char (match-end 0))
90 (setq bs-col (1- (current-column)))))
91 (delete-region (point) (match-end 0))
92 (setq c-fix-backslashes t))
93 (if c-syntactic-indentation
95 (or (let ((c-parsing-error nil)
98 (and (boundp 'c-syntactic-context)
99 c-syntactic-context))))
100 (c-save-buffer-state (indent)
101 (unless c-syntactic-context
102 (setq c-syntactic-context (c-guess-basic-syntax)))
103 (setq indent (c-get-syntactic-indentation
104 c-syntactic-context))
105 (and (not (c-echo-parsing-error quiet))
106 c-echo-syntactic-information-p
107 (message "syntax: %s, indent: %d"
108 c-syntactic-context indent))
109 (setq shift-amt (- indent (current-indentation))))
110 (c-shift-line-indentation shift-amt)
111 (run-hooks 'c-special-indent-hook)
116 (while (and (= (forward-line -1) 0)
117 (if (looking-at "\\s *\\\\?$")
119 (setq indent (current-indentation))
121 (setq shift-amt (- indent (current-indentation)))
122 (c-shift-line-indentation shift-amt)))
123 (when (and c-fix-backslashes line-cont-backslash)
128 (when c-auto-align-backslashes
129 ;; Realign the line continuation backslash.
130 (c-backslash-region (point) (point) nil t))))
133 (defun c-newline-and-indent (&optional newline-arg)
134 "Insert a newline and indent the new line.
135 This function fixes line continuation backslashes if inside a macro,
136 and takes care to set the indentation before calling
137 `indent-according-to-mode', so that lineup functions like
138 `c-lineup-dont-change' works better."
140 ;; TODO: Backslashes before eol in comments and literals aren't
142 (let ((c-macro-start (c-query-macro-start))
143 ;; Avoid calling c-backslash-region from c-indent-line if it's
144 ;; called during the newline call, which can happen due to
145 ;; c-electric-continued-statement, for example. We also don't
146 ;; want any backslash alignment from indent-according-to-mode.
147 (c-fix-backslashes nil)
148 has-backslash insert-backslash
153 (while (and (looking-at "[ \t]*\\\\?$")
154 (= (forward-line -1) 0)))
155 (setq col (current-indentation)))
157 (if (and (eolp) (eq (char-before) ?\\))
158 (setq insert-backslash t
160 (setq has-backslash (eq (char-before (c-point 'eol)) ?\\))))
161 (newline newline-arg)
166 ;; The backslash stayed on the previous line. Insert one
167 ;; before calling c-backslash-region, so that
168 ;; bs-col-after-end in it works better. Fixup the
169 ;; backslashes on the newly inserted line.
172 (c-backslash-region (point) (point) nil t))
173 ;; The backslash moved to the new line, if there was any. Let
174 ;; c-backslash-region fix a backslash on the previous line,
175 ;; and the one that might be on the new line.
176 ;; c-auto-align-backslashes is intentionally ignored here;
177 ;; maybe the moved backslash should be left alone if it's set,
178 ;; but we fix both lines on the grounds that the old backslash
179 ;; has been moved anyway and is now in a different context.
180 (c-backslash-region start (if has-backslash (point) start) nil t)))
181 (when c-syntactic-indentation
182 ;; Reindent syntactically. The indentation done above is not
183 ;; wasted, since c-indent-line might look at the current
185 (let ((c-syntactic-context (c-save-buffer-state nil
186 (c-guess-basic-syntax))))
187 ;; We temporarily insert another line break, so that the
188 ;; lineup functions will see the line as empty. That makes
189 ;; e.g. c-lineup-cpp-define more intuitive since it then
190 ;; proceeds to the preceding line in this case.
192 (delete-horizontal-space)
193 (setq start (- (point-max) (point)))
197 (indent-according-to-mode))
198 (goto-char (- (point-max) start))
201 ;; Must align the backslash again after reindentation. The
202 ;; c-backslash-region call above can't be optimized to ignore
203 ;; this line, since it then won't align correctly with the
204 ;; lines below if the first line in the macro is broken.
205 (c-backslash-region (point) (point) nil t)))))
207 (defun c-show-syntactic-information (arg)
208 "Show syntactic information for current line.
209 With universal argument, inserts the analysis as a comment on that line."
211 (let* ((c-parsing-error nil)
212 (syntax (if (boundp 'c-syntactic-context)
213 ;; Use `c-syntactic-context' in the same way as
214 ;; `c-indent-line', to be consistent.
216 (c-save-buffer-state nil
217 (c-guess-basic-syntax)))))
218 (if (not (consp arg))
220 (message "Syntactic analysis: %s" syntax)
224 (setq elem (pop syntax))
225 (when (setq pos (c-langelem-pos elem))
226 (push (c-put-overlay pos (1+ pos)
229 (when (setq pos (c-langelem-2nd-pos elem))
230 (push (c-put-overlay pos (1+ pos)
231 'face 'secondary-selection)
235 (c-delete-overlay (pop ols)))))
237 (insert-and-inherit (format "%s" syntax))
239 (c-keep-region-active))
241 (defun c-syntactic-information-on-region (from to)
242 "Insert a comment with the syntactic analysis on every line in the region."
246 (narrow-to-region from to)
247 (goto-char (point-min))
249 (c-show-syntactic-information '(0))
253 ;; Minor mode functions.
254 (defun c-update-modeline ()
255 (let ((fmt (format "/%s%s%s%s"
256 (if c-electric-flag "l" "")
257 (if (and c-electric-flag c-auto-newline)
259 (if c-hungry-delete-key "h" "")
261 ;; (cc-)subword might not be loaded.
262 (boundp 'c-subword-mode)
263 (symbol-value 'c-subword-mode))
264 ;; FIXME: subword-mode already comes with its
268 ;; FIXME: Derived modes might want to use something else
269 ;; than a string for `mode-name'.
270 (bare-mode-name (if (string-match "\\(^[^/]*\\)/" mode-name)
271 (match-string 1 mode-name)
273 ;; (setq c-submode-indicators
274 ;; (if (> (length fmt) 1)
277 (if (> (length fmt) 1)
278 (concat bare-mode-name fmt)
280 (force-mode-line-update)))
282 (defun c-toggle-syntactic-indentation (&optional arg)
283 "Toggle syntactic indentation.
284 Optional numeric ARG, if supplied, turns on syntactic indentation when
285 positive, turns it off when negative, and just toggles it when zero or
288 When syntactic indentation is turned on (the default), the indentation
289 functions and the electric keys indent according to the syntactic
290 context keys, when applicable.
292 When it's turned off, the electric keys don't reindent, the indentation
293 functions indents every new line to the same level as the previous
294 nonempty line, and \\[c-indent-command] adjusts the indentation in steps
295 specified by `c-basic-offset'. The indentation style has no effect in
296 this mode, nor any of the indentation associated variables,
297 e.g. `c-special-indent-hook'.
299 This command sets the variable `c-syntactic-indentation'."
301 (setq c-syntactic-indentation
302 (c-calculate-state arg c-syntactic-indentation))
303 (c-keep-region-active))
305 (defun c-toggle-auto-newline (&optional arg)
306 "Toggle auto-newline feature.
307 Optional numeric ARG, if supplied, turns on auto-newline when
308 positive, turns it off when negative, and just toggles it when zero or
311 Turning on auto-newline automatically enables electric indentation.
313 When the auto-newline feature is enabled (indicated by \"/la\" on the
314 mode line after the mode name) newlines are automatically inserted
315 after special characters such as brace, comma, semi-colon, and colon."
318 (c-calculate-state arg (and c-auto-newline c-electric-flag)))
319 (if c-auto-newline (setq c-electric-flag t))
321 (c-keep-region-active))
323 (defalias 'c-toggle-auto-state 'c-toggle-auto-newline)
324 (make-obsolete 'c-toggle-auto-state 'c-toggle-auto-newline "22.1")
326 (defun c-toggle-hungry-state (&optional arg)
327 "Toggle hungry-delete-key feature.
328 Optional numeric ARG, if supplied, turns on hungry-delete when
329 positive, turns it off when negative, and just toggles it when zero or
332 When the hungry-delete-key feature is enabled (indicated by \"/h\" on
333 the mode line after the mode name) the delete key gobbles all preceding
334 whitespace in one fell swoop."
336 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
338 (c-keep-region-active))
340 (defun c-toggle-auto-hungry-state (&optional arg)
341 "Toggle auto-newline and hungry-delete-key features.
342 Optional numeric ARG, if supplied, turns on auto-newline and
343 hungry-delete when positive, turns them off when negative, and just
344 toggles them when zero or left out.
346 See `c-toggle-auto-newline' and `c-toggle-hungry-state' for details."
348 (setq c-auto-newline (c-calculate-state arg c-auto-newline))
349 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
351 (c-keep-region-active))
353 (defun c-toggle-electric-state (&optional arg)
354 "Toggle the electric indentation feature.
355 Optional numeric ARG, if supplied, turns on electric indentation when
356 positive, turns it off when negative, and just toggles it when zero or
359 (setq c-electric-flag (c-calculate-state arg c-electric-flag))
361 (when (fboundp 'electric-indent-local-mode) ; Emacs 24.4 or later.
362 (electric-indent-local-mode (if c-electric-flag 1 0)))
363 (c-keep-region-active))
368 (defun c-electric-backspace (arg)
369 "Delete the preceding character or whitespace.
370 If `c-hungry-delete-key' is non-nil (indicated by \"/h\" on the mode
371 line) then all preceding whitespace is consumed. If however a prefix
372 argument is supplied, or `c-hungry-delete-key' is nil, or point is
373 inside a literal then the function in the variable
374 `c-backspace-function' is called."
376 (if (c-save-buffer-state ()
377 (or (not c-hungry-delete-key)
380 (funcall c-backspace-function (prefix-numeric-value arg))
381 (c-hungry-delete-backwards)))
383 (defun c-hungry-delete-backwards ()
384 "Delete the preceding character or all preceding whitespace
385 back to the previous non-whitespace character.
386 See also \\[c-hungry-delete-forward]."
388 (let ((here (point)))
390 (if (/= (point) here)
391 (delete-region (point) here)
392 (funcall c-backspace-function 1))))
394 (defalias 'c-hungry-backspace 'c-hungry-delete-backwards)
396 (defun c-electric-delete-forward (arg)
397 "Delete the following character or whitespace.
398 If `c-hungry-delete-key' is non-nil (indicated by \"/h\" on the mode
399 line) then all following whitespace is consumed. If however a prefix
400 argument is supplied, or `c-hungry-delete-key' is nil, or point is
401 inside a literal then the function in the variable `c-delete-function'
404 (if (c-save-buffer-state ()
405 (or (not c-hungry-delete-key)
408 (funcall c-delete-function (prefix-numeric-value arg))
409 (c-hungry-delete-forward)))
411 (defun c-hungry-delete-forward ()
412 "Delete the following character or all following whitespace
413 up to the next non-whitespace character.
414 See also \\[c-hungry-delete-backwards]."
416 (let ((here (point)))
418 (if (/= (point) here)
419 (delete-region (point) here)
420 (funcall c-delete-function 1))))
422 ;; This function is only used in XEmacs.
423 (defun c-electric-delete (arg)
424 "Deletes preceding or following character or whitespace.
425 This function either deletes forward as `c-electric-delete-forward' or
426 backward as `c-electric-backspace', depending on the configuration: If
427 the function `delete-forward-p' is defined and returns non-nil, it
428 deletes forward. Otherwise it deletes backward.
430 Note: This is the way in XEmacs to choose the correct action for the
431 [delete] key, whichever key that means. Other flavors don't use this
432 function to control that."
434 (if (and (fboundp 'delete-forward-p)
436 (c-electric-delete-forward arg)
437 (c-electric-backspace arg)))
439 ;; This function is only used in XEmacs.
440 (defun c-hungry-delete ()
441 "Delete a non-whitespace char, or all whitespace up to the next non-whitespace char.
442 The direction of deletion depends on the configuration: If the
443 function `delete-forward-p' is defined and returns non-nil, it deletes
444 forward using `c-hungry-delete-forward'. Otherwise it deletes
445 backward using `c-hungry-backspace'.
447 Note: This is the way in XEmacs to choose the correct action for the
448 [delete] key, whichever key that means. Other flavors don't use this
449 function to control that."
451 (if (and (fboundp 'delete-forward-p)
453 (c-hungry-delete-forward)
454 (c-hungry-delete-backwards)))
456 (defun c-electric-pound (arg)
458 If `c-electric-flag' is set, handle it specially according to the variable
459 `c-electric-pound-behavior'. If a numeric ARG is supplied, or if point is
460 inside a literal or a macro, nothing special happens."
462 (if (c-save-buffer-state ()
464 (not c-electric-flag)
465 (not (memq 'alignleft c-electric-pound-behavior))
467 (skip-chars-backward " \t")
470 (and (= (forward-line -1) 0)
472 (eq (char-before) ?\\))))
474 ;; do nothing special
475 (self-insert-command (prefix-numeric-value arg))
476 ;; place the pound character at the left edge
477 (let ((pos (- (point-max) (point)))
480 (delete-horizontal-space)
481 (insert (c-last-command-char))
483 (goto-char (- (point-max) pos)))
486 (defun c-point-syntax ()
487 ;; Return the syntactic context of the construct at point. (This is NOT
488 ;; nec. the same as the s.c. of the line point is on). N.B. This won't work
489 ;; between the `#' of a cpp thing and what follows (see c-opt-cpp-prefix).
490 (c-save-buffer-state (;; shut this up too
491 (c-echo-syntactic-information-p nil)
493 (c-tentative-buffer-changes
494 ;; insert a newline to isolate the construct at point for syntactic
497 ;; In AWK (etc.) or in a macro, make sure this CR hasn't changed
498 ;; the syntax. (There might already be an escaped NL there.)
501 (c-skip-ws-backward (c-point 'bopl))
506 (and (c-beginning-of-macro)
507 (progn (c-end-of-macro)
512 (let ((c-syntactic-indentation-in-macros t)
513 (c-auto-newline-analysis t))
514 ;; Turn on syntactic macro analysis to help with auto
516 (setq syntax (c-guess-basic-syntax))
520 (defun c-brace-newlines (syntax)
521 ;; A brace stands at point. SYNTAX is the syntactic context of this brace
522 ;; (not necessarily the same as the S.C. of the line it is on). Return
523 ;; NEWLINES, the list containing some combination of the symbols `before'
524 ;; and `after' saying where newlines should be inserted.
527 ;; This is the list of brace syntactic symbols that can hang.
528 ;; If any new ones are added to c-offsets-alist, they should be
529 ;; added here as well.
531 ;; The order of this list is important; if SYNTAX has several
532 ;; elements, the element that "wins" is the earliest in SYMS.
533 '(arglist-cont-nonempty ; e.g. an array literal.
534 class-open class-close defun-open defun-close
535 inline-open inline-close
536 brace-list-open brace-list-close
537 brace-list-intro brace-entry-open
538 block-open block-close
539 substatement-open statement-case-open
540 extern-lang-open extern-lang-close
541 namespace-open namespace-close
542 module-open module-close
543 composition-open composition-close
544 inexpr-class-open inexpr-class-close
545 ;; `statement-cont' is here for the case with a brace
546 ;; list opener inside a statement. C.f. CASE B.2 in
547 ;; `c-guess-continued-construct'.
550 (c-echo-syntactic-information-p nil)
551 symb-newlines) ; e.g. (substatement-open . (after))
554 ;; Do not try to insert newlines around a special
555 ;; (Pike-style) brace list.
556 (if (and c-special-brace-lists
558 (c-safe (if (= (char-before) ?{)
561 (c-looking-at-special-brace-list))))
563 ;; Seek the matching entry in c-hanging-braces-alist.
566 ;; Substitute inexpr-class and class-open or
567 ;; class-close with inexpr-class-open or
568 ;; inexpr-class-close.
569 (if (assq 'inexpr-class syntax)
570 (cond ((assq 'class-open syntax)
571 '((inexpr-class-open)))
572 ((assq 'class-close syntax)
573 '((inexpr-class-close)))
576 c-hanging-braces-alist)
577 '(ignore before after)))) ; Default, when not in c-h-b-l.
579 ;; If syntax is a function symbol, then call it using the
580 ;; defined semantics.
581 (if (and (not (consp (cdr symb-newlines)))
582 (functionp (cdr symb-newlines)))
583 (let ((c-syntactic-context syntax))
584 (funcall (cdr symb-newlines)
587 (cdr symb-newlines))))
589 (defun c-try-one-liner ()
590 ;; Point is just after a newly inserted }. If the non-whitespace
591 ;; content of the braces is a single line of code, compact the whole
592 ;; construct to a single line, if this line isn't too long. The Right
593 ;; Thing is done with comments.
595 ;; Point will be left after the }, regardless of whether the clean-up is
596 ;; done. Return NON-NIL if the clean-up happened, NIL if it didn't.
599 (pos (- (point-max) (point)))
600 mbeg1 mend1 mbeg4 mend4
601 eol-col cmnt-pos cmnt-col cmnt-gap)
606 ;; Avoid backtracking over a very large block. The one we
607 ;; deal with here can never be more than three lines.
608 (narrow-to-region (save-excursion
612 (and (c-safe (c-backward-sexp))
615 (narrow-to-region (point) (1- here)) ; innards of {.}
617 (cc-eval-when-compile
619 "\\(" ; (match-beginning 1)
620 "[ \t]*\\([\r\n][ \t]*\\)?" ; WS with opt. NL
621 "\\)" ; (match-end 1)
622 "[^ \t\r\n]+\\([ \t]+[^ \t\r\n]+\\)*" ; non-WS
623 "\\(" ; (match-beginning 4)
624 "[ \t]*\\([\r\n][ \t]*\\)?" ; WS with opt. NL
625 "\\)\\'"))))))) ; (match-end 4) at EOB.
627 (if (c-tentative-buffer-changes
628 (setq mbeg1 (match-beginning 1) mend1 (match-end 1)
629 mbeg4 (match-beginning 4) mend4 (match-end 4))
630 (backward-char) ; back over the `}'
632 (setq cmnt-pos (and (c-backward-single-comment)
633 (- (point) (- mend1 mbeg1)))))
634 (delete-region mbeg4 mend4)
635 (delete-region mbeg1 mend1)
636 (setq eol-col (save-excursion (end-of-line) (current-column)))
638 ;; Necessary to put the closing brace before any line
639 ;; oriented comment to keep it syntactically significant.
640 ;; This isn't necessary for block comments, but the result
641 ;; looks nicer anyway.
643 (delete-char 1) ; the `}' has blundered into a comment
645 (setq cmnt-col (1+ (current-column)))
646 (setq cmnt-pos (1+ cmnt-pos)) ; we're inserting a `}'
648 (insert-char ?\} 1) ; reinsert the `}' before the comment.
649 (setq cmnt-gap (- cmnt-col (current-column)))
650 (when (zerop cmnt-gap)
651 (insert-char ?\ 1) ; Put a space before a bare comment.
654 (or (null c-max-one-liner-length)
655 (zerop c-max-one-liner-length)
656 (<= eol-col c-max-one-liner-length)
657 ;; Can we trim space before comment to make the line fit?
659 (< (- eol-col cmnt-gap) c-max-one-liner-length)
660 (progn (goto-char cmnt-pos)
661 (backward-delete-char-untabify
662 (- eol-col c-max-one-liner-length))
664 (goto-char (- (point-max) pos))))))
666 (defun c-electric-brace (arg)
669 If `c-electric-flag' is non-nil, the brace is not inside a literal and a
670 numeric ARG hasn't been supplied, the command performs several electric
673 \(a) If the auto-newline feature is turned on (indicated by \"/la\" on
674 the mode line) newlines are inserted before and after the brace as
675 directed by the settings in `c-hanging-braces-alist'.
677 \(b) Any auto-newlines are indented. The original line is also
678 reindented unless `c-syntactic-indentation' is nil.
680 \(c) If auto-newline is turned on, various newline cleanups based on the
681 settings of `c-cleanup-list' are done."
684 (let (safepos literal
685 ;; We want to inhibit blinking the paren since this would be
686 ;; most disruptive. We'll blink it ourselves later on.
687 (old-blink-paren blink-paren-function)
688 blink-paren-function case-fold-search)
690 (c-save-buffer-state ()
691 (setq safepos (c-safe-position (point) (c-parse-state))
692 literal (c-in-literal safepos)))
694 ;; Insert the brace. Note that expand-abbrev might reindent
695 ;; the line here if there's a preceding "else" or something.
696 (self-insert-command (prefix-numeric-value arg))
698 (when (and c-electric-flag (not literal) (not arg))
699 (if (not (looking-at "[ \t]*\\\\?$"))
700 (if c-syntactic-indentation
701 (indent-according-to-mode))
703 (let ( ;; shut this up too
704 (c-echo-syntactic-information-p nil)
706 ln-syntax br-syntax syntax) ; Syntactic context of the original line,
707 ; of the brace itself, of the line the brace ends up on.
708 (c-save-buffer-state ((c-syntactic-indentation-in-macros t)
709 (c-auto-newline-analysis t))
710 (setq ln-syntax (c-guess-basic-syntax)))
711 (if c-syntactic-indentation
712 (c-indent-line ln-syntax))
716 (setq br-syntax (c-point-syntax)
717 newlines (c-brace-newlines br-syntax))
719 ;; Insert the BEFORE newline, if wanted, and reindent the newline.
720 (if (and (memq 'before newlines)
721 (> (current-column) (current-indentation)))
722 (if c-syntactic-indentation
723 ;; Only a plain newline for now - it's indented
724 ;; after the cleanups when the line has its final
727 (c-newline-and-indent)))
730 ;; `syntax' is the syntactic context of the line which ends up
731 ;; with the brace on it.
732 (setq syntax (if (memq 'before newlines) br-syntax ln-syntax))
734 ;; Do all appropriate clean ups
736 (pos (- (point-max) (point)))
740 ;; `}': clean up empty defun braces
741 (when (c-save-buffer-state ()
742 (and (memq 'empty-defun-braces c-cleanup-list)
743 (eq (c-last-command-char) ?\})
744 (c-intersect-lists '(defun-close class-close inline-close)
749 (eq (char-before) ?\{))
750 ;; make sure matching open brace isn't in a comment
751 (not (c-in-literal))))
752 (delete-region (point) (1- here))
753 (setq here (- (point-max) pos)))
756 ;; `}': compact to a one-liner defun?
759 (and (eq (c-last-command-char) ?\})
760 (memq 'one-liner-defun c-cleanup-list)
761 (c-intersect-lists '(defun-close) syntax)
763 (setq here (- (point-max) pos))))
765 ;; `{': clean up brace-else-brace and brace-elseif-brace
766 (when (eq (c-last-command-char) ?\{)
768 ((and (memq 'brace-else-brace c-cleanup-list)
771 "\\([ \t\n]\\|\\\\\n\\)*"
773 "\\([ \t\n]\\|\\\\\n\\)*"
777 (delete-region (match-beginning 0) (match-end 0))
778 (insert-and-inherit "} else {"))
779 ((and (memq 'brace-elseif-brace c-cleanup-list)
781 (goto-char (1- here))
785 (eq (char-before) ?\)))
786 (zerop (c-save-buffer-state nil (c-backward-token-2 1 t)))
787 (eq (char-after) ?\()
792 "\\([ \t\n]\\|\\\\\n\\)*"
794 "\\([ \t\n]\\|\\\\\n\\)+"
796 "\\([ \t\n]\\|\\\\\n\\)*"
799 ;(eq (match-end 0) tmp);
801 (delete-region mbeg mend)
805 (goto-char (- (point-max) pos))
807 ;; Indent the line after the cleanups since it might
808 ;; very well indent differently due to them, e.g. if
809 ;; c-indent-one-line-block is used together with the
810 ;; one-liner-defun cleanup.
811 (when c-syntactic-indentation
814 ;; does a newline go after the brace?
815 (if (memq 'after newlines)
816 (c-newline-and-indent))
820 (and (eq (c-last-command-char) ?\})
821 (not executing-kbd-macro)
824 (c-save-buffer-state nil
825 (c-backward-syntactic-ws safepos))
826 (funcall old-blink-paren)))))
828 (defun c-electric-slash (arg)
829 "Insert a slash character.
831 If the slash is inserted immediately after the comment prefix in a c-style
832 comment, the comment might get closed by removing whitespace and possibly
833 inserting a \"*\". See the variable `c-cleanup-list'.
835 Indent the line as a comment, if:
837 1. The slash is second of a \"//\" line oriented comment introducing
838 token and we are on a comment-only-line, or
840 2. The slash is part of a \"*/\" token that closes a block oriented
843 If a numeric ARG is supplied, point is inside a literal, or
844 `c-syntactic-indentation' is nil or `c-electric-flag' is nil, indentation
847 (let ((literal (c-save-buffer-state () (c-in-literal)))
850 (c-echo-syntactic-information-p nil))
852 ;; comment-close-slash cleanup? This DOESN'T need `c-electric-flag' or
853 ;; `c-syntactic-indentation' set.
856 (memq 'comment-close-slash c-cleanup-list)
857 (eq (c-last-command-char) ?/)
858 (looking-at (concat "[ \t]*\\("
859 (regexp-quote comment-end) "\\)?$"))
860 ; (eq c-block-comment-ender "*/") ; C-style comments ALWAYS end in */
863 (narrow-to-region (point-min) (point))
864 (back-to-indentation)
865 (looking-at (concat c-current-comment-prefix "[ \t]*$")))))
866 (delete-region (progn (forward-line 0) (point))
867 (progn (end-of-line) (point)))
868 (insert-char ?* 1)) ; the / comes later. ; Do I need a t (retain sticky properties) here?
870 (setq indentp (and (not arg)
871 c-syntactic-indentation
873 (eq (c-last-command-char) ?/)
874 (eq (char-before) (if literal ?* ?/))))
875 (self-insert-command (prefix-numeric-value arg))
877 (indent-according-to-mode))))
879 (defun c-electric-star (arg)
880 "Insert a star character.
881 If `c-electric-flag' and `c-syntactic-indentation' are both non-nil, and
882 the star is the second character of a C style comment starter on a
883 comment-only-line, indent the line as a comment. If a numeric ARG is
884 supplied, point is inside a literal, or `c-syntactic-indentation' is nil,
885 this indentation is inhibited."
888 (self-insert-command (prefix-numeric-value arg))
889 ;; if we are in a literal, or if arg is given do not reindent the
890 ;; current line, unless this star introduces a comment-only line.
891 (if (c-save-buffer-state ()
892 (and c-syntactic-indentation
895 (eq (c-in-literal) 'c)
896 (eq (char-before) ?*)
899 (skip-chars-backward "*")
900 (if (eq (char-before) ?/)
902 (skip-chars-backward " \t")
904 (let (c-echo-syntactic-information-p) ; shut this up
905 (indent-according-to-mode))
908 (defun c-electric-semi&comma (arg)
909 "Insert a comma or semicolon.
911 If `c-electric-flag' is non-nil, point isn't inside a literal and a
912 numeric ARG hasn't been supplied, the command performs several electric
915 \(a) When the auto-newline feature is turned on (indicated by \"/la\" on
916 the mode line) a newline might be inserted. See the variable
917 `c-hanging-semi&comma-criteria' for how newline insertion is determined.
919 \(b) Any auto-newlines are indented. The original line is also
920 reindented unless `c-syntactic-indentation' is nil.
922 \(c) If auto-newline is turned on, a comma following a brace list or a
923 semicolon following a defun might be cleaned up, depending on the
924 settings of `c-cleanup-list'."
926 (let* (lim literal c-syntactic-context
929 (c-echo-syntactic-information-p nil))
931 (c-save-buffer-state ()
932 (setq lim (c-most-enclosing-brace (c-parse-state))
933 literal (c-in-literal lim)))
935 (self-insert-command (prefix-numeric-value arg))
937 (if (and c-electric-flag (not literal) (not arg))
938 ;; do all cleanups and newline insertions if c-auto-newline is on.
939 (if (or (not c-auto-newline)
940 (not (looking-at "[ \t]*\\\\?$")))
941 (if c-syntactic-indentation
943 ;; clean ups: list-close-comma or defun-close-semi
944 (let ((pos (- (point-max) (point))))
945 (if (c-save-buffer-state ()
947 (eq (c-last-command-char) ?,)
948 (memq 'list-close-comma c-cleanup-list))
950 (eq (c-last-command-char) ?\;)
951 (memq 'defun-close-semi c-cleanup-list)))
955 (eq (char-before) ?}))
956 ;; make sure matching open brace isn't in a comment
957 (not (c-in-literal lim))))
958 (delete-region (point) here))
959 (goto-char (- (point-max) pos)))
961 (when c-syntactic-indentation
962 (setq c-syntactic-context (c-guess-basic-syntax))
963 (c-indent-line c-syntactic-context))
964 ;; check to see if a newline should be added
965 (let ((criteria c-hanging-semi&comma-criteria)
966 answer add-newline-p)
968 (setq answer (funcall (car criteria)))
969 ;; only nil value means continue checking
971 (setq criteria (cdr criteria))
973 ;; only 'stop specifically says do not add a newline
974 (setq add-newline-p (not (eq answer 'stop)))
977 (c-newline-and-indent))
980 (defun c-electric-colon (arg)
983 If `c-electric-flag' is non-nil, the colon is not inside a literal and a
984 numeric ARG hasn't been supplied, the command performs several electric
987 \(a) If the auto-newline feature is turned on (indicated by \"/la\" on
988 the mode line) newlines are inserted before and after the colon based on
989 the settings in `c-hanging-colons-alist'.
991 \(b) Any auto-newlines are indented. The original line is also
992 reindented unless `c-syntactic-indentation' is nil.
994 \(c) If auto-newline is turned on, whitespace between two colons will be
995 \"cleaned up\" leaving a scope operator, if this action is set in
999 (let* ((bod (c-point 'bod))
1000 (literal (c-save-buffer-state () (c-in-literal bod)))
1001 newlines is-scope-op
1003 (c-echo-syntactic-information-p nil))
1004 (self-insert-command (prefix-numeric-value arg))
1005 ;; Any electric action?
1006 (if (and c-electric-flag (not literal) (not arg))
1007 ;; Unless we're at EOL, only re-indentation happens.
1008 (if (not (looking-at "[ \t]*\\\\?$"))
1009 (if c-syntactic-indentation
1010 (indent-according-to-mode))
1012 ;; scope-operator clean-up?
1013 (let ((pos (- (point-max) (point)))
1015 (if (c-save-buffer-state () ; Why do we need this? [ACM, 2003-03-12]
1017 (memq 'scope-operator c-cleanup-list)
1018 (eq (char-before) ?:)
1021 (c-skip-ws-backward)
1022 (eq (char-before) ?:))
1023 (not (c-in-literal))
1024 (not (eq (char-after (- (point) 2)) ?:))))
1026 (delete-region (point) (1- here))
1027 (setq is-scope-op t)))
1028 (goto-char (- (point-max) pos)))
1030 ;; indent the current line if it's done syntactically.
1031 (if c-syntactic-indentation
1032 ;; Cannot use the same syntax analysis as we find below,
1033 ;; since that's made with c-syntactic-indentation-in-macros
1035 (indent-according-to-mode))
1037 ;; Calculate where, if anywhere, we want newlines.
1038 (c-save-buffer-state
1039 ((c-syntactic-indentation-in-macros t)
1040 (c-auto-newline-analysis t)
1041 ;; Turn on syntactic macro analysis to help with auto newlines
1043 (syntax (c-guess-basic-syntax))
1045 ;; Translate substatement-label to label for this operation.
1047 (if (eq (car (car elem)) 'substatement-label)
1048 (setcar (car elem) 'label))
1049 (setq elem (cdr elem)))
1050 ;; some language elements can only be determined by checking
1051 ;; the following line. Let's first look for ones that can be
1052 ;; found when looking on the line with the colon
1055 (or (c-lookup-lists '(case-label label access-label)
1056 syntax c-hanging-colons-alist)
1057 (c-lookup-lists '(member-init-intro inher-intro)
1061 (c-guess-basic-syntax)
1063 c-hanging-colons-alist)))))
1064 ;; does a newline go before the colon? Watch out for already
1065 ;; non-hung colons. However, we don't unhang them because that
1066 ;; would be a cleanup (and anti-social).
1067 (if (and (memq 'before newlines)
1070 (skip-chars-backward ": \t")
1072 (let ((pos (- (point-max) (point))))
1074 (c-newline-and-indent)
1075 (goto-char (- (point-max) pos))))
1076 ;; does a newline go after the colon?
1077 (if (and (memq 'after (cdr-safe newlines))
1079 (c-newline-and-indent))
1082 (defun c-electric-lt-gt (arg)
1083 "Insert a \"<\" or \">\" character.
1084 If the current language uses angle bracket parens (e.g. template
1085 arguments in C++), try to find out if the inserted character is a
1086 paren and give it paren syntax if appropriate.
1088 If `c-electric-flag' and `c-syntactic-indentation' are both non-nil, the
1089 line will be reindented if the inserted character is a paren or if it
1090 finishes a C++ style stream operator in C++ mode. Exceptions are when a
1091 numeric argument is supplied, or the point is inside a literal."
1094 (let ((c-echo-syntactic-information-p nil)
1095 final-pos found-delim case-fold-search)
1097 (self-insert-command (prefix-numeric-value arg))
1098 (setq final-pos (point))
1100 ;;;; 2010-01-31: There used to be code here to put a syntax-table text
1101 ;;;; property on the new < or > and its mate (if any) when they are template
1102 ;;;; parens. This is now done in an after-change function.
1104 ;; Indent the line if appropriate.
1105 (when (and c-electric-flag c-syntactic-indentation c-recognize-<>-arglists)
1107 (if (eq (c-last-command-char) ?<)
1108 ;; If a <, basically see if it's got "template" before it .....
1112 (progn (c-beginning-of-current-token) (point))))
1114 (c-backward-token-2)
1115 (looking-at c-opt-<>-sexp-key)))
1116 ;; ..... or is a C++ << operator.
1117 (and (c-major-mode-is 'c++-mode)
1119 (goto-char (1- final-pos))
1120 (c-beginning-of-current-token)
1122 (>= (match-end 0) final-pos)))
1124 ;; It's a >. Either a template/generic terminator ...
1125 (or (c-get-char-property (1- final-pos) 'syntax-table)
1126 ;; or a C++ >> operator.
1127 (and (c-major-mode-is 'c++-mode)
1129 (goto-char (1- final-pos))
1130 (c-beginning-of-current-token)
1132 (>= (match-end 0) final-pos))))))
1134 (goto-char final-pos)
1136 (indent-according-to-mode)
1137 (when (and (eq (char-before) ?>)
1138 (not executing-kbd-macro)
1139 blink-paren-function)
1140 ;; From now (2016-01-01), the syntax-table text properties on < and >
1141 ;; are applied in an after-change function, not during redisplay. Hence
1142 ;; we no longer need to call (sit-for 0) for blink paren to work.
1143 (funcall blink-paren-function)))))
1145 (defun c-electric-paren (arg)
1146 "Insert a parenthesis.
1148 If `c-syntactic-indentation' and `c-electric-flag' are both non-nil, the
1149 line is reindented unless a numeric ARG is supplied, or the parenthesis
1150 is inserted inside a literal.
1152 Whitespace between a function name and the parenthesis may get added or
1153 removed; see the variable `c-cleanup-list'.
1155 Also, if `c-electric-flag' and `c-auto-newline' are both non-nil, some
1156 newline cleanups are done if appropriate; see the variable `c-cleanup-list'."
1158 (let ((literal (c-save-buffer-state () (c-in-literal)))
1160 (c-echo-syntactic-information-p nil)
1162 (self-insert-command (prefix-numeric-value arg))
1164 (if (and (not arg) (not literal))
1165 (let* ( ;; We want to inhibit blinking the paren since this will
1166 ;; be most disruptive. We'll blink it ourselves
1168 (old-blink-paren blink-paren-function)
1169 blink-paren-function)
1170 (if (and c-syntactic-indentation c-electric-flag)
1171 (indent-according-to-mode))
1173 ;; If we're at EOL, check for new-line clean-ups.
1174 (when (and c-electric-flag c-auto-newline
1175 (looking-at "[ \t]*\\\\?$"))
1177 ;; clean up brace-elseif-brace
1179 (and (memq 'brace-elseif-brace c-cleanup-list)
1180 (eq (c-last-command-char) ?\()
1183 "\\([ \t\n]\\|\\\\\n\\)*"
1185 "\\([ \t\n]\\|\\\\\n\\)+"
1187 "\\([ \t\n]\\|\\\\\n\\)*"
1191 (not (c-save-buffer-state () (c-in-literal))))
1192 (delete-region (match-beginning 0) (match-end 0))
1193 (insert-and-inherit "} else if ("))
1195 ;; clean up brace-catch-brace
1197 (and (memq 'brace-catch-brace c-cleanup-list)
1198 (eq (c-last-command-char) ?\()
1201 "\\([ \t\n]\\|\\\\\n\\)*"
1203 "\\([ \t\n]\\|\\\\\n\\)*"
1207 (not (c-save-buffer-state () (c-in-literal))))
1208 (delete-region (match-beginning 0) (match-end 0))
1209 (insert-and-inherit "} catch (")))
1211 ;; Check for clean-ups at function calls. These two DON'T need
1212 ;; `c-electric-flag' or `c-syntactic-indentation' set.
1213 ;; Point is currently just after the inserted paren.
1214 (let (beg (end (1- (point))))
1217 ;; space-before-funcall clean-up?
1218 ((and (memq 'space-before-funcall c-cleanup-list)
1219 (eq (c-last-command-char) ?\()
1222 (skip-chars-backward " \t")
1224 (and (c-save-buffer-state () (c-on-identifier))
1225 ;; Don't add a space into #define FOO()....
1226 (not (and (c-beginning-of-macro)
1227 (c-forward-over-cpp-define-id)
1228 (eq (point) beg))))))
1230 (delete-region beg end)
1234 ;; compact-empty-funcall clean-up?
1235 ((c-save-buffer-state ()
1236 (and (memq 'compact-empty-funcall c-cleanup-list)
1237 (eq (c-last-command-char) ?\))
1239 (c-safe (backward-char 2))
1240 (when (looking-at "()")
1242 (skip-chars-backward " \t")
1244 (c-on-identifier)))))
1245 (delete-region beg end))))
1246 (and (eq last-input-event ?\))
1247 (not executing-kbd-macro)
1249 (funcall old-blink-paren))))))
1251 (defun c-electric-continued-statement ()
1252 "Reindent the current line if appropriate.
1254 This function is used to reindent the line after a keyword which
1255 continues an earlier statement is typed, e.g. an \"else\" or the
1256 \"while\" in a do-while block.
1258 The line is reindented if there is nothing but whitespace before the
1259 keyword on the line, the keyword is not inserted inside a literal, and
1260 `c-electric-flag' and `c-syntactic-indentation' are both non-nil."
1261 (let (;; shut this up
1262 (c-echo-syntactic-information-p nil))
1263 (when (c-save-buffer-state ()
1264 (and c-electric-flag
1265 c-syntactic-indentation
1266 (not (eq (c-last-command-char) ?_))
1268 (skip-syntax-backward "w")
1271 (not (c-in-literal (c-point 'bod)))))
1272 ;; Have to temporarily insert a space so that
1273 ;; c-guess-basic-syntax recognizes the keyword. Follow the
1274 ;; space with a nonspace to avoid messing up any whitespace
1275 ;; sensitive meddling that might be done, e.g. by
1276 ;; `c-backslash-region'.
1277 (insert-and-inherit " x")
1279 (indent-according-to-mode)
1280 (delete-char -2)))))
1284 (declare-function subword-forward "subword" (&optional arg))
1285 (declare-function subword-backward "subword" (&optional arg))
1288 ((and (fboundp 'subword-mode) (not (fboundp 'c-subword-mode)))
1289 ;; Recent Emacsen come with their own subword support. Use that.
1290 (define-obsolete-function-alias 'c-subword-mode 'subword-mode "24.3")
1291 (define-obsolete-variable-alias 'c-subword-mode 'subword-mode "24.3"))
1293 ;; Autoload directive for emacsen that doesn't have an older CC Mode
1294 ;; version in the dist.
1295 (autoload 'c-subword-mode "cc-subword"
1296 "Mode enabling subword movement and editing keys." t)))
1298 (declare-function c-forward-subword "ext:cc-subword" (&optional arg))
1299 (declare-function c-backward-subword "ext:cc-subword" (&optional arg))
1301 ;; "nomenclature" functions + c-scope-operator.
1302 (defun c-forward-into-nomenclature (&optional arg)
1303 "Compatibility alias for `c-forward-subword'."
1305 (if (fboundp 'subword-mode)
1308 (subword-forward arg))
1309 (require 'cc-subword)
1310 (c-forward-subword arg)))
1311 (make-obsolete 'c-forward-into-nomenclature
1312 (if (fboundp 'subword-mode) 'subword-forward 'c-forward-subword)
1315 (defun c-backward-into-nomenclature (&optional arg)
1316 "Compatibility alias for `c-backward-subword'."
1318 (if (fboundp 'subword-mode)
1321 (subword-backward arg))
1322 (require 'cc-subword)
1323 (c-backward-subword arg)))
1325 'c-backward-into-nomenclature
1326 (if (fboundp 'subword-mode) 'subword-backward 'c-backward-subword) "23.2")
1328 (defun c-scope-operator ()
1329 "Insert a double colon scope operator at point.
1330 No indentation or other \"electric\" behavior is performed."
1332 (insert-and-inherit "::"))
1335 ;; Movement (etc.) by defuns.
1336 (defun c-in-function-trailer-p (&optional lim)
1337 ;; Return non-nil if point is between the closing brace and the semicolon of
1338 ;; a brace construct which needs a semicolon, e.g. within the "variables"
1339 ;; portion of a declaration like "struct foo {...} bar ;".
1341 ;; Return the position of the main declaration. Otherwise, return nil.
1342 ;; Point is assumed to be at the top level and outside of any macro or
1345 ;; If LIM is non-nil, it is the bound on a the backward search for the
1346 ;; beginning of the declaration.
1348 ;; This function might do hidden buffer changes.
1349 (and c-opt-block-decls-with-vars-key
1351 (c-syntactic-skip-backward "^;}" lim)
1352 (let ((eo-block (point))
1354 (and (eq (char-before) ?\})
1355 (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1357 ;; Look for struct or union or ... If we find one, it might
1358 ;; be the return type of a function, or the like. Exclude
1360 (c-syntactic-re-search-forward
1361 (concat "[;=([{]\\|\\("
1362 c-opt-block-decls-with-vars-key
1365 (match-beginning 1) ; Is there a "struct" etc., somewhere?
1366 (not (eq (char-before) ?_))
1367 (c-syntactic-re-search-forward "[;=([{]" eo-block t t t)
1368 (eq (char-before) ?\{)
1371 (defun c-where-wrt-brace-construct ()
1372 ;; Determine where we are with respect to functions (or other brace
1373 ;; constructs, included in the term "function" in the rest of this comment).
1374 ;; Point is assumed to be outside any macro or literal.
1375 ;; This is used by c-\(beginning\|end\)-of-defun.
1377 ;; Return one of these symbols:
1378 ;; at-header : we're at the start of a function's header.
1379 ;; in-header : we're inside a function's header, this extending right
1380 ;; up to the brace. This bit includes any k&r declarations.
1381 ;; in-block : we're inside a function's brace block.
1382 ;; in-trailer : we're in the area between the "}" and ";" of something
1383 ;; like "struct foo {...} bar, baz;".
1384 ;; at-function-end : we're just after the closing brace (or semicolon) that
1385 ;; terminates the function.
1386 ;; outwith-function: we're not at or in any function. Being inside a
1387 ;; non-brace construct also counts as 'outwith-function'.
1389 ;; This function might do hidden buffer changes.
1392 decl-result brace-decl-p
1394 (paren-state (c-parse-state))
1395 (least-enclosing (c-least-enclosing-brace paren-state)))
1398 ((and least-enclosing
1399 (eq (char-after least-enclosing) ?\{))
1401 ((c-in-function-trailer-p)
1403 ((and (not least-enclosing)
1405 (consp (car paren-state))
1406 (eq start (cdar paren-state)))
1409 ;; Find the start of the current declaration. NOTE: If we're in the
1410 ;; variables after a "struct/eval" type block, we don't get to the
1411 ;; real declaration here - we detect and correct for this later.
1413 ;;If we're in the parameters' parens, move back out of them.
1414 (if least-enclosing (goto-char least-enclosing))
1415 ;; Kluge so that c-beginning-of-decl-1 won't go back if we're already
1416 ;; at a declaration.
1417 (if (or (and (eolp) (not (eobp))) ; EOL is matched by "\\s>"
1419 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\|\\s!\\)")))
1421 (setq kluge-start (point))
1423 (car (c-beginning-of-decl-1
1424 ;; NOTE: If we're in a K&R region, this might be the start
1425 ;; of a parameter declaration, not the actual function.
1426 ;; It might also leave us at a label or "label" like
1428 (and least-enclosing ; LIMIT for c-b-of-decl-1
1429 (c-safe-position least-enclosing paren-state)))))
1431 ;; Has the declaration we've gone back to got braces?
1432 (or (eq decl-result 'label)
1435 (and (c-syntactic-re-search-forward "[;{]" nil t t)
1436 (or (eq (char-before) ?\{)
1437 (and c-recognize-knr-p
1438 ;; Might have stopped on the
1439 ;; ';' in a K&R argdecl. In
1440 ;; that case the declaration
1441 ;; should contain a block.
1442 (c-in-knr-argdecl)))))))
1445 ((or (eq decl-result 'label) ; e.g. "private:" or invalid syntax.
1446 (= (point) kluge-start)) ; might be BOB or unbalanced parens.
1448 ((eq decl-result 'same)
1450 (if (eq (point) start)
1454 ((eq decl-result 'previous)
1455 (if (and (not brace-decl-p)
1456 (c-in-function-trailer-p))
1460 "c-where-wrt-brace-construct: c-beginning-of-decl-1 returned %s"
1463 (defun c-backward-to-nth-BOF-{ (n where)
1464 ;; Skip to the opening brace of the Nth function before point. If
1465 ;; point is inside a function, this counts as the first. Point must be
1466 ;; outside any comment/string or macro.
1468 ;; N must be strictly positive.
1469 ;; WHERE describes the position of point, one of the symbols `at-header',
1470 ;; `in-header', `in-block', `in-trailer', `at-function-end',
1471 ;; `outwith-function' as returned by c-where-wrt-brace-construct.
1473 ;; If we run out of functions, leave point at BOB. Return zero on success,
1474 ;; otherwise the number of {s still to go.
1476 ;; This function may do hidden buffer changes
1478 ;; What we do to go back the first defun depends on where we start.
1480 ((eq where 'in-block)
1481 (goto-char (c-least-enclosing-brace (c-parse-state)))
1483 ((eq where 'in-header)
1484 (c-syntactic-re-search-forward "{")
1487 ((memq where '(at-header outwith-function at-function-end in-trailer))
1488 (c-syntactic-skip-backward "^}")
1489 (when (eq (char-before) ?\})
1492 (t (error "Unknown `where' %s in c-backward-to-nth-EOF-{" where)))
1494 ;; Each time round the loop, go back to a "{" at the outermost level.
1495 (while (and (> n 0) (not (bobp)))
1496 (c-parse-state) ; This call speeds up the following one
1497 ; by a factor of ~6. Hmmm. 2006/4/5.
1498 (c-syntactic-skip-backward "^}")
1499 (when (eq (char-before) ?\})
1504 (defun c-narrow-to-most-enclosing-decl-block (&optional inclusive)
1505 ;; If we are inside a decl-block (in the sense of c-looking-at-decl-block),
1506 ;; i.e. something like namespace{} or extern{}, narrow to the insides of
1507 ;; that block (NOT including the enclosing braces) if INCLUSIVE is nil,
1508 ;; otherwise include the braces. If the closing brace is missing,
1509 ;; (point-max) is used instead.
1510 (let ((paren-state (c-parse-state))
1512 (setq encl-decl (and paren-state (c-most-enclosing-decl-block paren-state)))
1517 (progn (goto-char encl-decl)
1518 (c-beginning-of-decl-1)
1522 (goto-char encl-decl)
1523 (or (c-safe (forward-list)
1529 (defun c-widen-to-enclosing-decl-scope (paren-state orig-point-min orig-point-max)
1530 ;; Narrow the buffer to the innermost declaration scope (e.g. a class, a
1531 ;; namespace or the "whole buffer") recorded in PAREN-STATE, the bounding
1532 ;; braces NOT being included in the resulting region. On no account may the
1533 ;; final region exceed that bounded by ORIG-POINT-MIN, ORIG-POINT-MAX.
1534 ;; PAREN-STATE is a list of buffer positions in the style of
1535 ;; (c-parse-state), one of which will be that of the desired opening brace,
1538 ;; Return the position of the enclosing opening brace, or nil
1539 (let (encl-decl) ; putative position of decl-scope's opening brace.
1541 (narrow-to-region orig-point-min orig-point-max)
1542 (setq encl-decl (and paren-state
1543 (c-most-enclosing-decl-block paren-state))))
1547 (narrow-to-region (1+ encl-decl)
1549 (goto-char encl-decl)
1550 (or (c-safe (forward-list)
1554 (narrow-to-region orig-point-min orig-point-max)
1558 (defmacro c-while-widening-to-decl-block (condition)
1559 ;; Repeatedly evaluate CONDITION until it returns nil. After each
1560 ;; evaluation, if `c-defun-tactic' is set appropriately, widen to innards
1561 ;; of the next enclosing declaration block (e.g. namespace, class), or the
1562 ;; buffer's original restriction.
1564 ;; This is a very special purpose macro, which assumes the existence of
1565 ;; several variables. It is for use only in c-beginning-of-defun and
1569 (eq c-defun-tactic 'go-outward)
1571 (setq paren-state (c-whack-state-after lim paren-state))
1572 (setq lim (c-widen-to-enclosing-decl-scope
1573 paren-state orig-point-min orig-point-max))
1574 (setq where 'in-block))))
1576 (defun c-beginning-of-defun (&optional arg)
1577 "Move backward to the beginning of a defun.
1578 Every top level declaration that contains a brace paren block is
1579 considered to be a defun.
1581 With a positive argument, move backward that many defuns. A negative
1582 argument -N means move forward to the Nth following beginning. Return
1583 t unless search stops due to beginning or end of buffer.
1585 Unlike the built-in `beginning-of-defun' this tries to be smarter
1586 about finding the char with open-parenthesis syntax that starts the
1590 (or arg (setq arg 1))
1592 (or (not (eq this-command 'c-beginning-of-defun))
1593 (eq last-command 'c-beginning-of-defun)
1594 (c-region-is-active-p)
1597 (c-self-bind-state-cache ; We must not share with other users of c-state-cache.
1598 (c-save-buffer-state
1599 (beginning-of-defun-function
1600 end-of-defun-function
1602 (paren-state (c-parse-state))
1603 (orig-point-min (point-min)) (orig-point-max (point-max))
1604 lim ; Position of { which has been widened to.
1605 where pos case-fold-search)
1608 (if (eq c-defun-tactic 'go-outward)
1609 (setq lim (c-widen-to-enclosing-decl-scope ; e.g. class, namespace.
1610 paren-state orig-point-min orig-point-max)))
1612 ;; Move back out of any macro/comment/string we happen to be in.
1613 (c-beginning-of-macro)
1614 (setq pos (c-literal-limits))
1615 (if pos (goto-char (car pos)))
1617 (setq where (c-where-wrt-brace-construct))
1620 ;; Move forward to the closing brace of a function.
1622 (if (memq where '(at-function-end outwith-function))
1623 (setq arg (1+ arg)))
1625 (c-while-widening-to-decl-block
1626 (< (setq arg (- (c-forward-to-nth-EOF-} (- arg) where))) 0)))
1627 ;; Move forward to the next opening brace....
1628 (when (and (= arg 0)
1630 (c-while-widening-to-decl-block
1631 (not (c-syntactic-re-search-forward "{" nil 'eob)))
1632 (eq (char-before) ?{)))
1634 ;; ... and backward to the function header.
1635 (c-beginning-of-decl-1)
1638 ;; Move backward to the opening brace of a function, making successively
1639 ;; larger portions of the buffer visible as necessary.
1641 (c-while-widening-to-decl-block
1642 (> (setq arg (c-backward-to-nth-BOF-{ arg where)) 0)))
1645 ;; Go backward to this function's header.
1646 (c-beginning-of-decl-1)
1649 ;; We're now there, modulo comments and whitespace.
1650 ;; Try to be line oriented; position point at the closest
1651 ;; preceding boi that isn't inside a comment, but if we hit
1652 ;; the previous declaration then we use the current point
1654 (while (and (/= (point) (c-point 'boi))
1655 (c-backward-single-comment)))
1656 (if (/= (point) (c-point 'boi))
1659 (c-keep-region-active)
1662 (defun c-forward-to-nth-EOF-} (n where)
1663 ;; Skip to the closing brace of the Nth function after point. If
1664 ;; point is inside a function, this counts as the first. Point must be
1665 ;; outside any comment/string or macro.
1667 ;; N must be strictly positive.
1668 ;; WHERE describes the position of point, one of the symbols `at-header',
1669 ;; `in-header', `in-block', `in-trailer', `at-function-end',
1670 ;; `outwith-function' as returned by c-where-wrt-brace-construct.
1672 ;; If we run out of functions, leave point at EOB. Return zero on success,
1673 ;; otherwise the number of }s still to go.
1675 ;; This function may do hidden buffer changes.
1678 ;; What we do to go forward over the first defun depends on where we
1679 ;; start. We go to the closing brace of that defun, even when we go
1680 ;; backwards to it (in a "struct foo {...} bar ;").
1682 ((eq where 'in-block)
1683 (goto-char (c-least-enclosing-brace (c-parse-state)))
1686 ((eq where 'in-trailer)
1687 (c-syntactic-skip-backward "^}")
1689 ((memq where '(at-function-end outwith-function at-header in-header))
1690 (when (c-syntactic-re-search-forward "{" nil 'eob)
1694 (t (error "c-forward-to-nth-EOF-}: `where' is %s" where)))
1696 ;; Each time round the loop, go forward to a "}" at the outermost level.
1697 (while (and (> n 0) (not (eobp)))
1698 ;(c-parse-state) ; This call speeds up the following one by a factor
1699 ; of ~6. Hmmm. 2006/4/5.
1700 (when (c-syntactic-re-search-forward "{" nil 'eob)
1706 (defun c-end-of-defun (&optional arg)
1707 "Move forward to the end of a top level declaration.
1708 With argument, do it that many times. Negative argument -N means move
1709 back to Nth preceding end. Returns t unless search stops due to
1710 beginning or end of buffer.
1712 An end of a defun occurs right after the close-parenthesis that matches
1713 the open-parenthesis that starts a defun; see `beginning-of-defun'."
1715 (or arg (setq arg 1))
1717 (or (not (eq this-command 'c-end-of-defun))
1718 (eq last-command 'c-end-of-defun)
1719 (c-region-is-active-p)
1722 (c-self-bind-state-cache ; c-state-cache's list structure must not be shared
1724 (c-save-buffer-state
1725 (beginning-of-defun-function
1726 end-of-defun-function
1728 (paren-state (c-parse-state))
1729 (orig-point-min (point-min)) (orig-point-max (point-max))
1731 where pos case-fold-search)
1734 (if (eq c-defun-tactic 'go-outward)
1735 (setq lim (c-widen-to-enclosing-decl-scope ; e.g. class, namespace
1736 paren-state orig-point-min orig-point-max)))
1738 ;; Move back out of any macro/comment/string we happen to be in.
1739 (c-beginning-of-macro)
1740 (setq pos (c-literal-limits))
1741 (if pos (goto-char (car pos)))
1743 (setq where (c-where-wrt-brace-construct))
1746 ;; Move backwards to the } of a function
1748 (if (memq where '(at-header outwith-function))
1749 (setq arg (1+ arg)))
1751 (c-while-widening-to-decl-block
1752 (< (setq arg (- (c-backward-to-nth-BOF-{ (- arg) where))) 0)))
1754 (c-while-widening-to-decl-block
1755 (progn (c-syntactic-skip-backward "^}")
1756 (not (eq (char-before) ?}))))))
1758 ;; Move forward to the } of a function
1760 (c-while-widening-to-decl-block
1761 (> (setq arg (c-forward-to-nth-EOF-} arg where)) 0))))
1763 ;; Do we need to move forward from the brace to the semicolon?
1765 (if (c-in-function-trailer-p) ; after "}" of struct/enum, etc.
1766 (c-syntactic-re-search-forward ";"))
1769 ;; We're there now, modulo comments and whitespace.
1770 ;; Try to be line oriented; position point after the next
1771 ;; newline that isn't inside a comment, but if we hit the
1772 ;; next declaration then we use the current point instead.
1773 (while (and (not (bolp))
1774 (not (looking-at "\\s *$"))
1775 (c-forward-single-comment)))
1777 ((looking-at "\\s *$")
1782 (c-keep-region-active)
1785 (defun c-defun-name ()
1786 "Return the name of the current defun, or NIL if there isn't one.
1787 \"Defun\" here means a function, or other top level construct
1788 with a brace block."
1790 (c-save-buffer-state
1791 (beginning-of-defun-function end-of-defun-function
1792 where pos name-end case-fold-search)
1797 ;; Move back out of any macro/comment/string we happen to be in.
1798 (c-beginning-of-macro)
1799 (setq pos (c-literal-limits))
1800 (if pos (goto-char (car pos)))
1802 (setq where (c-where-wrt-brace-construct))
1804 ;; Move to the beginning of the current defun, if any, if we're not
1806 (if (eq where 'outwith-function)
1808 (unless (eq where 'at-header)
1809 (c-backward-to-nth-BOF-{ 1 where)
1810 (c-beginning-of-decl-1))
1812 ;; Pick out the defun name, according to the type of defun.
1814 ;; struct, union, enum, or similar:
1815 ((and (looking-at c-type-prefix-key)
1816 (progn (c-forward-token-2 2) ; over "struct foo "
1817 (or (eq (char-after) ?\{)
1818 (looking-at c-symbol-key)))) ; "struct foo bar ..."
1819 (save-match-data (c-forward-token-2))
1820 (when (eq (char-after) ?\{)
1821 (c-backward-token-2)
1822 (looking-at c-symbol-key))
1823 (match-string-no-properties 0))
1825 ((looking-at "DEFUN\\s-*(") ;"DEFUN\\_>") think of XEmacs!
1826 ;; DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory, ...) ==> Ffile_name_directory
1827 ;; DEFUN(POSIX::STREAM-LOCK, stream lockp &key BLOCK SHARED START LENGTH) ==> POSIX::STREAM-LOCK
1829 (c-forward-syntactic-ws)
1830 (when (eq (char-after) ?\")
1832 (c-forward-token-2)) ; over the comma and following WS.
1833 (buffer-substring-no-properties
1837 (when (looking-at ":") ; CLISP: DEFUN(PACKAGE:LISP-SYMBOL,...)
1838 (skip-chars-forward "^,"))
1839 (c-backward-syntactic-ws)
1842 ((looking-at "DEF[a-zA-Z0-9_]* *( *\\([^, ]*\\) *,")
1843 ;; DEFCHECKER(sysconf_arg,prefix=_SC,default=, ...) ==> sysconf_arg
1844 ;; DEFFLAGSET(syslog_opt_flags,LOG_PID ...) ==> syslog_opt_flags
1845 (match-string-no-properties 1))
1848 ((assq 'objc-method-intro (c-guess-basic-syntax))
1849 (let ((bound (save-excursion (c-end-of-statement) (point)))
1850 (kw-re (concat "\\(?:" c-symbol-key "\\)?:"))
1852 (when (c-syntactic-re-search-forward c-symbol-key bound t t t)
1853 (push (match-string-no-properties 0) stretches)
1854 (while (c-syntactic-re-search-forward kw-re bound t t t)
1855 (push (match-string-no-properties 0) stretches)))
1856 (apply 'concat (nreverse stretches))))
1859 ;; Normal function or initializer.
1860 (when (c-syntactic-re-search-forward "[{(]" nil t)
1862 (c-backward-syntactic-ws)
1863 (when (eq (char-before) ?\=) ; struct foo bar = {0, 0} ;
1864 (c-backward-token-2)
1865 (c-backward-syntactic-ws))
1866 (setq name-end (point))
1867 (c-backward-token-2)
1868 (buffer-substring-no-properties (point) name-end)))))))))
1870 (defun c-declaration-limits (near)
1871 ;; Return a cons of the beginning and end positions of the current
1872 ;; top level declaration or macro. If point is not inside any then
1873 ;; nil is returned, unless NEAR is non-nil in which case the closest
1874 ;; following one is chosen instead (if there is any). The end
1875 ;; position is at the next line, providing there is one before the
1878 ;; This function might do hidden buffer changes.
1881 (when (eq c-defun-tactic 'go-outward)
1882 (c-narrow-to-most-enclosing-decl-block t) ; e.g. class, namespace
1883 (or (save-restriction
1884 (c-narrow-to-most-enclosing-decl-block nil)
1886 ;; Note: Some code duplication in `c-beginning-of-defun' and
1887 ;; `c-end-of-defun'.
1889 (let ((start (point))
1890 (paren-state (c-parse-state))
1893 (goto-char (c-least-enclosing-brace paren-state))
1894 ;; If we moved to the outermost enclosing paren
1895 ;; then we can use c-safe-position to set the
1896 ;; limit. Can't do that otherwise since the
1897 ;; earlier paren pair on paren-state might very
1898 ;; well be part of the declaration we should go
1900 (setq lim (c-safe-position (point) paren-state))
1902 ;; At top level. Make sure we aren't inside a literal.
1903 (setq pos (c-literal-limits
1904 (c-safe-position (point) paren-state)))
1905 (if pos (goto-char (car pos))))
1907 (when (c-beginning-of-macro)
1916 (when (or (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1918 ;; We moved back over the previous defun. Skip to the next
1919 ;; one. Not using c-forward-syntactic-ws here since we
1920 ;; should not skip a macro. We can also be directly after
1921 ;; the block in a `c-opt-block-decls-with-vars-key'
1922 ;; declaration, but then we won't move significantly far
1925 (c-forward-comments)
1927 (when (and near (c-beginning-of-macro))
1935 (if (eobp) (throw 'exit nil))
1937 ;; Check if `c-beginning-of-decl-1' put us after the block in a
1938 ;; declaration that doesn't end there. We're searching back and
1939 ;; forth over the block here, which can be expensive.
1941 (if (and c-opt-block-decls-with-vars-key
1943 (c-backward-syntactic-ws)
1944 (eq (char-before) ?}))
1945 (eq (car (c-beginning-of-decl-1))
1949 (and (> (point) pos)
1950 (setq end-pos (point)))))
1954 (if (and (not near) (> (point) start))
1957 ;; Try to be line oriented; position the limits at the
1958 ;; closest preceding boi, and after the next newline, that
1959 ;; isn't inside a comment, but if we hit a neighboring
1960 ;; declaration then we instead use the exact declaration
1961 ;; limit in that direction.
1964 (while (and (/= (point) (c-point 'boi))
1965 (c-backward-single-comment)))
1966 (if (/= (point) (c-point 'boi))
1974 (while (and (not (bolp))
1975 (not (looking-at "\\s *$"))
1976 (c-forward-single-comment)))
1979 ((looking-at "\\s *$")
1985 (goto-char (point-min))
1986 (c-forward-decl-or-cast-1 -1 nil nil)
1987 (eq (char-after) ?\{)
1988 (cons (point-min) (point-max))))))))
1990 (defun c-mark-function ()
1991 "Put mark at end of the current top-level declaration or macro, point at beginning.
1992 If point is not inside any then the closest following one is
1993 chosen. Each successive call of this command extends the marked
1994 region by one function.
1996 A mark is left where the command started, unless the region is already active
1997 \(in Transient Mark mode).
1999 As opposed to \\[c-beginning-of-defun] and \\[c-end-of-defun], this
2000 function does not require the declaration to contain a brace block."
2003 (let (decl-limits case-fold-search)
2004 (c-save-buffer-state nil
2005 ;; We try to be line oriented, unless there are several
2006 ;; declarations on the same line.
2007 (if (looking-at c-syntactic-eol)
2008 (c-backward-token-2 1 nil (c-point 'bol)))
2009 (setq decl-limits (c-declaration-limits t)))
2011 (if (not decl-limits)
2012 (error "Cannot find any declaration")
2013 (let* ((extend-region-p
2014 (and (eq this-command 'c-mark-function)
2015 (eq last-command 'c-mark-function)))
2016 (push-mark-p (and (eq this-command 'c-mark-function)
2017 (not extend-region-p)
2018 (not (c-region-is-active-p)))))
2019 (if push-mark-p (push-mark (point)))
2022 (exchange-point-and-mark)
2023 (setq decl-limits (c-declaration-limits t))
2024 (when (not decl-limits)
2025 (exchange-point-and-mark)
2026 (error "Cannot find any declaration"))
2027 (goto-char (cdr decl-limits))
2028 (exchange-point-and-mark))
2029 (goto-char (car decl-limits))
2030 (push-mark (cdr decl-limits) nil t))))))
2032 (defun c-cpp-define-name ()
2033 "Return the name of the current CPP macro, or NIL if we're not in one."
2035 (let (case-fold-search)
2037 (and c-opt-cpp-macro-define-start
2038 (c-beginning-of-macro)
2039 (looking-at c-opt-cpp-macro-define-start)
2040 (match-string-no-properties 1)))))
2043 ;; Movement by statements.
2044 (defun c-in-comment-line-prefix-p ()
2045 ;; Point is within a comment. Is it also within a comment-prefix?
2046 ;; Space at BOL which precedes a comment-prefix counts as part of it.
2048 ;; This function might do hidden buffer changes.
2049 (let ((here (point)))
2052 (skip-chars-forward " \t")
2053 (and (looking-at c-current-comment-prefix)
2054 (/= (match-beginning 0) (match-end 0))
2055 (< here (match-end 0))))))
2057 (defun c-narrow-to-comment-innards (range)
2058 ;; Narrow to the "inside" of the comment (block) defined by range, as
2061 ;; A c-style block comment has its opening "/*" and its closing "*/" (if
2062 ;; present) removed. A c++-style line comment retains its opening "//" but
2063 ;; has any final NL removed. If POINT is currently outwith these innards,
2064 ;; move it to the appropriate boundary.
2066 ;; This narrowing simplifies the sentence movement functions, since it
2067 ;; eliminates awkward things at the boundaries of the comment (block).
2069 ;; This function might do hidden buffer changes.
2070 (let* ((lit-type (c-literal-type range))
2071 (beg (if (eq lit-type 'c) (+ (car range) 2) (car range)))
2072 (end (if (eq lit-type 'c)
2073 (if (and (eq (char-before (cdr range)) ?/)
2074 (eq (char-before (1- (cdr range))) ?*))
2077 (if (eq (cdr range) (point-max))
2079 (- (cdr range) 1)))))
2081 (goto-char end)) ; This would be done automatically by ...
2083 (goto-char beg)) ; ... narrow-to-region but is not documented.
2084 (narrow-to-region beg end)))
2086 (defun c-beginning-of-sentence-in-comment (range)
2087 ;; Move backwards to the "beginning of a sentence" within the comment
2088 ;; defined by RANGE, a cons of its starting and ending positions. If we
2089 ;; find a BOS, return NIL. Otherwise, move point to just before the start
2090 ;; of the comment and return T.
2092 ;; The BOS is either text which follows a regexp match of sentence-end,
2093 ;; or text which is a beginning of "paragraph".
2094 ;; Comment-prefixes are treated like WS when calculating BOSes or BOPs.
2096 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2097 ;; It is not a general function, but is intended only for calling from
2098 ;; c-move-over-sentence. Not all preconditions have been explicitly stated.
2100 ;; This function might do hidden buffer changes.
2102 (let ((start-point (point)))
2104 (c-narrow-to-comment-innards range) ; This may move point back.
2105 (let* ((here (point))
2107 (here-filler ; matches WS and comment-prefixes at point.
2108 (concat "\\=\\(^[ \t]*\\(" c-current-comment-prefix "\\)"
2109 "\\|[ \t\n\r\f]\\)*"))
2110 (prefix-at-bol-here ; matches WS and prefix at BOL, just before point
2111 (concat "^[ \t]*\\(" c-current-comment-prefix "\\)[ \t\n\r\f]*\\="))
2112 ;; First, find the previous paragraph start, if any.
2113 (par-beg ; point where non-WS/non-prefix text of paragraph starts.
2115 (forward-paragraph -1) ; uses cc-mode values of
2116 ; paragraph-\(start\|separate\)
2117 (if (> (re-search-forward here-filler nil t) here)
2119 (when (>= (point) here)
2120 (forward-paragraph -2)
2121 (if (> (re-search-forward here-filler nil t) here)
2125 ;; Now seek successively earlier sentence ends between PAR-BEG and
2126 ;; HERE, until the "start of sentence" following it is earlier than
2127 ;; HERE, or we hit PAR-BEG. Beware of comment prefixes!
2128 (while (and (re-search-backward (c-sentence-end) par-beg 'limit)
2130 (goto-char (match-end 0)) ; tentative beginning of sentence
2131 (or (>= (point) here)
2132 (and (not (bolp)) ; Found a non-blank comment-prefix?
2134 (if (re-search-backward prefix-at-bol-here nil t)
2135 (/= (match-beginning 1) (match-end 1)))))
2136 (progn ; Skip the crud to find a real b-o-s.
2137 (if (c-in-comment-line-prefix-p)
2138 (beginning-of-line))
2139 (re-search-forward here-filler) ; always succeeds.
2140 (>= (point) here))))
2142 (re-search-forward here-filler)))
2144 (if (< (point) start-point)
2146 (goto-char (car range))
2149 (defun c-end-of-sentence-in-comment (range)
2150 ;; Move forward to the "end of a sentence" within the comment defined by
2151 ;; RANGE, a cons of its starting and ending positions (enclosing the opening
2152 ;; comment delimiter and the terminating */ or newline). If we find an EOS,
2153 ;; return NIL. Otherwise, move point to just after the end of the comment
2156 ;; The EOS is just after the non-WS part of the next match of the regexp
2157 ;; sentence-end. Typically, this is just after one of [.!?]. If there is
2158 ;; no sentence-end match following point, any WS before the end of the
2159 ;; comment will count as EOS, providing we're not already in it.
2161 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2162 ;; It is not a general function, but is intended only for calling from
2163 ;; c-move-over-sentence.
2165 ;; This function might do hidden buffer changes.
2167 (let ((start-point (point))
2168 ;; (lit-type (c-literal-type range)) ; Commented out, 2005/11/23, ACM
2171 (c-narrow-to-comment-innards range) ; This might move point forwards.
2172 (let* ((here (point))
2173 (par-end ; EOL position of last text in current/next paragraph.
2175 ;; The cc-mode values of paragraph-\(start\|separate\), set
2176 ;; in c-setup-paragraph-variables, are used in the
2178 (forward-paragraph 1)
2179 (if (eq (preceding-char) ?\n) (forward-char -1))
2180 (when (<= (point) here) ; can happen, e.g., when HERE is at EOL.
2182 (forward-paragraph 2)
2183 (if (eq (preceding-char) ?\n) (forward-char -1)))
2188 (concat "^[ \t]*\\(" c-current-comment-prefix "\\)\\=")))
2189 ;; Go forward one "comment-prefix which looks like sentence-end"
2190 ;; each time round the following:
2191 (while (and (re-search-forward (c-sentence-end) par-end 'limit)
2194 (skip-chars-backward " \t\n")
2195 (or (and (not (bolp))
2196 (re-search-backward prefix-at-bol-here nil t)
2197 (/= (match-beginning 1) (match-end 1)))
2198 (<= (point) here))))
2201 ;; Take special action if we're up against the end of a comment (of
2202 ;; either sort): Leave point just after the last non-ws text.
2203 (if (eq (point) (point-max))
2204 (while (or (/= (skip-chars-backward " \t\n") 0)
2205 (and (re-search-backward prefix-at-bol-here nil t)
2206 (/= (match-beginning 1) (match-end 1))))))))
2208 (if (> (point) start-point)
2210 (goto-char (cdr range))
2213 (defun c-beginning-of-sentence-in-string (range)
2214 ;; Move backwards to the "beginning of a sentence" within the string defined
2215 ;; by RANGE, a cons of its starting and ending positions (enclosing the
2216 ;; string quotes). If we find a BOS, return NIL. Otherwise, move point to
2217 ;; just before the start of the string and return T.
2219 ;; The BOS is either the text which follows a regexp match of sentence-end
2220 ;; or text which is a beginning of "paragraph". For the purposes of
2221 ;; determining paragraph boundaries, escaped newlines are treated as
2222 ;; ordinary newlines.
2224 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2225 ;; It is not a general function, but is intended only for calling from
2226 ;; c-move-over-sentence.
2228 ;; This function might do hidden buffer changes.
2230 (let* ((here (point)) last
2231 (end (1- (cdr range)))
2232 (here-filler ; matches WS and escaped newlines at point.
2233 "\\=\\([ \t\n\r\f]\\|\\\\[\n\r]\\)*")
2234 ;; Enhance paragraph-start and paragraph-separate also to recognize
2235 ;; blank lines terminated by escaped EOLs. IT MAY WELL BE that
2236 ;; these values should be customizable user options, or something.
2237 (paragraph-start c-string-par-start)
2238 (paragraph-separate c-string-par-separate)
2240 (par-beg ; beginning of current (or previous) paragraph.
2243 (narrow-to-region (1+ (car range)) end)
2244 (forward-paragraph -1) ; uses above values of
2245 ; paragraph-\(start\|separate\)
2246 (if (> (re-search-forward here-filler nil t) here)
2248 (when (>= (point) here)
2249 (forward-paragraph -2)
2250 (if (> (re-search-forward here-filler nil t) here)
2253 ;; Now see if we can find a sentence end after PAR-BEG.
2254 (while (and (re-search-backward c-sentence-end-with-esc-eol par-beg 'limit)
2256 (goto-char (match-end 0))
2260 here-filler end t) ; always succeeds. Use end rather
2261 ; than here, in case point starts
2262 ; beyond the closing quote.
2263 (>= (point) here))))
2265 (re-search-forward here-filler here t)
2266 (if (< (point) here)
2268 (goto-char (car range))
2271 (defun c-end-of-sentence-in-string (range)
2272 ;; Move forward to the "end of a sentence" within the string defined by
2273 ;; RANGE, a cons of its starting and ending positions. If we find an EOS,
2274 ;; return NIL. Otherwise, move point to just after the end of the string
2277 ;; The EOS is just after the non-WS part of the next match of the regexp
2278 ;; sentence-end. Typically, this is just after one of [.!?]. If there is
2279 ;; no sentence-end match following point, any WS before the end of the
2280 ;; string will count as EOS, providing we're not already in it.
2282 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2283 ;; It is not a general function, but is intended only for calling from
2284 ;; c-move-over-sentence.
2286 ;; This function might do hidden buffer changes.
2288 (let* ((here (point))
2290 ;; Enhance paragraph-start and paragraph-separate to recognize
2291 ;; blank lines terminated by escaped EOLs.
2292 (paragraph-start c-string-par-start)
2293 (paragraph-separate c-string-par-separate)
2295 (par-end ; EOL position of last text in current/next paragraph.
2298 (narrow-to-region (car range) (1- (cdr range)))
2299 ;; The above values of paragraph-\(start\|separate\) are used
2300 ;; in the following.
2301 (forward-paragraph 1)
2303 ;; (re-search-backward filler-here nil t) would find an empty
2304 ;; string. Therefore we simulate it by the following:
2305 (while (or (/= (skip-chars-backward " \t\n\r\f") 0)
2306 (re-search-backward "\\\\\\($\\)\\=" nil t)))
2307 (unless (> (point) here)
2309 (forward-paragraph 1)
2310 (while (or (/= (skip-chars-backward " \t\n\r\f") 0)
2311 (re-search-backward "\\\\\\($\\)\\=" nil t))))
2313 ;; Try to go forward a sentence.
2314 (when (re-search-forward c-sentence-end-with-esc-eol par-end 'limit)
2316 (while (or (/= (skip-chars-backward " \t\n") 0)
2317 (re-search-backward "\\\\\\($\\)\\=" nil t))))
2318 ;; Did we move a sentence, or did we hit the end of the string?
2319 (if (> (point) here)
2321 (goto-char (cdr range))
2324 (defun c-ascertain-preceding-literal ()
2325 ;; Point is not in a literal (i.e. comment or string (include AWK regexp)).
2326 ;; If a literal is the next thing (aside from whitespace) to be found before
2327 ;; point, return a cons of its start.end positions (enclosing the
2328 ;; delimiters). Otherwise return NIL.
2330 ;; This function might do hidden buffer changes.
2332 (c-collect-line-comments
2333 (let ((here (point))
2335 (if (c-backward-single-comment)
2336 (cons (point) (progn (c-forward-single-comment) (point)))
2338 ;; to prevent `looking-at' seeing a " at point.
2339 (narrow-to-region (point-min) here)
2342 ;; An EOL can act as an "open string" terminator in AWK.
2343 (looking-at c-ws*-string-limit-regexp)
2345 (progn (backward-char)
2346 (looking-at c-string-limit-regexp))))
2347 (goto-char (match-end 0)) ; just after the string terminator.
2349 (c-safe (c-backward-sexp 1) ; move back over the string.
2350 (cons (point) pos)))))))))
2352 (defun c-ascertain-following-literal ()
2353 ;; Point is not in a literal (i.e. comment or string (include AWK regexp)).
2354 ;; If a literal is the next thing (aside from whitespace) following point,
2355 ;; return a cons of its start.end positions (enclosing the delimiters).
2356 ;; Otherwise return NIL.
2358 ;; This function might do hidden buffer changes.
2360 (c-collect-line-comments
2363 (if (looking-at c-string-limit-regexp) ; string-delimiter.
2364 (cons (point) (or (c-safe (progn (c-forward-sexp 1) (point)))
2367 (if (c-forward-single-comment)
2368 (cons pos (point))))))))
2370 (defun c-after-statement-terminator-p () ; Should we pass in LIM here?
2371 ;; Does point immediately follow a statement "terminator"? A virtual
2372 ;; semicolon is regarded here as such. So is an opening brace ;-)
2374 ;; This function might do hidden buffer changes.
2377 (and (looking-at "[;{}]")
2378 (not (and c-special-brace-lists ; Pike special brace lists.
2379 (eq (char-after) ?{)
2380 (c-looking-at-special-brace-list)))))
2382 ;; The following (for macros) is not strict about exactly where we are
2383 ;; wrt white space at the end of the macro. Doesn't seem to matter too
2384 ;; much. ACM 2004/3/29.
2387 (if (c-beginning-of-macro)
2388 (setq eom (progn (c-end-of-macro)
2392 (c-forward-comments)
2393 (>= (point) eom))))))
2395 (defun c-back-over-illiterals (macro-start)
2396 ;; Move backwards over code which isn't a literal (i.e. comment or string),
2397 ;; stopping before reaching BOB or a literal or the boundary of a
2398 ;; preprocessor statement or the "beginning of a statement". MACRO-START is
2399 ;; the position of the '#' beginning the current preprocessor directive, or
2400 ;; NIL if we're not in such.
2402 ;; Return a cons (A.B), where
2403 ;; A is NIL if we moved back to a BOS (and know it), T otherwise (we
2404 ;; didn't move, or we hit a literal, or we're not sure about BOS).
2405 ;; B is MACRO-BOUNDARY if we are about to cross the boundary out of or
2406 ;; into a macro, otherwise LITERAL if we've hit a literal, otherwise NIL
2408 ;; The total collection of returned values is as follows:
2409 ;; (nil . nil): Found a BOS whilst remaining inside the illiterals.
2410 ;; (t . literal): No BOS found: only a comment/string. We _might_ be at
2411 ;; a BOS - the caller must check this.
2412 ;; (nil . macro-boundary): only happens with non-nil macro-start. We've
2413 ;; moved and reached the opening # of the macro.
2414 ;; (t . macro-boundary): Every other circumstance in which we're at a
2415 ;; macro-boundary. We might be at a BOS.
2417 ;; Point is left either at the beginning-of-statement, or at the last non-ws
2418 ;; code before encountering the literal/BOB or macro-boundary.
2420 ;; Note that this function moves within either preprocessor commands
2421 ;; (macros) or normal code, but will not cross a boundary between the two,
2422 ;; or between two distinct preprocessor commands.
2424 ;; Stop before `{' and after `;', `{', `}' and `};' when not followed by `}'
2425 ;; or `)', but on the other side of the syntactic ws. Move by sexps and
2426 ;; move into parens. Also stop before `#' when it's at boi on a line.
2428 ;; This function might do hidden buffer changes.
2430 (let ((here (point))
2431 last) ; marks the position of non-ws code, what'll be BOS if, say, a
2432 ; semicolon precedes it.
2434 (while t ;; We go back one "token" each iteration of the loop.
2437 ;; Stop at the token after a comment.
2438 ((c-backward-single-comment) ; Also functions as backwards-ws.
2440 (throw 'done '(t . literal)))
2442 ;; If we've gone back over a LF, we might have moved into or out of
2443 ;; a preprocessor line.
2444 ((and (save-excursion
2446 (re-search-forward "\\(^\\|[^\\]\\)[\n\r]" last t))
2448 (< (point) macro-start)
2449 (c-beginning-of-macro)))
2451 ;; Return a car of NIL ONLY if we've hit the opening # of a macro.
2452 (throw 'done (cons (or (eq (point) here)
2456 ;; Have we found a virtual semicolon? If so, stop, unless the next
2457 ;; statement is where we started from.
2458 ((and (c-at-vsemi-p)
2460 (not (memq (char-after last) '(?\) ?})))) ; we've moved back from ) or }
2462 (throw 'done '(nil . nil)))
2464 ;; Hit the beginning of the buffer/region?
2468 (throw 'done '(nil . nil)))
2470 ;; Move back a character.
2471 ((progn (backward-char) nil))
2473 ;; Stop at "{" (unless it's a PIKE special brace list.)
2474 ((eq (char-after) ?\{)
2475 (if (and c-special-brace-lists
2476 (c-looking-at-special-brace-list))
2477 (skip-syntax-backward "w_") ; Speedup only.
2480 (throw 'done '(nil . nil))))
2482 ;; Have we reached the start of a macro? This always counts as
2483 ;; BOS. (N.B. I don't think (eq (point) here) can ever be true
2484 ;; here. FIXME!!! ACM 2004/3/29)
2485 ((and macro-start (eq (point) macro-start))
2486 (throw 'done (cons (eq (point) here) 'macro-boundary)))
2488 ;; Stop at token just after "}" or ";".
2489 ((looking-at "[;}]")
2490 ;; If we've gone back over ;, {, or }, we're done.
2491 (if (or (= here last)
2492 (memq (char-after last) '(?\) ?}))) ; we've moved back from ) or }
2493 (if (and (eq (char-before) ?}) ; If };, treat them as a unit.
2494 (eq (char-after) ?\;))
2496 (goto-char last) ; To the statement starting after the ; or }.
2497 (throw 'done '(nil . nil))))
2499 ;; Stop at the token after a string.
2500 ((looking-at c-string-limit-regexp) ; Just gone back over a string terminator?
2502 (throw 'done '(t . literal)))
2504 ;; Nothing special: go back word characters.
2505 (t (skip-syntax-backward "w_")) ; Speedup only.
2508 (defun c-forward-over-illiterals (macro-end allow-early-stop)
2509 ;; Move forwards over code, stopping before reaching EOB or a literal
2510 ;; (i.e. a comment/string) or the boundary of a preprocessor statement or
2511 ;; the "end of a statement". MACRO-END is the position of the EOL/EOB which
2512 ;; terminates the current preprocessor directive, or NIL if we're not in
2515 ;; ALLOW-EARLY-STOP is non-nil if it is permissible to return without moving
2516 ;; forward at all, should we encounter a `{'. This is an ugly kludge, but
2517 ;; seems unavoidable. Depending on the context this function is called
2518 ;; from, we _sometimes_ need to stop there. Currently (2004/4/3),
2519 ;; ALLOW-EARLY-STOP is applied only to open braces, not to virtual
2520 ;; semicolons, or anything else.
2522 ;; Return a cons (A.B), where
2523 ;; A is NIL if we moved forward to an EOS, or stay at one (when
2524 ;; ALLOW-EARLY-STOP is set), T otherwise (we hit a literal).
2525 ;; B is 'MACRO-BOUNDARY if we are about to cross the boundary out of or
2526 ;; into a macro, otherwise 'LITERAL if we've hit a literal, otherwise NIL
2528 ;; Point is left either after the end-of-statement, or at the last non-ws
2529 ;; code before encountering the literal, or the # of the preprocessor
2530 ;; statement, or at EOB [or just after last non-WS stuff??].
2532 ;; As a clarification of "after the end-of-statement", if a comment or
2533 ;; whitespace follows a completed AWK statement, that statement is treated
2534 ;; as ending just after the last non-ws character before the comment.
2536 ;; Note that this function moves within either preprocessor commands
2537 ;; (macros) or normal code, but not both within the same invocation.
2539 ;; Stop before `{', `}', and `#' when it's at boi on a line, but on the
2540 ;; other side of the syntactic ws, and after `;', `}' and `};'. Only
2541 ;; stop before `{' if at top level or inside braces, though. Move by
2542 ;; sexps and move into parens. Also stop at eol of lines with `#' at
2545 ;; This function might do hidden buffer changes.
2546 (let ((here (point))
2549 (while t ;; We go one "token" forward each time round this loop.
2552 ;; If we've moved forward to a virtual semicolon, we're done.
2553 (if (and (> last here) ; Should we check ALLOW-EARLY-STOP, here? 2004/4/3
2555 (throw 'done '(nil . nil)))
2559 ;; Gone past the end of a macro?
2560 ((and macro-end (> (point) macro-end))
2562 (throw 'done (cons (eq (point) here) 'macro-boundary)))
2564 ;; About to hit a comment?
2565 ((save-excursion (c-forward-single-comment))
2567 (throw 'done '(t . literal)))
2573 (throw 'done '(nil . nil)))
2575 ;; If we encounter a '{', stop just after the previous token.
2576 ((and (eq (char-after) ?{)
2577 (not (and c-special-brace-lists
2578 (c-looking-at-special-brace-list)))
2579 (or allow-early-stop (/= here last))
2580 (save-excursion ; Is this a check that we're NOT at top level?
2581 ;;;; NO! This seems to check that (i) EITHER we're at the top level; OR (ii) The next enclosing
2582 ;;;; level of bracketing is a '{'. HMM. Doesn't seem to make sense.
2583 ;;;; 2003/8/8 This might have something to do with the GCC extension "Statement Expressions", e.g.
2584 ;;;; while ({stmt1 ; stmt2 ; exp ;}). This form excludes such Statement Expressions.
2585 (or (not (c-safe (up-list -1) t))
2586 (= (char-after) ?{))))
2588 (throw 'done '(nil . nil)))
2590 ;; End of a PIKE special brace list? If so, step over it and continue.
2591 ((and c-special-brace-lists
2592 (eq (char-after) ?})
2594 (and (c-safe (up-list -1) t)
2595 (c-looking-at-special-brace-list))))
2597 (skip-syntax-forward "w_")) ; Speedup only.
2599 ;; Have we got a '}' after having moved? If so, stop after the
2601 ((and (eq (char-after) ?})
2604 (throw 'done '(nil . nil)))
2606 ;; Stop if we encounter a preprocessor line. Continue if we
2608 ((and c-opt-cpp-prefix
2610 (eq (char-after) ?#)
2611 (= (point) (c-point 'boi)))
2612 (if (= (point) here) ; Not a macro, therefore naked #.
2614 (throw 'done '(t . macro-boundary))))
2616 ;; Stop after a ';', '}', or "};"
2617 ((looking-at ";\\|};?")
2618 (goto-char (match-end 0))
2619 (throw 'done '(nil . nil)))
2621 ;; Found a string (this subsumes AWK regexps)?
2622 ((looking-at c-string-limit-regexp)
2624 (throw 'done '(t . literal)))
2627 (forward-char) ; Can't fail - we checked (eobp) earlier on.
2628 (skip-syntax-forward "w_") ; Speedup only.
2629 (when (and macro-end (> (point) macro-end))
2631 (throw 'done (cons (eq (point) here) 'macro-boundary))))
2634 (defun c-one-line-string-p (range)
2635 ;; Is the literal defined by RANGE a string contained in a single line?
2637 ;; This function might do hidden buffer changes.
2639 (goto-char (car range))
2640 (and (looking-at c-string-limit-regexp)
2641 (progn (skip-chars-forward "^\n" (cdr range))
2642 (eq (point) (cdr range))))))
2644 (defun c-beginning-of-statement (&optional count lim sentence-flag)
2645 "Go to the beginning of the innermost C statement.
2646 With prefix arg, go back N - 1 statements. If already at the
2647 beginning of a statement then go to the beginning of the closest
2648 preceding one, moving into nested blocks if necessary (use
2649 \\[backward-sexp] to skip over a block). If within or next to a
2650 comment or multiline string, move by sentences instead of statements.
2652 When called from a program, this function takes 3 optional args: the
2653 repetition count, a buffer position limit which is the farthest back
2654 to search for the syntactic context, and a flag saying whether to do
2655 sentence motion in or near comments and multiline strings.
2657 Note that for use in programs, `c-beginning-of-statement-1' is
2658 usually better. It has much better defined semantics than this one,
2659 which is intended for interactive use, and might therefore change to
2660 be more \"DWIM:ey\"."
2661 (interactive (list (prefix-numeric-value current-prefix-arg)
2664 (c-end-of-statement (- count) lim sentence-flag)
2665 (c-save-buffer-state
2666 ((count (or count 1))
2667 last ; start point for going back ONE chunk. Updated each chunk movement.
2669 (save-excursion (and (not (bobp)) (c-beginning-of-macro) (point))))
2670 res ; result from sub-function call
2671 not-bos ; "not beginning-of-statement"
2672 (range (c-collect-line-comments (c-literal-limits lim)))) ; (start.end) of current literal or NIL
2674 ;; Go back one statement at each iteration of the following loop.
2675 (while (and (/= count 0)
2676 (or (not lim) (> (point) lim)))
2677 ;; Go back one "chunk" each time round the following loop, stopping
2678 ;; when we reach a statement boundary, etc.
2681 (cond ; Each arm of this cond returns NIL on reaching a desired
2682 ; statement boundary, non-NIL otherwise.
2687 (range ; point is within or approaching a literal.
2689 ;; Single line string or sentence-flag is null => skip the
2691 ((or (null sentence-flag)
2692 (c-one-line-string-p range))
2693 (goto-char (car range))
2694 (setq range (c-ascertain-preceding-literal))
2695 ;; N.B. The following is essentially testing for an AWK regexp
2697 ;; Was the previous non-ws thing an end of statement?
2700 (c-backward-comments)
2701 (c-backward-syntactic-ws))
2702 (not (or (bobp) (c-after-statement-terminator-p)))))
2704 ;; Comment inside a statement or a multi-line string.
2705 (t (when (setq res ; returns non-nil when we go out of the literal
2706 (if (eq (c-literal-type range) 'string)
2707 (c-beginning-of-sentence-in-string range)
2708 (c-beginning-of-sentence-in-comment range)))
2709 (setq range (c-ascertain-preceding-literal)))
2712 ;; Non-literal code.
2713 (t (setq res (c-back-over-illiterals macro-fence))
2714 (setq not-bos ; "not reached beginning-of-statement".
2715 (or (= (point) last)
2716 (memq (char-after) '(?\) ?\}))
2719 ;; We're at a tentative BOS. The next form goes
2720 ;; back over WS looking for an end of previous
2722 (not (save-excursion
2724 (c-backward-comments)
2725 (c-backward-syntactic-ws))
2726 (or (bobp) (c-after-statement-terminator-p)))))))
2727 ;; Are we about to move backwards into or out of a
2728 ;; preprocessor command? If so, locate its beginning.
2729 (when (eq (cdr res) 'macro-boundary)
2734 (progn (c-skip-ws-backward) (c-beginning-of-macro))
2736 ;; Are we about to move backwards into a literal?
2737 (when (memq (cdr res) '(macro-boundary literal))
2738 (setq range (c-ascertain-preceding-literal)))
2740 (setq last (point)))
2742 (if (/= count 0) (setq count (1- count))))
2743 (c-keep-region-active))))
2745 (defun c-end-of-statement (&optional count lim sentence-flag)
2746 "Go to the end of the innermost C statement.
2747 With prefix arg, go forward N - 1 statements. Move forward to the end
2748 of the next statement if already at end, and move into nested blocks
2749 \(use \\[forward-sexp] to skip over a block). If within or next to a
2750 comment or multiline string, move by sentences instead of statements.
2752 When called from a program, this function takes 3 optional args: the
2753 repetition count, a buffer position limit which is the farthest back
2754 to search for the syntactic context, and a flag saying whether to do
2755 sentence motion in or near comments and multiline strings."
2756 (interactive (list (prefix-numeric-value current-prefix-arg)
2758 (setq count (or count 1))
2759 (if (< count 0) (c-beginning-of-statement (- count) lim sentence-flag)
2761 (c-save-buffer-state
2762 (here ; start point for going forward ONE statement. Updated each statement.
2765 (and (not (eobp)) (c-beginning-of-macro)
2766 (progn (c-end-of-macro) (point)))))
2768 (range (c-collect-line-comments (c-literal-limits lim)))) ; (start.end) of current literal or NIL
2770 ;; Go back/forward one statement at each iteration of the following loop.
2771 (while (and (/= count 0)
2772 (or (not lim) (< (point) lim)))
2773 (setq here (point)) ; ONLY HERE is HERE updated
2775 ;; Go forward one "chunk" each time round the following loop, stopping
2776 ;; when we reach a statement boundary, etc.
2778 (cond ; Each arm of this cond returns NIL on reaching a desired
2779 ; statement boundary, non-NIL otherwise.
2784 (range ; point is within a literal.
2786 ;; sentence-flag is null => skip the entire literal.
2787 ;; or a Single line string.
2788 ((or (null sentence-flag)
2789 (c-one-line-string-p range))
2790 (goto-char (cdr range))
2791 (setq range (c-ascertain-following-literal))
2792 ;; Is there a virtual semicolon here (e.g. for AWK)?
2793 (not (c-at-vsemi-p)))
2795 ;; Comment or multi-line string.
2796 (t (when (setq res ; gets non-nil when we go out of the literal
2797 (if (eq (c-literal-type range) 'string)
2798 (c-end-of-sentence-in-string range)
2799 (c-end-of-sentence-in-comment range)))
2800 (setq range (c-ascertain-following-literal)))
2801 ;; If we've just come forward out of a literal, check for
2802 ;; vsemi. (N.B. AWK can't have a vsemi after a comment, but
2803 ;; some other language may do in the future)
2805 (not (c-at-vsemi-p))))))
2807 ;; Non-literal code.
2808 (t (setq res (c-forward-over-illiterals macro-fence
2810 ;; Are we about to move forward into or out of a
2811 ;; preprocessor command?
2812 (when (eq (cdr res) 'macro-boundary)
2819 (progn (c-skip-ws-forward)
2820 (c-beginning-of-macro))
2821 (progn (c-end-of-macro)
2824 (c-beginning-of-macro)
2825 (progn (c-end-of-macro) (point)))))))
2826 ;; Are we about to move forward into a literal?
2827 (when (memq (cdr res) '(macro-boundary literal))
2828 (setq range (c-ascertain-following-literal)))
2831 (if (/= count 0) (setq count (1- count))))
2832 (c-keep-region-active))))
2835 ;; set up electric character functions to work with pending-del,
2836 ;; (a.k.a. delsel) mode. All symbols get the t value except
2837 ;; the functions which delete, which gets 'supersede, and (from Emacs
2838 ;; 25) `c-electric-brace' and `c-electric-paren' get special handling
2839 ;; so as to work gracefully with `electric-pair-mode'.
2843 (put sym 'delete-selection t) ; for delsel (Emacs)
2844 (put sym 'pending-delete t))) ; for pending-del (XEmacs)
2848 c-electric-semi&comma
2854 (put sym 'delete-selection (if (fboundp 'delete-selection-uses-region-p)
2855 'delete-selection-uses-region-p
2857 (put sym 'pending-delete t)))
2860 (put 'c-electric-delete 'delete-selection 'supersede) ; delsel
2861 (put 'c-electric-delete 'pending-delete 'supersede) ; pending-del
2862 (put 'c-electric-backspace 'delete-selection 'supersede) ; delsel
2863 (put 'c-electric-backspace 'pending-delete 'supersede) ; pending-del
2864 (put 'c-electric-delete-forward 'delete-selection 'supersede) ; delsel
2865 (put 'c-electric-delete-forward 'pending-delete 'supersede) ; pending-del
2868 ;; Inserting/indenting comments
2869 (defun c-calc-comment-indent (entry)
2870 ;; This function might do hidden buffer changes.
2872 (setq entry (or (assq entry c-indent-comment-alist)
2873 (assq 'other c-indent-comment-alist)
2874 '(default . (column . nil)))))
2875 (let ((action (car (cdr entry)))
2876 (value (cdr (cdr entry)))
2877 (col (current-column)))
2878 (cond ((eq action 'space)
2880 ((eq action 'column)
2881 (unless value (setq value comment-column))
2883 ;; Do not pad with one space if we're at bol.
2885 (max (1+ col) value)))
2891 (let ((lim (c-literal-limits (c-point 'bol) t)))
2893 (goto-char (car lim))
2894 (when (looking-at "/[/*]") ; FIXME!!! Adapt for AWK! (ACM, 2005/11/18)
2895 ;; Found comment to align with.
2897 ;; Do not pad with one space if we're at bol.
2899 (max (1+ col) (current-column))))))))
2900 ;; Recurse to handle value as a new spec.
2901 (c-calc-comment-indent (cdr entry)))))))
2903 (defun c-comment-indent ()
2904 "Used by `indent-for-comment' to create and indent comments.
2905 See `c-indent-comment-alist' for a description."
2908 (c-save-buffer-state
2909 ((eot (let ((lim (c-literal-limits (c-point 'bol) t)))
2910 (or (when (consp lim)
2911 (goto-char (car lim))
2912 (when (looking-at "/[/*]")
2913 (skip-chars-backward " \t")
2916 (skip-chars-backward " \t")
2919 (cond ((looking-at "^/[/*]")
2921 ((progn (beginning-of-line)
2924 ((progn (back-to-indentation)
2925 (and (eq (char-after) ?})
2926 (eq (point) (1- eot))))
2928 ((and (looking-at "#[ \t]*\\(endif\\|else\\)")
2929 (eq (match-end 0) eot))
2934 (if (and (memq line-type '(anchored-comment empty-line))
2935 c-indent-comments-syntactically-p)
2936 (let ((c-syntactic-context (c-guess-basic-syntax)))
2937 ;; BOGOSITY ALERT: if we're looking at the eol, its
2938 ;; because indent-for-comment hasn't put the comment-start
2939 ;; in the buffer yet. this will screw up the syntactic
2940 ;; analysis so we kludge in the necessary info. Another
2941 ;; kludge is that if we're at the bol, then we really want
2942 ;; to ignore any anchoring as specified by
2943 ;; c-comment-only-line-offset since it doesn't apply here.
2945 (c-add-syntax 'comment-intro))
2946 (let ((c-comment-only-line-offset
2947 (if (consp c-comment-only-line-offset)
2948 c-comment-only-line-offset
2949 (cons c-comment-only-line-offset
2950 c-comment-only-line-offset))))
2951 (c-get-syntactic-indentation c-syntactic-context)))
2953 (c-calc-comment-indent line-type)))))
2956 ;; used by outline-minor-mode
2957 (defun c-outline-level ()
2958 (let (buffer-invisibility-spec);; This so that `current-column' DTRT
2959 ;; in otherwise-hidden text.
2961 (skip-chars-forward "\t ")
2965 ;; Movement by CPP conditionals.
2966 (defun c-up-conditional (count)
2967 "Move back to the containing preprocessor conditional, leaving mark behind.
2968 A prefix argument acts as a repeat count. With a negative argument,
2969 move forward to the end of the containing preprocessor conditional.
2971 \"#elif\" is treated like \"#else\" followed by \"#if\", so the
2972 function stops at them when going backward, but not when going
2975 (let ((new-point (c-scan-conditionals (- count) -1)))
2977 (goto-char new-point))
2978 (c-keep-region-active))
2980 (defun c-up-conditional-with-else (count)
2981 "Move back to the containing preprocessor conditional, including \"#else\".
2982 Just like `c-up-conditional', except it also stops at \"#else\"
2985 (let ((new-point (c-scan-conditionals (- count) -1 t)))
2987 (goto-char new-point))
2988 (c-keep-region-active))
2990 (defun c-down-conditional (count)
2991 "Move forward into the next preprocessor conditional, leaving mark behind.
2992 A prefix argument acts as a repeat count. With a negative argument,
2993 move backward into the previous preprocessor conditional.
2995 \"#elif\" is treated like \"#else\" followed by \"#if\", so the
2996 function stops at them when going forward, but not when going
2999 (let ((new-point (c-scan-conditionals count 1)))
3001 (goto-char new-point))
3002 (c-keep-region-active))
3004 (defun c-down-conditional-with-else (count)
3005 "Move forward into the next preprocessor conditional, including \"#else\".
3006 Just like `c-down-conditional', except it also stops at \"#else\"
3009 (let ((new-point (c-scan-conditionals count 1 t)))
3011 (goto-char new-point))
3012 (c-keep-region-active))
3014 (defun c-backward-conditional (count &optional target-depth with-else)
3015 "Move back across a preprocessor conditional, leaving mark behind.
3016 A prefix argument acts as a repeat count. With a negative argument,
3017 move forward across a preprocessor conditional.
3019 The optional arguments TARGET-DEPTH and WITH-ELSE are historical,
3020 and have the same meanings as in `c-scan-conditionals'. If you
3021 are calling c-forward-conditional from a program, you might want
3022 to call `c-scan-conditionals' directly instead."
3024 (let ((new-point (c-scan-conditionals (- count) target-depth with-else)))
3026 (goto-char new-point))
3027 (c-keep-region-active))
3029 (defun c-forward-conditional (count &optional target-depth with-else)
3030 "Move forward across a preprocessor conditional, leaving mark behind.
3031 A prefix argument acts as a repeat count. With a negative argument,
3032 move backward across a preprocessor conditional.
3034 If there aren't enough conditionals after \(or before) point, an
3037 \"#elif\" is treated like \"#else\" followed by \"#if\", except that
3038 the nesting level isn't changed when tracking subconditionals.
3040 The optional arguments TARGET-DEPTH and WITH-ELSE are historical,
3041 and have the same meanings as in `c-scan-conditionals'. If you
3042 are calling c-forward-conditional from a program, you might want
3043 to call `c-scan-conditionals' directly instead."
3045 (let ((new-point (c-scan-conditionals count target-depth with-else)))
3047 (goto-char new-point)))
3049 (defun c-scan-conditionals (count &optional target-depth with-else)
3050 "Scan forward across COUNT preprocessor conditionals.
3051 With a negative argument, scan backward across preprocessor
3052 conditionals. Return the end position. Point is not moved.
3054 If there aren't enough preprocessor conditionals, throw an error.
3056 \"#elif\" is treated like \"#else\" followed by \"#if\", except that
3057 the nesting level isn't changed when tracking subconditionals.
3059 The optional argument TARGET-DEPTH specifies the wanted nesting depth
3060 after each scan. E.g. if TARGET-DEPTH is -1, the end position will be
3061 outside the enclosing conditional. A non-integer non-nil TARGET-DEPTH
3064 If the optional argument WITH-ELSE is non-nil, \"#else\" directives
3065 are treated as conditional clause limits. Normally they are ignored."
3066 (let* ((forward (> count 0))
3067 (increment (if forward -1 1))
3068 (search-function (if forward 're-search-forward 're-search-backward))
3069 new case-fold-search)
3070 (unless (integerp target-depth)
3071 (setq target-depth (if target-depth -1 0)))
3075 ;; subdepth is the depth in "uninteresting" subtrees,
3076 ;; i.e. those that takes us farther from the target
3077 ;; depth instead of closer.
3081 ;; Find the "next" significant line in the proper direction.
3082 (while (and (not found)
3083 ;; Rather than searching for a # sign that
3084 ;; comes at the beginning of a line aside from
3085 ;; whitespace, search first for a string
3086 ;; starting with # sign. Then verify what
3087 ;; precedes it. This is faster on account of
3088 ;; the fastmap feature of the regexp matcher.
3089 (funcall search-function
3090 "#[ \t]*\\(if\\|elif\\|endif\\|else\\)"
3093 ;; Now verify it is really a preproc line.
3094 (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\|else\\)")
3095 (let (dchange (directive (match-string 1)))
3096 (cond ((string= directive "if")
3097 (setq dchange (- increment)))
3098 ((string= directive "endif")
3099 (setq dchange increment))
3101 ;; When we're not in an "uninteresting"
3102 ;; subtree, we might want to act on "elif"
3104 (if (cond (with-else
3105 ;; Always move toward the target depth.
3107 (if (> target-depth 0) 1 -1)))
3108 ((string= directive "elif")
3109 (setq dchange (- increment))))
3110 ;; Ignore the change if it'd take us
3111 ;; into an "uninteresting" subtree.
3112 (if (eq (> dchange 0) (<= target-depth 0))
3113 (setq dchange nil)))))
3115 (when (or (/= subdepth 0)
3116 (eq (> dchange 0) (<= target-depth 0)))
3117 (setq subdepth (+ subdepth dchange)))
3118 (setq depth (+ depth dchange))
3119 ;; If we are trying to move across, and we find an
3120 ;; end before we find a beginning, get an error.
3121 (if (and (< depth target-depth) (< dchange 0))
3123 "No following conditional at this level"
3124 "No previous conditional at this level"))))
3125 ;; When searching forward, start from next line so
3126 ;; that we don't find the same line again.
3127 (if forward (forward-line 1))
3128 ;; We found something if we've arrived at the
3130 (if (and dchange (= depth target-depth))
3131 (setq found (point))))
3133 (if forward (forward-line 1)))))
3135 (error "No containing preprocessor conditional"))
3136 (goto-char (setq new found)))
3137 (setq count (+ count increment))))
3138 (c-keep-region-active)
3142 ;; commands to indent lines, regions, defuns, and expressions
3143 (defun c-indent-command (&optional arg)
3144 "Indent current line as C code, and/or insert some whitespace.
3146 If `c-tab-always-indent' is t, always just indent the current line.
3147 If nil, indent the current line only if point is at the left margin or
3148 in the line's indentation; otherwise insert some whitespace[*]. If
3149 other than nil or t, then some whitespace[*] is inserted only within
3150 literals (comments and strings), but the line is always reindented.
3152 If `c-syntactic-indentation' is t, indentation is done according to
3153 the syntactic context. A numeric argument, regardless of its value,
3154 means indent rigidly all the lines of the expression starting after
3155 point so that this line becomes properly indented. The relative
3156 indentation among the lines of the expression is preserved.
3158 If `c-syntactic-indentation' is nil, the line is just indented one
3159 step according to `c-basic-offset'. In this mode, a numeric argument
3160 indents a number of such steps, positive or negative, and an empty
3161 prefix argument is equivalent to -1.
3163 [*] The amount and kind of whitespace inserted is controlled by the
3164 variable `c-insert-tab-function', which is called to do the actual
3165 insertion of whitespace. Normally the function in this variable
3166 just inserts a tab character, or the equivalent number of spaces,
3167 depending on the variable `indent-tabs-mode'."
3170 (let ((indent-function
3171 (if c-syntactic-indentation
3172 (symbol-function 'indent-according-to-mode)
3174 (let ((c-macro-start c-macro-start)
3175 (steps (if (equal arg '(4))
3177 (prefix-numeric-value arg))))
3178 (c-shift-line-indentation (* steps c-basic-offset))
3179 (when (and c-auto-align-backslashes
3182 (eq (char-before) ?\\))
3183 (c-query-and-set-macro-start))
3184 ;; Realign the line continuation backslash if inside a macro.
3185 (c-backslash-region (point) (point) nil t)))
3187 (if (and c-syntactic-indentation arg)
3188 ;; If c-syntactic-indentation and got arg, always indent this
3189 ;; line as C and shift remaining lines of expression the same
3191 (let ((shift-amt (save-excursion
3192 (back-to-indentation)
3196 (setq shift-amt (- (save-excursion
3197 (back-to-indentation)
3201 (if (eq c-tab-always-indent t)
3202 (beginning-of-line)) ; FIXME!!! What is this here for? ACM 2005/10/31
3210 (indent-code-rigidly beg end shift-amt "#")))
3211 ;; Else use c-tab-always-indent to determine behavior.
3213 ;; CASE 1: indent when at column zero or in line's indentation,
3214 ;; otherwise insert a tab
3215 ((not c-tab-always-indent)
3217 (skip-chars-backward " \t")
3219 (funcall c-insert-tab-function)
3220 (funcall indent-function)))
3221 ;; CASE 2: just indent the line
3222 ((eq c-tab-always-indent t)
3223 (funcall indent-function))
3224 ;; CASE 3: if in a literal, insert a tab, but always indent the
3227 (if (c-save-buffer-state () (c-in-literal))
3228 (funcall c-insert-tab-function))
3229 (funcall indent-function)
3232 (defun c-indent-exp (&optional shutup-p)
3233 "Indent each line in the balanced expression following point syntactically.
3234 If optional SHUTUP-P is non-nil, no errors are signaled if no
3235 balanced expression is found."
3237 (let ((here (point-marker))
3239 (set-marker-insertion-type here t)
3241 (let ((start (save-restriction
3242 ;; Find the closest following open paren that
3243 ;; ends on another line.
3244 (narrow-to-region (point-min) (c-point 'eol))
3245 (let (beg (end (point)))
3246 (while (and (setq beg (c-down-list-forward end))
3247 (setq end (c-up-list-forward beg))))
3249 (eq (char-syntax (char-before beg)) ?\()
3254 (error "Cannot find start of balanced expression to indent"))
3256 (setq end (c-safe (scan-sexps (point) 1)))
3259 (error "Cannot find end of balanced expression to indent"))
3262 (c-indent-region (point) end)))))
3264 (set-marker here nil))))
3266 (defun c-indent-defun ()
3267 "Indent the current top-level declaration or macro syntactically.
3268 In the macro case this also has the effect of realigning any line
3269 continuation backslashes, unless `c-auto-align-backslashes' is nil."
3271 (let ((here (point-marker)) decl-limits case-fold-search)
3274 (c-save-buffer-state nil
3275 ;; We try to be line oriented, unless there are several
3276 ;; declarations on the same line.
3277 (if (looking-at c-syntactic-eol)
3278 (c-backward-token-2 1 nil (c-point 'bol))
3279 (c-forward-token-2 0 nil (c-point 'eol)))
3280 (setq decl-limits (c-declaration-limits nil)))
3282 (c-indent-region (car decl-limits)
3283 (cdr decl-limits))))
3285 (set-marker here nil))))
3287 (defun c-indent-region (start end &optional quiet)
3288 "Indent syntactically every line whose first char is between START
3289 and END inclusive. If the optional argument QUIET is non-nil then no
3290 syntactic errors are reported, even if `c-report-syntactic-errors' is
3294 (skip-chars-backward " \t\n\r\f\v")
3297 ;; Advance to first nonblank line.
3299 (skip-chars-forward " \t\n\r\f\v")
3300 (setq start (point))
3302 (setq c-parsing-error
3303 (or (let ((endmark (copy-marker end))
3304 (c-parsing-error nil)
3305 ;; shut up any echo msgs on indiv lines
3306 (c-echo-syntactic-information-p nil)
3307 (ml-macro-start ; Start pos of multi-line macro.
3308 (and (c-save-buffer-state ()
3309 (save-excursion (c-beginning-of-macro)))
3310 (eq (char-before (c-point 'eol)) ?\\)
3312 (c-fix-backslashes nil)
3316 (c-progress-init start end 'c-indent-region)
3318 (while (and (bolp) ;; One line each time round the loop.
3320 (< (point) endmark))
3324 (unless (or (looking-at "\\s *$")
3325 (and ml-macro-start (looking-at "\\s *\\\\$")))
3326 ;; Get syntax and indent.
3327 (c-save-buffer-state nil
3328 (setq syntax (c-guess-basic-syntax)))
3329 (c-indent-line syntax t t))
3332 ;; End of current multi-line macro?
3333 (when (and c-auto-align-backslashes
3334 (not (eq (char-before (c-point 'eol)) ?\\)))
3335 ;; Fixup macro backslashes.
3336 (c-backslash-region ml-macro-start (c-point 'bonl) nil)
3337 (setq ml-macro-start nil))
3338 ;; New multi-line macro?
3339 (if (and (assq 'cpp-macro syntax)
3340 (eq (char-before (c-point 'eol)) ?\\))
3341 (setq ml-macro-start (point))))
3345 (if (and ml-macro-start c-auto-align-backslashes)
3346 (c-backslash-region ml-macro-start (c-point 'bopl) nil t)))
3347 (set-marker endmark nil)
3348 (c-progress-fini 'c-indent-region))
3349 (c-echo-parsing-error quiet))
3352 (defun c-fn-region-is-active-p ()
3353 ;; Function version of the macro for use in places that aren't
3354 ;; compiled, e.g. in the menus.
3355 (c-region-is-active-p))
3357 (defun c-indent-line-or-region (&optional arg region)
3358 "Indent active region, current line, or block starting on this line.
3359 In Transient Mark mode, when the region is active, reindent the region.
3360 Otherwise, with a prefix argument, rigidly reindent the expression
3361 starting on the current line.
3362 Otherwise reindent just the current line."
3364 (list current-prefix-arg (c-region-is-active-p)))
3366 (c-indent-region (region-beginning) (region-end))
3367 (c-indent-command arg)))
3369 ;; for progress reporting
3370 (defvar c-progress-info nil)
3372 (defun c-progress-init (start end context)
3375 ((not c-progress-interval))
3376 ;; Start the progress update messages. If this Emacs doesn't have
3377 ;; a built-in timer, just be dumb about it.
3378 ((not (fboundp 'current-time))
3379 (message "Indenting region... (this may take a while)"))
3380 ;; If progress has already been initialized, do nothing. otherwise
3381 ;; initialize the counter with a vector of:
3382 ;; [start end lastsec context]
3384 (t (setq c-progress-info (vector start
3388 (nth 1 (current-time))
3390 (message "Indenting region..."))
3393 (defun c-progress-update ()
3394 (if (not (and c-progress-info c-progress-interval))
3396 (let ((now (nth 1 (current-time)))
3397 (start (aref c-progress-info 0))
3398 (end (aref c-progress-info 1))
3399 (lastsecs (aref c-progress-info 2)))
3400 ;; should we update? currently, update happens every 2 seconds,
3401 ;; what's the right value?
3402 (if (< c-progress-interval (- now lastsecs))
3404 (message "Indenting region... (%d%% complete)"
3405 (floor (* 100.0 (- (point) start)) (- end start)))
3406 (aset c-progress-info 2 now)))
3409 (defun c-progress-fini (context)
3410 (if (not c-progress-interval)
3412 (if (or (eq context (aref c-progress-info 3))
3415 (set-marker (aref c-progress-info 1) nil)
3416 (setq c-progress-info nil)
3417 (message "Indenting region... done")))))
3421 ;;; This page handles insertion and removal of backslashes for C macros.
3423 (defun c-backslash-region (from to delete-flag &optional line-mode)
3424 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3425 With no argument, inserts backslashes and aligns existing backslashes.
3426 With an argument, deletes the backslashes. The backslash alignment is
3427 done according to the settings in `c-backslash-column',
3428 `c-backslash-max-column' and `c-auto-align-backslashes'.
3430 This function does not modify blank lines at the start of the region.
3431 If the region ends at the start of a line and the macro doesn't
3432 continue below it, the backslash (if any) at the end of the previous
3435 You can put the region around an entire macro definition and use this
3436 command to conveniently insert and align the necessary backslashes."
3437 (interactive "*r\nP")
3438 (let ((endmark (make-marker))
3439 ;; Keep the backslash trimming functions from changing the
3440 ;; whitespace around point, since in this case it's only the
3441 ;; position of point that tells the indentation of the line.
3442 (point-pos (if (save-excursion
3443 (skip-chars-backward " \t")
3444 (and (bolp) (looking-at "[ \t]*\\\\?$")))
3447 column longest-line-col bs-col-after-end)
3450 (if (and (not line-mode) (bobp))
3451 ;; Nothing to do if to is at bob, since we should back up
3452 ;; and there's no line to back up to.
3454 (when (and (not line-mode) (bolp))
3455 ;; Do not back up the to line if line-mode is set, to make
3456 ;; e.g. c-newline-and-indent consistent regardless whether
3457 ;; the (newline) call leaves point at bol or not.
3462 (set-marker endmark (point))
3464 (c-delete-backslashes-forward endmark point-pos))
3465 ;; Set bs-col-after-end to the column of any backslash
3466 ;; following the region, or nil if there is none.
3467 (setq bs-col-after-end
3468 (and (progn (end-of-line)
3469 (eq (char-before) ?\\))
3470 (= (forward-line 1) 0)
3471 (progn (end-of-line)
3472 (eq (char-before) ?\\))
3473 (1- (current-column))))
3475 ;; Back up the to line if line-mode is set, since the line
3476 ;; after the newly inserted line break should not be
3477 ;; touched in c-newline-and-indent.
3478 (setq to (max from (or (c-safe (c-point 'eopl)) from)))
3479 (unless bs-col-after-end
3480 ;; Set bs-col-after-end to non-nil in any case, since we
3481 ;; do not want to delete the backslash at the last line.
3482 (setq bs-col-after-end t)))
3484 (not c-auto-align-backslashes))
3486 ;; Compute the smallest column number past the ends of all
3488 (setq longest-line-col 0)
3490 (if bs-col-after-end
3491 ;; Include one more line in the max column
3492 ;; calculation, since the to line will be backslashed
3496 (while (and (>= (point) from)
3498 (if (eq (char-before) ?\\)
3500 (skip-chars-backward " \t")
3501 (setq longest-line-col (max longest-line-col
3502 (1+ (current-column))))
3506 ;; Try to align with surrounding backslashes.
3509 (if (and (not (bobp))
3510 (progn (backward-char)
3511 (eq (char-before) ?\\)))
3513 (setq column (1- (current-column)))
3514 (if (numberp bs-col-after-end)
3515 ;; Both a preceding and a following backslash.
3516 ;; Choose the greatest of them.
3517 (setq column (max column bs-col-after-end)))
3519 ;; No preceding backslash. Try to align with one
3520 ;; following the region. Disregard the backslash at the
3521 ;; to line since it's likely to be bogus (e.g. when
3522 ;; called from c-newline-and-indent).
3523 (if (numberp bs-col-after-end)
3524 (setq column bs-col-after-end))
3525 ;; Don't modify blank lines at start of region.
3527 (while (and (< (point) to) (bolp) (eolp))
3529 (if (and column (< column longest-line-col))
3530 ;; Don't try to align with surrounding backslashes if
3531 ;; any line is too long.
3534 ;; Impose minimum limit and tab width alignment only if
3535 ;; we can't align with surrounding backslashes.
3536 (if (> (% longest-line-col tab-width) 0)
3537 (setq longest-line-col
3538 (* (/ (+ longest-line-col tab-width -1)
3541 (setq column (max c-backslash-column
3543 ;; Always impose maximum limit.
3544 (setq column (min column c-backslash-max-column)))
3545 (if bs-col-after-end
3546 ;; Add backslashes on all lines if the macro continues
3547 ;; after the to line.
3549 (set-marker endmark to)
3550 (c-append-backslashes-forward endmark column point-pos))
3551 ;; Add backslashes on all lines except the last, and
3552 ;; remove any on the last line.
3557 (set-marker endmark (1- (point)))))
3559 (c-append-backslashes-forward endmark column point-pos)
3560 ;; The function above leaves point on the line
3561 ;; following endmark.
3562 (set-marker endmark (point)))
3563 (set-marker endmark to))
3564 (c-delete-backslashes-forward endmark point-pos)))))
3565 (set-marker endmark nil)
3566 (if (markerp point-pos)
3567 (set-marker point-pos nil))))
3569 (defun c-append-backslashes-forward (to-mark column point-pos)
3570 (let ((state (parse-partial-sexp (c-point 'bol) (point))))
3574 (<= (point) to-mark)
3576 (let ((start (point)) (inserted nil) end col)
3578 (unless (eq (char-before) ?\\)
3581 (setq state (parse-partial-sexp
3582 start (point) nil nil state))
3584 (setq col (current-column))
3586 ;; Avoid unnecessary changes of the buffer.
3587 (cond ((and (not inserted) (nth 3 state))
3588 ;; Don't realign backslashes in string literals
3589 ;; since that would change them.
3596 (skip-chars-backward
3597 " \t" (if (>= (point) point-pos) point-pos))
3601 ((and (= col column)
3602 (memq (char-before) '(?\ ?\t))))
3606 (or (/= (skip-chars-backward
3607 " \t" (if (>= (point) point-pos) point-pos))
3609 (/= (char-after) ?\ )))
3610 (delete-region (point) end)
3611 (indent-to column 1)))
3613 (zerop (forward-line 1)))
3614 (bolp))) ; forward-line has funny behavior at eob.
3616 ;; Make sure there are backslashes with at least one space in
3620 (<= (point) to-mark)
3622 (let ((start (point)))
3624 (setq state (parse-partial-sexp
3625 start (point) nil nil state))
3627 (if (eq (char-before) ?\\)
3628 (unless (nth 3 state)
3630 (unless (and (memq (char-before) '(?\ ?\t))
3631 (/= (point) point-pos))
3634 (if (and (memq (char-before) '(?\ ?\t))
3635 (/= (point) point-pos))
3639 (zerop (forward-line 1)))
3640 (bolp)))))) ; forward-line has funny behavior at eob.
3642 (defun c-delete-backslashes-forward (to-mark point-pos)
3644 (and (<= (point) to-mark)
3647 (if (eq (char-before) ?\\)
3650 (progn (backward-char)
3651 (skip-chars-backward " \t" (if (>= (point) point-pos)
3654 (zerop (forward-line 1)))
3655 (bolp)))) ; forward-line has funny behavior at eob.
3659 ;;; Line breaking and paragraph filling.
3661 (defvar c-auto-fill-prefix t)
3662 (defvar c-lit-limits nil)
3663 (defvar c-lit-type nil)
3665 ;; The filling code is based on a simple theory; leave the intricacies
3666 ;; of the text handling to the currently active mode for that
3667 ;; (e.g. adaptive-fill-mode or filladapt-mode) and do as little as
3668 ;; possible to make them work correctly wrt the comment and string
3669 ;; separators, one-line paragraphs etc. Unfortunately, when it comes
3670 ;; to it, there's quite a lot of special cases to handle which makes
3671 ;; the code anything but simple. The intention is that it will work
3672 ;; with any well-written text filling package that preserves a fill
3675 ;; We temporarily mask comment starters and enders as necessary for
3676 ;; the filling code to do its job on a seemingly normal text block.
3677 ;; We do _not_ mask the fill prefix, so it's up to the filling code to
3678 ;; preserve it correctly (especially important when filling C++ style
3679 ;; line comments). By default, we set up and use adaptive-fill-mode,
3680 ;; which is standard in all supported Emacs flavors.
3682 (defun c-guess-fill-prefix (lit-limits lit-type)
3683 ;; Determine the appropriate comment fill prefix for a block or line
3684 ;; comment. Return a cons of the prefix string and the column where
3685 ;; it ends. If fill-prefix is set, it'll override. Note that this
3686 ;; function also uses the value of point in some heuristics.
3688 ;; This function might do hidden buffer changes.
3690 (let* ((here (point))
3691 (prefix-regexp (concat "[ \t]*\\("
3692 c-current-comment-prefix
3694 (comment-start-regexp (if (eq lit-type 'c++)
3696 comment-start-skip))
3697 prefix-line comment-prefix res comment-text-end)
3701 (setq res (cons fill-prefix
3702 ;; Ugly way of getting the column after the fill
3703 ;; prefix; it'd be nice with a current-column
3704 ;; that works on strings..
3705 (let ((start (point)))
3708 (insert-and-inherit "\n" fill-prefix)
3710 (delete-region start (point)))))))
3714 ;; Set fallback for comment-prefix if none is found.
3715 (setq comment-prefix "// "
3716 comment-text-end (cdr lit-limits))
3719 (if (> (point) (car lit-limits))
3720 ;; The current line is not the comment starter, so the
3721 ;; comment has more than one line, and it can therefore be
3722 ;; used to find the comment fill prefix.
3723 (setq prefix-line (point))
3725 (goto-char (car lit-limits))
3726 (if (and (= (forward-line 1) 0)
3727 (< (point) (cdr lit-limits)))
3728 ;; The line after the comment starter is inside the
3729 ;; comment, so we can use it.
3730 (setq prefix-line (point))
3732 ;; The comment is only one line. Take the comment prefix
3733 ;; from it and keep the indentation.
3734 (goto-char (car lit-limits))
3735 (if (looking-at prefix-regexp)
3736 (goto-char (match-end 0))
3738 (skip-chars-forward " \t"))
3741 (if (eq (c-point 'boi) (car lit-limits))
3742 ;; There is only whitespace before the comment
3743 ;; starter; take the prefix straight from this line.
3744 (setq str (buffer-substring-no-properties
3745 (c-point 'bol) (point))
3746 col (current-column))
3748 ;; There is code before the comment starter, so we
3749 ;; have to temporarily insert and indent a new line to
3750 ;; get the right space/tab mix in the indentation.
3751 (let ((prefix-len (- (point) (car lit-limits)))
3755 (goto-char (car lit-limits))
3756 (indent-to (prog1 (current-column)
3759 (forward-char prefix-len)
3760 (setq str (buffer-substring-no-properties
3761 (c-point 'bol) (point))
3762 col (current-column)))
3763 (delete-region (car lit-limits) tmp))))
3766 (if (or (string-match "\\s \\'" str) (not (eolp)))
3768 ;; The prefix ends the line with no whitespace
3769 ;; after it. Default to a single space.
3770 (cons (concat str " ") (1+ col))))
3774 (setq comment-text-end
3776 (goto-char (- (cdr lit-limits) 2))
3777 (if (looking-at "\\*/") (point) (cdr lit-limits))))
3781 (if (and (> (point) (car lit-limits))
3782 (not (and (looking-at "[ \t]*\\*/")
3783 (eq (cdr lit-limits) (match-end 0)))))
3784 ;; The current line is not the comment starter and
3785 ;; contains more than just the ender, so it's good enough
3786 ;; to be used for the comment fill prefix.
3787 (setq prefix-line (point))
3788 (goto-char (car lit-limits))
3790 (cond ((or (/= (forward-line 1) 0)
3791 (>= (point) (cdr lit-limits))
3792 (and (looking-at "[ \t]*\\*/")
3793 (eq (cdr lit-limits) (match-end 0)))
3794 (and (looking-at prefix-regexp)
3795 (<= (1- (cdr lit-limits)) (match-end 0))))
3796 ;; The comment is either one line or the next line contains
3797 ;; just the comment ender. In this case we have no
3798 ;; information about a suitable comment prefix, so we resort
3799 ;; to c-block-comment-prefix.
3800 (setq comment-prefix (or c-block-comment-prefix "")))
3803 ;; The point was on the comment opener line, so we might want
3804 ;; to treat this as a not yet closed comment.
3806 (if (and (match-beginning 1)
3807 (/= (match-beginning 1) (match-end 1)))
3808 ;; Above `prefix-regexp' matched a nonempty prefix on the
3809 ;; second line, so let's use it. Normally it should do
3810 ;; to set `prefix-line' and let the code below pick up
3811 ;; the whole prefix, but if there's no text after the
3812 ;; match then it will probably fall back to no prefix at
3813 ;; all if the comment isn't closed yet, so in that case
3814 ;; it's better to force use of the prefix matched now.
3815 (if (= (match-end 0) (c-point 'eol))
3816 (setq comment-prefix (match-string 1))
3817 (setq prefix-line (point)))
3819 ;; There's no nonempty prefix on the line after the
3820 ;; comment opener. If the line is empty, or if the
3821 ;; text on it has less or equal indentation than the
3822 ;; comment starter we assume it's an unclosed
3823 ;; comment starter, i.e. that
3824 ;; `c-block-comment-prefix' should be used.
3825 ;; Otherwise we assume it's a closed comment where
3826 ;; the prefix really is the empty string.
3827 ;; E.g. this is an unclosed comment:
3838 ;; (Looking for the presence of the comment closer
3839 ;; rarely works since it's probably the closer of
3840 ;; some comment further down when the comment
3841 ;; really is unclosed.)
3842 (if (<= (save-excursion (back-to-indentation)
3844 (save-excursion (goto-char (car lit-limits))
3846 (setq comment-prefix (or c-block-comment-prefix ""))
3847 (setq prefix-line (point)))))
3850 ;; Otherwise the line after the comment starter is good
3851 ;; enough to find the prefix in.
3852 (setq prefix-line (point))))
3854 (when comment-prefix
3855 ;; Haven't got the comment prefix on any real line that we
3856 ;; can take it from, so we have to temporarily insert
3857 ;; `comment-prefix' on a line and indent it to find the
3858 ;; correct column and the correct mix of tabs and spaces.
3860 (let (tmp-pre tmp-post)
3864 (goto-char (car lit-limits))
3865 (if (looking-at comment-start-regexp)
3866 (goto-char (min (match-end 0)
3869 (skip-chars-forward " \t"))
3871 (when (eq (char-syntax (char-before)) ?\ )
3872 ;; If there's ws on the current line, we'll use it
3873 ;; instead of what's ending comment-prefix.
3874 (setq comment-prefix
3875 (concat (substring comment-prefix
3879 (buffer-substring-no-properties
3881 (skip-chars-backward " \t")
3885 (setq tmp-pre (point-marker))
3887 ;; We insert an extra non-whitespace character
3888 ;; before the line break and after comment-prefix in
3889 ;; case it's "" or ends with whitespace.
3890 (insert-and-inherit "x\n" comment-prefix "x")
3891 (setq tmp-post (point-marker))
3893 (indent-according-to-mode)
3895 (goto-char (1- tmp-post))
3896 (cons (buffer-substring-no-properties
3897 (c-point 'bol) (point))
3901 (delete-region tmp-pre tmp-post)
3902 (set-marker tmp-pre nil)
3903 (set-marker tmp-post nil))))))))))
3905 (or res ; Found a good prefix above.
3908 ;; prefix-line is the bol of a line on which we should try
3909 ;; to find the prefix.
3910 (let* (fb-string fb-endpos ; Contains any fallback prefix found.
3913 (when (and (looking-at prefix-regexp)
3914 (<= (match-end 0) comment-text-end))
3915 (unless (eq (match-end 0) (c-point 'eol))
3916 ;; The match is fine if there's text after it.
3917 (throw 'found (cons (buffer-substring-no-properties
3918 (match-beginning 0) (match-end 0))
3919 (progn (goto-char (match-end 0))
3920 (current-column)))))
3922 ;; This match is better than nothing, so let's
3923 ;; remember it in case nothing better is found
3925 (setq fb-string (buffer-substring-no-properties
3926 (match-beginning 0) (match-end 0))
3927 fb-endpos (match-end 0)))
3931 ;; Search for a line which has text after the prefix
3932 ;; so that we get the proper amount of whitespace
3933 ;; after it. We start with the current line, then
3934 ;; search backwards, then forwards.
3936 (goto-char prefix-line)
3937 (when (and (funcall test-line)
3938 (or (/= (match-end 1) (match-end 0))
3939 ;; The whitespace is sucked up by the
3940 ;; first [ \t]* glob if the prefix is empty.
3941 (and (= (match-beginning 1) (match-end 1))
3942 (/= (match-beginning 0) (match-end 0)))))
3943 ;; If the current line doesn't have text but do
3944 ;; have whitespace after the prefix, we'll use it.
3945 (throw 'found (cons fb-string
3946 (progn (goto-char fb-endpos)
3947 (current-column)))))
3949 (if (eq lit-type 'c++)
3950 ;; For line comments we can search up to and
3951 ;; including the first line.
3952 (while (and (zerop (forward-line -1))
3953 (>= (point) (car lit-limits)))
3954 (funcall test-line))
3955 ;; For block comments we must stop before the
3957 (while (and (zerop (forward-line -1))
3958 (> (point) (car lit-limits)))
3959 (funcall test-line)))
3961 (goto-char prefix-line)
3962 (while (and (zerop (forward-line 1))
3963 (< (point) (cdr lit-limits)))
3964 (funcall test-line))
3966 (goto-char prefix-line)
3970 ;; A good line wasn't found, but at least we have a
3971 ;; fallback that matches the comment prefix regexp.
3972 (cond ((or (string-match "\\s \\'" fb-string)
3974 (goto-char fb-endpos)
3976 ;; There are ws or text after the prefix, so
3978 (cons fb-string (current-column)))
3981 ;; Check if there's any whitespace padding
3982 ;; on the comment start line that we can
3983 ;; use after the prefix.
3984 (goto-char (car lit-limits))
3985 (if (looking-at comment-start-regexp)
3986 (goto-char (match-end 0))
3988 (skip-chars-forward " \t"))
3990 (eq (char-syntax (char-before)) ?\ )))
3992 (setq fb-string (buffer-substring-no-properties
3994 (skip-chars-backward " \t")
3997 (goto-char fb-endpos)
3998 (skip-chars-backward " \t")
4000 (let ((tmp (point)))
4001 ;; Got to mess in the buffer once again to
4002 ;; ensure the column gets correct. :P
4005 (insert-and-inherit fb-string)
4006 (cons (buffer-substring-no-properties
4010 (delete-region tmp (point)))))
4013 ;; Last resort: Just add a single space after
4015 (cons (concat fb-string " ")
4016 (progn (goto-char fb-endpos)
4017 (1+ (current-column)))))))
4019 ;; The line doesn't match the comment prefix regexp.
4021 ;; We have a fallback for line comments that we must use.
4022 (cons (concat (buffer-substring-no-properties
4023 prefix-line (c-point 'boi))
4025 (progn (back-to-indentation)
4026 (+ (current-column) (length comment-prefix))))
4028 ;; Assume we are dealing with a "free text" block
4029 ;; comment where the lines doesn't have any comment
4030 ;; prefix at all and we should just fill it as
4035 (defun c-mask-paragraph (fill-paragraph apply-outside-literal fun &rest args)
4036 ;; Calls FUN with ARGS ar arguments while the current paragraph is
4037 ;; masked to allow adaptive filling to work correctly. That
4038 ;; includes narrowing the buffer and, if point is inside a comment,
4039 ;; masking the comment starter and ender appropriately.
4041 ;; FILL-PARAGRAPH is non-nil if called for whole paragraph filling.
4042 ;; The position of point is then less significant when doing masking
4045 ;; If APPLY-OUTSIDE-LITERAL is nil then the function will be called
4046 ;; only if the point turns out to be inside a comment or a string.
4048 ;; Note that this function does not do any hidden buffer changes.
4051 ;; beg and end limit the region to narrow. end is a marker.
4053 ;; tmp-pre and tmp-post mark strings that are temporarily
4054 ;; inserted at the start and end of the region. tmp-pre is a
4055 ;; cons of the positions of the prepended string. tmp-post is
4056 ;; a marker pointing to the single character of the appended
4059 ;; If hang-ender-stuck isn't nil, the comment ender is
4060 ;; hanging. In that case it's set to the number of spaces
4061 ;; that should be between the text and the ender.
4063 ;; auto-fill-spaces is the exact sequence of whitespace between a
4064 ;; comment's last word and the comment ender, temporarily replaced
4065 ;; with 'x's before calling FUN when FILL-PARAGRAPH is nil.
4068 (c-lit-limits c-lit-limits)
4069 (c-lit-type c-lit-type))
4071 ;; Restore point on undo. It's necessary since we do a lot of
4072 ;; hidden inserts and deletes below that should be as transparent
4074 (if (and buffer-undo-list (not (eq buffer-undo-list t)))
4075 (setq buffer-undo-list (cons (point) buffer-undo-list)))
4077 ;; Determine the limits and type of the containing literal (if any):
4078 ;; C-LIT-LIMITS, C-LIT-TYPE; and the limits of the current paragraph:
4080 (c-save-buffer-state ()
4082 ;; Widen to catch comment limits correctly.
4084 (unless c-lit-limits
4085 (setq c-lit-limits (c-literal-limits nil fill-paragraph)))
4086 (setq c-lit-limits (c-collect-line-comments c-lit-limits))
4088 (setq c-lit-type (c-literal-type c-lit-limits))))
4091 (unless (c-safe (backward-char)
4095 (forward-paragraph))
4096 (setq end (point-marker)))
4098 (unless (c-safe (forward-char)
4099 (backward-paragraph)
4102 (backward-paragraph))
4103 (setq beg (point))))
4107 ;; For each of the possible types of text (string, C comment ...)
4108 ;; determine BEG and END, the region we will narrow to. If we're in
4109 ;; a literal, constrain BEG and END to the limits of this literal.
4111 ;; For some of these text types, particularly a block comment, we
4112 ;; may need to massage whitespace near literal delimiters, so that
4113 ;; these don't get filled inappropriately.
4116 ((eq c-lit-type 'c++) ; Line comment.
4118 ;; Limit to the comment or paragraph end, whichever
4120 (set-marker end (min end (cdr c-lit-limits)))
4122 (when (<= beg (car c-lit-limits))
4123 ;; The region includes the comment starter, so we must
4125 (goto-char (car c-lit-limits))
4126 (back-to-indentation)
4127 (if (eq (point) (car c-lit-limits))
4128 ;; Include the first line in the region.
4129 (setq beg (c-point 'bol))
4130 ;; The first line contains code before the
4131 ;; comment. We must fake a line that doesn't.
4134 (setq apply-outside-literal t))
4136 ((eq c-lit-type 'c) ; Block comment.
4138 (or (> end (cdr c-lit-limits))
4139 (and (= end (cdr c-lit-limits))
4140 (eq (char-before end) ?/)
4141 (eq (char-before (1- end)) ?*)
4143 (> (- (cdr c-lit-limits) (car c-lit-limits)) 3)))
4144 ;; There is a comment ender, and the region includes it. If
4145 ;; it's on its own line, it stays on its own line. If it's got
4146 ;; company on the line, it keeps (at least one word of) it.
4147 ;; "=====*/" counts as a comment ender here, but "===== */"
4148 ;; doesn't and "foo*/" doesn't.
4151 (goto-char (cdr c-lit-limits))
4153 ;; The following conjunct was added to avoid an
4154 ;; "Invalid search bound (wrong side of point)"
4155 ;; error in the subsequent re-search. Maybe
4156 ;; another fix would be needed (2007-12-08).
4157 ; (or (<= (- (cdr c-lit-limits) 2) (point))
4158 ; 2010-10-17 Construct removed.
4159 ; (or (< (- (cdr c-lit-limits) 2) (point))
4161 (search-forward-regexp
4162 (concat "\\=[ \t]*\\(" c-current-comment-prefix "\\)")
4163 (- (cdr c-lit-limits) 2) t)
4164 (not (search-forward-regexp
4166 (- (cdr c-lit-limits) 2) 'limit))
4167 ;; The comment ender IS on its own line. Exclude this
4168 ;; line from the filling.
4169 (set-marker end (c-point 'bol))));)
4171 ;; The comment ender is hanging. Replace all space between it
4172 ;; and the last word either by one or two 'x's (when
4173 ;; FILL-PARAGRAPH is non-nil), or a row of x's the same width
4174 ;; as the whitespace (when auto filling), and include it in
4175 ;; the region. We'll change them back to whitespace
4176 ;; afterwards. The effect of this is to glue the comment
4177 ;; ender to the last word in the comment during filling.
4178 (let* ((ender-start (save-excursion
4179 (goto-char (cdr c-lit-limits))
4180 (skip-syntax-backward "^w ")
4182 (ender-column (save-excursion
4183 (goto-char ender-start)
4185 (point-rel (- ender-start here))
4186 (sentence-ends-comment
4188 (goto-char ender-start)
4189 (and (search-backward-regexp
4190 (c-sentence-end) (c-point 'bol) t)
4191 (goto-char (match-end 0))
4192 (looking-at "[ \t]*")
4193 (= (match-end 0) ender-start))))
4197 ;; Insert a CR after the "*/", adjust END
4198 (goto-char (cdr c-lit-limits))
4199 (setq tmp-post (point-marker))
4201 (set-marker end (point))
4203 (forward-line -1) ; last line of the comment
4204 (if (and (looking-at (concat "[ \t]*\\(\\("
4205 c-current-comment-prefix
4207 (eq ender-start (match-end 0)))
4208 ;; The comment ender is prefixed by nothing but a
4209 ;; comment line prefix. IS THIS POSSIBLE? (ACM,
4210 ;; 2006/4/28). Remove it along with surrounding ws.
4211 (setq spaces (- (match-end 1) (match-end 2)))
4212 (goto-char ender-start))
4213 (skip-chars-backward " \t\r\n") ; Surely this can be
4214 ; " \t"? "*/" is NOT alone on the line (ACM, 2005/8/18)
4216 ;; What's being tested here? 2006/4/20. FIXME!!!
4217 (if (/= (point) ender-start)
4219 (if (<= here (point))
4220 ;; Don't adjust point below if it's
4221 ;; before the string we replace.
4222 (setq point-rel -1))
4223 ;; Keep one or two spaces between the
4224 ;; text and the ender, depending on how
4225 ;; many there are now.
4227 (setq spaces (- ender-column (current-column))))
4228 (setq auto-fill-spaces (c-delete-and-extract-region
4229 (point) ender-start))
4230 ;; paragraph filling condenses multiple spaces to
4231 ;; single or double spaces. auto-fill doesn't.
4236 (if (and sentence-ends-comment
4237 sentence-end-double-space)
4240 ;; Insert the filler first to keep marks right.
4241 (insert-char ?x spaces t)
4242 (setq hang-ender-stuck spaces)
4244 (and (>= point-rel 0)
4245 (- (point) (min point-rel spaces)))))
4246 (setq point-rel nil)))
4249 ;; Point was in the middle of the string we
4250 ;; replaced above, so put it back in the same
4251 ;; relative position, counting from the end.
4252 (goto-char point-rel)))
4255 (when (<= beg (car c-lit-limits))
4256 ;; The region includes the comment starter.
4258 (goto-char (car c-lit-limits))
4259 (if (looking-at (concat "\\(" comment-start-skip "\\)$"))
4260 ;; Begin with the next line.
4261 (setq beg (c-point 'bonl))
4262 ;; Fake the fill prefix in the first line.
4265 (setq apply-outside-literal t))
4267 ((eq c-lit-type 'string) ; String.
4269 (when (>= end (cdr c-lit-limits))
4270 (goto-char (1- (cdr c-lit-limits)))
4271 (setq tmp-post (point-marker))
4273 (set-marker end (point)))
4274 (when (<= beg (car c-lit-limits))
4275 (goto-char (1+ (car c-lit-limits)))
4276 (setq beg (if (looking-at "\\\\$")
4277 ;; Leave the start line if it's
4278 ;; nothing but an escaped newline.
4281 (setq apply-outside-literal t))
4283 ((eq c-lit-type 'pound) ; Macro
4284 ;; Narrow to the macro limits if they are nearer than the
4285 ;; paragraph limits. Don't know if this is necessary but
4286 ;; do it for completeness sake (doing auto filling at all
4287 ;; inside macros is bogus to begin with since the line
4288 ;; continuation backslashes aren't handled).
4290 (c-save-buffer-state ()
4291 (c-beginning-of-macro)
4298 (set-marker end (point))))))
4301 ;; Try to avoid comments and macros in the paragraph to
4302 ;; avoid that the adaptive fill mode gets the prefix from
4304 (c-save-buffer-state nil
4307 (c-forward-syntactic-ws end)
4311 (c-backward-syntactic-ws beg)
4313 (set-marker end (point))))))
4316 ;; Temporarily insert the fill prefix after the comment
4317 ;; starter so that the first line looks like any other
4318 ;; comment line in the narrowed region.
4319 (setq fill (c-save-buffer-state nil
4320 (c-guess-fill-prefix c-lit-limits c-lit-type)))
4321 (unless (string-match (concat "\\`[ \t]*\\("
4322 c-current-comment-prefix
4325 ;; Oops, the prefix doesn't match the comment prefix
4326 ;; regexp. This could produce very confusing
4327 ;; results with adaptive fill packages together with
4328 ;; the insert prefix magic below, since the prefix
4329 ;; often doesn't appear at all. So let's warn about
4332 Warning: Regexp from `c-comment-prefix-regexp' doesn't match the comment prefix %S"
4334 ;; Find the right spot on the line, break it, insert
4335 ;; the fill prefix and make sure we're back in the
4336 ;; same column by temporarily prefixing the first word
4337 ;; with a number of 'x'.
4339 (goto-char (car c-lit-limits))
4340 (if (looking-at (if (eq c-lit-type 'c++)
4341 c-current-comment-prefix
4342 comment-start-skip))
4343 (goto-char (match-end 0))
4345 (skip-chars-forward " \t"))
4346 (while (and (< (current-column) (cdr fill))
4349 (let ((col (current-column)))
4350 (setq beg (1+ (point))
4351 tmp-pre (list (point)))
4354 (insert-and-inherit "\n" (car fill))
4355 (insert-char ?x (- col (current-column)) t))
4356 (setcdr tmp-pre (point))))))
4358 (when apply-outside-literal
4359 ;; `apply-outside-literal' is always set to t here if
4360 ;; we're inside a literal.
4364 ;; Kludge: If the function that adapts the fill prefix
4365 ;; doesn't produce the required comment starter for
4366 ;; line comments, then force it by setting fill-prefix.
4367 (when (and (eq c-lit-type 'c++)
4368 ;; Kludge the kludge: filladapt-mode doesn't
4369 ;; have this problem, but it currently
4370 ;; doesn't override fill-context-prefix
4372 (not (and (boundp 'filladapt-mode)
4376 (or (fill-context-prefix beg end)
4378 (c-save-buffer-state nil
4379 (car (or fill (c-guess-fill-prefix
4380 c-lit-limits c-lit-type)))))))
4382 ;; Save the relative position of point if it's outside the
4383 ;; region we're going to narrow. Want to restore it in that
4384 ;; case, but otherwise it should be moved according to the
4386 (point-rel (cond ((< (point) beg) (- (point) beg))
4387 ((> (point) end) (- (point) end)))))
4389 ;; Preparations finally done! Now we can call the
4393 (narrow-to-region beg end)
4396 ;; Restore point if it was outside the region.
4398 (goto-char (+ beg point-rel))
4399 (goto-char (+ end point-rel))))))))
4401 (when (consp tmp-pre)
4402 (delete-region (car tmp-pre) (cdr tmp-pre)))
4406 (goto-char tmp-post)
4408 (when hang-ender-stuck
4409 ;; Preserve point even if it's in the middle of the string
4410 ;; we replace; save-excursion doesn't work in that case.
4412 (goto-char tmp-post)
4413 (skip-syntax-backward "^w ")
4414 (forward-char (- hang-ender-stuck))
4415 (if (or fill-paragraph (not auto-fill-spaces))
4416 (insert-char ?\ hang-ender-stuck t)
4417 (insert auto-fill-spaces))
4418 (delete-char hang-ender-stuck)
4420 (set-marker tmp-post nil))
4422 (set-marker end nil))))
4424 (defun c-fill-paragraph (&optional arg)
4425 "Like \\[fill-paragraph] but handles C and C++ style comments.
4426 If any of the current line is a comment or within a comment, fill the
4427 comment or the paragraph of it that point is in, preserving the
4428 comment indentation or line-starting decorations (see the
4429 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
4432 If point is inside multiline string literal, fill it. This currently
4433 does not respect escaped newlines, except for the special case when it
4434 is the very first thing in the string. The intended use for this rule
4435 is in situations like the following:
4437 char description[] = \"\\
4438 A very long description of something that you want to fill to make
4439 nicely formatted output.\";
4441 If point is in any other situation, i.e. in normal code, do nothing.
4443 Optional prefix ARG means justify paragraph as well."
4445 (let ((fill-paragraph-function
4446 ;; Avoid infinite recursion.
4447 (if (not (eq fill-paragraph-function 'c-fill-paragraph))
4448 fill-paragraph-function)))
4449 (c-mask-paragraph t nil 'fill-paragraph arg))
4450 ;; Always return t. This has the effect that if filling isn't done
4451 ;; above, it isn't done at all, and it's therefore effectively
4452 ;; disabled in normal code.
4455 (defun c-do-auto-fill ()
4456 ;; Do automatic filling if not inside a context where it should be
4458 (let ((c-auto-fill-prefix
4459 ;; The decision whether the line should be broken is actually
4460 ;; done in c-indent-new-comment-line, which do-auto-fill
4461 ;; calls to break lines. We just set this special variable
4462 ;; so that we'll know when we're called from there. It's
4463 ;; also used to detect whether fill-prefix is user set or
4464 ;; generated automatically by do-auto-fill.
4466 (c-mask-paragraph nil t 'do-auto-fill)))
4468 (defun c-indent-new-comment-line (&optional soft allow-auto-fill)
4469 "Break line at point and indent, continuing comment or macro if within one.
4470 If inside a comment and `comment-multi-line' is non-nil, the
4471 indentation and line prefix are preserved (see the
4472 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
4473 details). If inside a single line comment and `comment-multi-line' is
4474 nil, a new comment of the same type is started on the next line and
4475 indented as appropriate for comments. If inside a macro, a line
4476 continuation backslash is inserted and aligned as appropriate, and the
4477 new line is indented according to `c-syntactic-indentation'.
4479 If a fill prefix is specified, it overrides all the above."
4480 ;; allow-auto-fill is used from c-context-line-break to allow auto
4481 ;; filling to break the line more than once. Since this function is
4482 ;; used from auto-fill itself, that's normally disabled to avoid
4483 ;; unnecessary recursion.
4485 (let ((fill-prefix fill-prefix)
4488 (delete-horizontal-space)
4490 (insert-and-inherit ?\n)
4491 (newline (if allow-auto-fill nil 1)))))
4492 ;; Already know the literal type and limits when called from
4493 ;; c-context-line-break.
4494 (c-lit-limits c-lit-limits)
4495 (c-lit-type c-lit-type)
4496 (c-macro-start c-macro-start))
4498 (c-save-buffer-state ()
4499 (when (not (eq c-auto-fill-prefix t))
4500 ;; Called from do-auto-fill.
4501 (unless c-lit-limits
4502 (setq c-lit-limits (c-literal-limits nil nil t)))
4504 (setq c-lit-type (c-literal-type c-lit-limits)))
4505 (if (memq (cond ((c-query-and-set-macro-start) 'cpp)
4506 ((null c-lit-type) 'code)
4509 (setq fill-prefix t) ; Used as flag in the cond.
4510 (if (and (null c-auto-fill-prefix)
4512 (<= (c-point 'bol) (car c-lit-limits)))
4513 ;; The adaptive fill function has generated a prefix, but
4514 ;; we're on the first line in a block comment so it'll be
4515 ;; wrong. Ignore it to guess a better one below.
4516 (setq fill-prefix nil)
4517 (when (and (eq c-lit-type 'c++)
4518 (not (string-match (concat "\\`[ \t]*"
4519 c-line-comment-starter)
4520 (or fill-prefix ""))))
4521 ;; Kludge: If the function that adapted the fill prefix
4522 ;; doesn't produce the required comment starter for line
4523 ;; comments, then we ignore it.
4524 (setq fill-prefix nil)))
4527 (cond ((eq fill-prefix t)
4528 ;; A call from do-auto-fill which should be ignored.
4531 ;; A fill-prefix overrides anything.
4532 (funcall do-line-break)
4533 (insert-and-inherit fill-prefix))
4534 ((c-save-buffer-state ()
4535 (unless c-lit-limits
4536 (setq c-lit-limits (c-literal-limits)))
4538 (setq c-lit-type (c-literal-type c-lit-limits)))
4539 (memq c-lit-type '(c c++)))
4540 ;; Some sort of comment.
4541 (if (or comment-multi-line
4543 (goto-char (car c-lit-limits))
4545 (< (point) (cdr c-lit-limits))))
4546 ;; Inside a comment that should be continued.
4547 (let ((fill (c-save-buffer-state nil
4548 (c-guess-fill-prefix
4550 (c-collect-line-comments c-lit-limits))
4553 (start-col (current-column))
4555 (or (and (eq c-lit-type 'c)
4557 (goto-char (- (cdr c-lit-limits) 2))
4558 (if (looking-at "\\*/") (point))))
4559 (cdr c-lit-limits))))
4560 ;; Skip forward past the fill prefix in case
4561 ;; we're standing in it.
4563 ;; FIXME: This doesn't work well in cases like
4565 ;; /* Bla bla bla bla bla
4568 ;; If point is on the 'B' then the line will be
4569 ;; broken after "Bla b".
4571 ;; If we have an empty comment, /* */, the next
4572 ;; lot of code pushes point to the */. We fix
4573 ;; this by never allowing point to end up to the
4574 ;; right of where it started.
4575 (while (and (< (current-column) (cdr fill))
4578 (if (and (> (point) comment-text-end)
4579 (> (c-point 'bol) (car c-lit-limits)))
4581 ;; The skip takes us out of the (block)
4582 ;; comment; insert the fill prefix at bol
4583 ;; instead and keep the position.
4584 (setq pos (copy-marker pos t))
4586 (insert-and-inherit (car fill))
4587 (if soft (insert-and-inherit ?\n) (newline 1))
4589 (set-marker pos nil))
4590 ;; Don't break in the middle of a comment starter
4592 (cond ((> (point) comment-text-end)
4593 (goto-char comment-text-end))
4594 ((< (point) (+ (car c-lit-limits) 2))
4595 (goto-char (+ (car c-lit-limits) 2))))
4596 (funcall do-line-break)
4597 (insert-and-inherit (car fill))
4598 (if (> (current-column) start-col)
4599 (move-to-column start-col)))) ; can this hit the
4601 ;; Inside a comment that should be broken.
4602 (let ((comment-start comment-start)
4603 (comment-end comment-end)
4605 (if (eq c-lit-type 'c)
4606 (unless (string-match "[ \t]*/\\*" comment-start)
4607 (setq comment-start "/* " comment-end " */"))
4608 (unless (string-match "[ \t]*//" comment-start)
4609 (setq comment-start "// " comment-end "")))
4610 (setq col (save-excursion
4611 (back-to-indentation)
4613 (funcall do-line-break)
4614 (when (and comment-end (not (equal comment-end "")))
4616 (insert-and-inherit comment-end)
4618 ;; c-comment-indent may look at the current
4619 ;; indentation, so let's start out with the same
4620 ;; indentation as the previous one.
4622 (insert-and-inherit comment-start)
4623 (indent-for-comment))))
4624 ((c-query-and-set-macro-start)
4626 (unless (looking-at "[ \t]*\\\\$")
4627 ;; Do not clobber the alignment of the line continuation
4628 ;; slash; c-backslash-region might look at it.
4629 (delete-horizontal-space))
4630 ;; Got an asymmetry here: In normal code this command
4631 ;; doesn't indent the next line syntactically, and otoh a
4632 ;; normal syntactically indenting newline doesn't continue
4634 (c-newline-and-indent (if allow-auto-fill nil 1)))
4636 ;; Somewhere else in the code.
4637 (let ((col (save-excursion
4639 (while (and (looking-at "[ \t]*\\\\?$")
4640 (= (forward-line -1) 0)))
4641 (current-indentation))))
4642 (funcall do-line-break)
4643 (indent-to col))))))
4645 (defalias 'c-comment-line-break-function 'c-indent-new-comment-line)
4646 (make-obsolete 'c-comment-line-break-function 'c-indent-new-comment-line "21.1")
4648 ;; advice for indent-new-comment-line for older Emacsen
4649 (unless (boundp 'comment-line-break-function)
4650 (defvar c-inside-line-break-advice nil)
4651 (defadvice indent-new-comment-line (around c-line-break-advice
4652 activate preactivate)
4653 "Call `c-indent-new-comment-line' if in CC Mode."
4654 (if (or c-inside-line-break-advice
4655 (not c-buffer-is-cc-mode))
4657 (let ((c-inside-line-break-advice t))
4658 (c-indent-new-comment-line (ad-get-arg 0))))))
4660 (defun c-context-line-break ()
4661 "Do a line break suitable to the context.
4663 When point is outside a comment or macro, insert a newline and indent
4664 according to the syntactic context, unless `c-syntactic-indentation'
4665 is nil, in which case the new line is indented as the previous
4666 non-empty line instead.
4668 When point is inside the content of a preprocessor directive, a line
4669 continuation backslash is inserted before the line break and aligned
4670 appropriately. The end of the cpp directive doesn't count as inside
4673 When point is inside a comment, continue it with the appropriate
4674 comment prefix (see the `c-comment-prefix-regexp' and
4675 `c-block-comment-prefix' variables for details). The end of a
4676 C++-style line comment doesn't count as inside it.
4678 When point is inside a string, only insert a backslash when it is also
4679 inside a preprocessor directive."
4682 (let* (c-lit-limits c-lit-type
4683 (c-macro-start c-macro-start)
4686 (c-save-buffer-state ()
4687 (setq c-lit-limits (c-literal-limits nil nil t)
4688 c-lit-type (c-literal-type c-lit-limits))
4689 (when (eq c-lit-type 'c++)
4690 (setq c-lit-limits (c-collect-line-comments c-lit-limits)))
4691 (c-query-and-set-macro-start))
4694 ((or (eq c-lit-type 'c)
4695 (and (eq c-lit-type 'c++) ; C++ comment, but not at the very end of it.
4697 (skip-chars-forward " \t")
4699 (1- (cdr c-lit-limits))))
4700 (and (numberp c-macro-start) ; Macro, but not at the very end of
4701 ; it, not in a string, and not in the
4703 (not (eq c-lit-type 'string))
4704 (or (not (looking-at "\\s *$"))
4705 (eq (char-before) ?\\))
4707 (goto-char c-macro-start)
4708 (if (looking-at c-opt-cpp-start)
4709 (goto-char (match-end 0)))
4712 (let ((comment-multi-line t)
4714 (c-indent-new-comment-line nil t)))
4716 ((eq c-lit-type 'string)
4717 (if (and (numberp c-macro-start)
4718 (not (eq (char-before) ?\\)))
4722 (t (delete-horizontal-space)
4724 ;; c-indent-line may look at the current indentation, so let's
4725 ;; start out with the same indentation as the previous line.
4726 (let ((col (save-excursion
4729 (while (and (looking-at "[ \t]*\\\\?$")
4730 (= (forward-line -1) 0)))
4731 (current-indentation))))
4733 (indent-according-to-mode)))))
4735 (defun c-context-open-line ()
4736 "Insert a line break suitable to the context and leave point before it.
4737 This is the `c-context-line-break' equivalent to `open-line', which is
4738 normally bound to C-o. See `c-context-line-break' for the details."
4740 (let ((here (point)))
4743 ;; Temporarily insert a non-whitespace char to keep any
4744 ;; preceding whitespace intact.
4746 (c-context-line-break))
4751 (cc-provide 'cc-cmds)
4754 ;; indent-tabs-mode: t
4757 ;;; cc-cmds.el ends here