Merge from Gnulib
[emacs.git] / lisp / progmodes / cc-cmds.el
blob5c8bbebf31b23a98404ea0713e395f61cf660b16
1 ;;; cc-cmds.el --- user level commands for CC Mode
3 ;; Copyright (C) 1985, 1987, 1992-2017 Free Software Foundation, Inc.
5 ;; Authors: 2003- Alan Mackenzie
6 ;; 1998- Martin Stjernholm
7 ;; 1992-1999 Barry A. Warsaw
8 ;; 1987 Dave Detlefs
9 ;; 1987 Stewart Clamen
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
14 ;; Package: cc-mode
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 <https://www.gnu.org/licenses/>.
31 ;;; Commentary:
33 ;;; Code:
35 (eval-when-compile
36 (let ((load-path
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)
40 load-path)))
41 (load "cc-bytecomp" nil t)))
43 (cc-require 'cc-defs)
44 (cc-require 'cc-vars)
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 (defvar c-syntactic-context)
56 (defun c-indent-line (&optional syntax quiet ignore-point-pos)
57 "Indent the current line according to the syntactic context,
58 if `c-syntactic-indentation' is non-nil. Optional SYNTAX is the
59 syntactic information for the current line. Be silent about syntactic
60 errors if the optional argument QUIET is non-nil, even if
61 `c-report-syntactic-errors' is non-nil. Normally the position of
62 point is used to decide where the old indentation is on a lines that
63 is otherwise empty \(ignoring any line continuation backslash), but
64 that's not done if IGNORE-POINT-POS is non-nil. Returns the amount of
65 indentation change \(in columns)."
67 (let ((line-cont-backslash (save-excursion
68 (end-of-line)
69 (eq (char-before) ?\\)))
70 (c-fix-backslashes c-fix-backslashes)
71 bs-col
72 shift-amt)
73 (when (and (not ignore-point-pos)
74 (save-excursion
75 (beginning-of-line)
76 (looking-at (if line-cont-backslash
77 ;; Don't use "\\s " - ^L doesn't count as WS
78 ;; here
79 "\\([ \t]*\\)\\\\$"
80 "\\([ \t]*\\)$")))
81 (<= (point) (match-end 1)))
82 ;; Delete all whitespace after point if there's only whitespace
83 ;; on the line, so that any code that does back-to-indentation
84 ;; or similar gets the current column in this case. If this
85 ;; removes a line continuation backslash it'll be restored
86 ;; at the end.
87 (unless c-auto-align-backslashes
88 ;; Should try to keep the backslash alignment
89 ;; in this case.
90 (save-excursion
91 (goto-char (match-end 0))
92 (setq bs-col (1- (current-column)))))
93 (delete-region (point) (match-end 0))
94 (setq c-fix-backslashes t))
95 (if c-syntactic-indentation
96 (setq c-parsing-error
97 (or (let ((c-parsing-error nil)
98 (c-syntactic-context
99 (or syntax
100 (and (boundp 'c-syntactic-context)
101 c-syntactic-context))))
102 (c-save-buffer-state (indent)
103 (unless c-syntactic-context
104 (setq c-syntactic-context (c-guess-basic-syntax)))
105 (setq indent (c-get-syntactic-indentation
106 c-syntactic-context))
107 (and (not (c-echo-parsing-error quiet))
108 c-echo-syntactic-information-p
109 (message "syntax: %s, indent: %d"
110 c-syntactic-context indent))
111 (setq shift-amt (- indent (current-indentation))))
112 (c-shift-line-indentation shift-amt)
113 (run-hooks 'c-special-indent-hook)
114 c-parsing-error)
115 c-parsing-error))
116 (let ((indent 0))
117 (save-excursion
118 (while (and (= (forward-line -1) 0)
119 (if (looking-at "\\s *\\\\?$")
121 (setq indent (current-indentation))
122 nil))))
123 (setq shift-amt (- indent (current-indentation)))
124 (c-shift-line-indentation shift-amt)))
125 (when (and c-fix-backslashes line-cont-backslash)
126 (if bs-col
127 (save-excursion
128 (indent-to bs-col)
129 (insert ?\\))
130 (when c-auto-align-backslashes
131 ;; Realign the line continuation backslash.
132 (c-backslash-region (point) (point) nil t))))
133 shift-amt))
135 (defun c-newline-and-indent (&optional newline-arg)
136 "Insert a newline and indent the new line.
137 This function fixes line continuation backslashes if inside a macro,
138 and takes care to set the indentation before calling
139 `indent-according-to-mode', so that lineup functions like
140 `c-lineup-dont-change' works better."
142 ;; TODO: Backslashes before eol in comments and literals aren't
143 ;; kept intact.
144 (let ((c-macro-start (c-query-macro-start))
145 ;; Avoid calling c-backslash-region from c-indent-line if it's
146 ;; called during the newline call, which can happen due to
147 ;; c-electric-continued-statement, for example. We also don't
148 ;; want any backslash alignment from indent-according-to-mode.
149 (c-fix-backslashes nil)
150 has-backslash insert-backslash
151 start col)
152 (save-excursion
153 (beginning-of-line)
154 (setq start (point))
155 (while (and (looking-at "[ \t]*\\\\?$")
156 (= (forward-line -1) 0)))
157 (setq col (current-indentation)))
158 (when c-macro-start
159 (if (and (eolp) (eq (char-before) ?\\))
160 (setq insert-backslash t
161 has-backslash t)
162 (setq has-backslash (eq (char-before (c-point 'eol)) ?\\))))
163 (newline newline-arg)
164 (indent-to col)
165 (when c-macro-start
166 (if insert-backslash
167 (progn
168 ;; The backslash stayed on the previous line. Insert one
169 ;; before calling c-backslash-region, so that
170 ;; bs-col-after-end in it works better. Fixup the
171 ;; backslashes on the newly inserted line.
172 (insert ?\\)
173 (backward-char)
174 (c-backslash-region (point) (point) nil t))
175 ;; The backslash moved to the new line, if there was any. Let
176 ;; c-backslash-region fix a backslash on the previous line,
177 ;; and the one that might be on the new line.
178 ;; c-auto-align-backslashes is intentionally ignored here;
179 ;; maybe the moved backslash should be left alone if it's set,
180 ;; but we fix both lines on the grounds that the old backslash
181 ;; has been moved anyway and is now in a different context.
182 (c-backslash-region start (if has-backslash (point) start) nil t)))
183 (when c-syntactic-indentation
184 ;; Reindent syntactically. The indentation done above is not
185 ;; wasted, since c-indent-line might look at the current
186 ;; indentation.
187 (let ((c-syntactic-context (c-save-buffer-state nil
188 (c-guess-basic-syntax))))
189 ;; We temporarily insert another line break, so that the
190 ;; lineup functions will see the line as empty. That makes
191 ;; e.g. c-lineup-cpp-define more intuitive since it then
192 ;; proceeds to the preceding line in this case.
193 (insert ?\n)
194 (delete-horizontal-space)
195 (setq start (- (point-max) (point)))
196 (unwind-protect
197 (progn
198 (backward-char)
199 (indent-according-to-mode))
200 (goto-char (- (point-max) start))
201 (delete-char -1)))
202 (when has-backslash
203 ;; Must align the backslash again after reindentation. The
204 ;; c-backslash-region call above can't be optimized to ignore
205 ;; this line, since it then won't align correctly with the
206 ;; lines below if the first line in the macro is broken.
207 (c-backslash-region (point) (point) nil t)))))
209 (defun c-show-syntactic-information (arg)
210 "Show syntactic information for current line.
211 With universal argument, inserts the analysis as a comment on that line."
212 (interactive "P")
213 (let* ((c-parsing-error nil)
214 (syntax (if (boundp 'c-syntactic-context)
215 ;; Use `c-syntactic-context' in the same way as
216 ;; `c-indent-line', to be consistent.
217 c-syntactic-context
218 (c-save-buffer-state nil
219 (c-guess-basic-syntax)))))
220 (if (not (consp arg))
221 (let (elem pos ols)
222 (message "Syntactic analysis: %s" syntax)
223 (unwind-protect
224 (progn
225 (while syntax
226 (setq elem (pop syntax))
227 (when (setq pos (c-langelem-pos elem))
228 (push (c-put-overlay pos (1+ pos)
229 'face 'highlight)
230 ols))
231 (when (setq pos (c-langelem-2nd-pos elem))
232 (push (c-put-overlay pos (1+ pos)
233 'face 'secondary-selection)
234 ols)))
235 (sit-for 10))
236 (while ols
237 (c-delete-overlay (pop ols)))))
238 (indent-for-comment)
239 (insert-and-inherit (format "%s" syntax))
241 (c-keep-region-active))
243 (defun c-syntactic-information-on-region (from to)
244 "Insert a comment with the syntactic analysis on every line in the region."
245 (interactive "*r")
246 (save-excursion
247 (save-restriction
248 (narrow-to-region from to)
249 (goto-char (point-min))
250 (while (not (eobp))
251 (c-show-syntactic-information '(0))
252 (forward-line)))))
255 ;; Minor mode functions.
256 ;; `c-block-comment-flag' gets initialized to the current mode's default in
257 ;; c-basic-common-init.
258 (defvar c-block-comment-flag nil)
259 (make-variable-buffer-local 'c-block-comment-flag)
261 (defun c-update-modeline ()
262 (let ((fmt (format "/%s%s%s%s%s"
263 (if c-block-comment-flag "*" "/")
264 (if c-electric-flag "l" "")
265 (if (and c-electric-flag c-auto-newline)
266 "a" "")
267 (if c-hungry-delete-key "h" "")
268 (if (and
269 ;; (cc-)subword might not be loaded.
270 (boundp 'c-subword-mode)
271 (symbol-value 'c-subword-mode))
272 ;; FIXME: subword-mode already comes with its
273 ;; own lighter!
275 "")))
276 ;; FIXME: Derived modes might want to use something else
277 ;; than a string for `mode-name'.
278 (bare-mode-name (if (string-match "\\(^[^/]*\\)/" mode-name)
279 (match-string 1 mode-name)
280 mode-name)))
281 (setq mode-name
282 (if (> (length fmt) 1)
283 (concat bare-mode-name fmt)
284 bare-mode-name))
285 (force-mode-line-update)))
287 (defun c-toggle-syntactic-indentation (&optional arg)
288 "Toggle syntactic indentation.
289 Optional numeric ARG, if supplied, turns on syntactic indentation when
290 positive, turns it off when negative, and just toggles it when zero or
291 left out.
293 When syntactic indentation is turned on (the default), the indentation
294 functions and the electric keys indent according to the syntactic
295 context keys, when applicable.
297 When it's turned off, the electric keys don't reindent, the indentation
298 functions indents every new line to the same level as the previous
299 nonempty line, and \\[c-indent-command] adjusts the indentation in steps
300 specified by `c-basic-offset'. The indentation style has no effect in
301 this mode, nor any of the indentation associated variables,
302 e.g. `c-special-indent-hook'.
304 This command sets the variable `c-syntactic-indentation'."
305 (interactive "P")
306 (setq c-syntactic-indentation
307 (c-calculate-state arg c-syntactic-indentation))
308 (c-keep-region-active))
310 (defun c-toggle-auto-newline (&optional arg)
311 "Toggle auto-newline feature.
312 Optional numeric ARG, if supplied, turns on auto-newline when
313 positive, turns it off when negative, and just toggles it when zero or
314 left out.
316 Turning on auto-newline automatically enables electric indentation.
318 When the auto-newline feature is enabled (indicated by \"/la\" on the
319 mode line after the mode name) newlines are automatically inserted
320 after special characters such as brace, comma, semi-colon, and colon."
321 (interactive "P")
322 (setq c-auto-newline
323 (c-calculate-state arg (and c-auto-newline c-electric-flag)))
324 (if c-auto-newline (setq c-electric-flag t))
325 (c-update-modeline)
326 (c-keep-region-active))
328 (defalias 'c-toggle-auto-state 'c-toggle-auto-newline)
329 (make-obsolete 'c-toggle-auto-state 'c-toggle-auto-newline "22.1")
331 (defun c-toggle-hungry-state (&optional arg)
332 "Toggle hungry-delete-key feature.
333 Optional numeric ARG, if supplied, turns on hungry-delete when
334 positive, turns it off when negative, and just toggles it when zero or
335 left out.
337 When the hungry-delete-key feature is enabled (indicated by \"/h\" on
338 the mode line after the mode name) the delete key gobbles all preceding
339 whitespace in one fell swoop."
340 (interactive "P")
341 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
342 (c-update-modeline)
343 (c-keep-region-active))
345 (defun c-toggle-auto-hungry-state (&optional arg)
346 "Toggle auto-newline and hungry-delete-key features.
347 Optional numeric ARG, if supplied, turns on auto-newline and
348 hungry-delete when positive, turns them off when negative, and just
349 toggles them when zero or left out.
351 See `c-toggle-auto-newline' and `c-toggle-hungry-state' for details."
352 (interactive "P")
353 (setq c-auto-newline (c-calculate-state arg c-auto-newline))
354 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
355 (c-update-modeline)
356 (c-keep-region-active))
358 (defun c-toggle-electric-state (&optional arg)
359 "Toggle the electric indentation feature.
360 Optional numeric ARG, if supplied, turns on electric indentation when
361 positive, turns it off when negative, and just toggles it when zero or
362 left out."
363 (interactive "P")
364 (setq c-electric-flag (c-calculate-state arg c-electric-flag))
365 (c-update-modeline)
366 (when (fboundp 'electric-indent-local-mode) ; Emacs 24.4 or later.
367 (electric-indent-local-mode (if c-electric-flag 1 0)))
368 (c-keep-region-active))
370 (defun c-toggle-comment-style (&optional arg)
371 "Toggle the comment style between block and line comments.
372 Optional numeric ARG, if supplied, switches to block comment
373 style when positive, to line comment style when negative, and
374 just toggles it when zero or left out.
376 This action does nothing when the mode only has one comment style."
377 (interactive "P")
378 (setq c-block-comment-flag
379 (cond
380 ((and c-line-comment-starter c-block-comment-starter)
381 (c-calculate-state arg c-block-comment-flag))
382 (c-line-comment-starter nil)
383 (t t)))
384 (setq comment-start
385 (concat (if c-block-comment-flag
386 c-block-comment-starter
387 c-line-comment-starter)
388 " "))
389 (setq comment-end
390 (if c-block-comment-flag
391 (concat " " c-block-comment-ender)
392 ""))
393 (c-update-modeline)
394 (c-keep-region-active))
397 ;; Electric keys
399 (defun c-electric-backspace (arg)
400 "Delete the preceding character or whitespace.
401 If `c-hungry-delete-key' is non-nil (indicated by \"/h\" on the mode
402 line) then all preceding whitespace is consumed. If however a prefix
403 argument is supplied, or `c-hungry-delete-key' is nil, or point is
404 inside a literal then the function in the variable
405 `c-backspace-function' is called."
406 (interactive "*P")
407 (if (c-save-buffer-state ()
408 (or (not c-hungry-delete-key)
410 (c-in-literal)))
411 (funcall c-backspace-function (prefix-numeric-value arg))
412 (c-hungry-delete-backwards)))
414 (defun c-hungry-delete-backwards ()
415 "Delete the preceding character or all preceding whitespace
416 back to the previous non-whitespace character.
417 See also \\[c-hungry-delete-forward]."
418 (interactive)
419 (let ((here (point)))
420 (c-skip-ws-backward)
421 (if (/= (point) here)
422 (delete-region (point) here)
423 (funcall c-backspace-function 1))))
425 (defalias 'c-hungry-backspace 'c-hungry-delete-backwards)
427 (defun c-electric-delete-forward (arg)
428 "Delete the following character or whitespace.
429 If `c-hungry-delete-key' is non-nil (indicated by \"/h\" on the mode
430 line) then all following whitespace is consumed. If however a prefix
431 argument is supplied, or `c-hungry-delete-key' is nil, or point is
432 inside a literal then the function in the variable `c-delete-function'
433 is called."
434 (interactive "*P")
435 (if (c-save-buffer-state ()
436 (or (not c-hungry-delete-key)
438 (c-in-literal)))
439 (funcall c-delete-function (prefix-numeric-value arg))
440 (c-hungry-delete-forward)))
442 (defun c-hungry-delete-forward ()
443 "Delete the following character or all following whitespace
444 up to the next non-whitespace character.
445 See also \\[c-hungry-delete-backwards]."
446 (interactive)
447 (let ((here (point)))
448 (c-skip-ws-forward)
449 (if (/= (point) here)
450 (delete-region (point) here)
451 (funcall c-delete-function 1))))
453 ;; This function is only used in XEmacs.
454 (defun c-electric-delete (arg)
455 "Deletes preceding or following character or whitespace.
456 This function either deletes forward as `c-electric-delete-forward' or
457 backward as `c-electric-backspace', depending on the configuration: If
458 the function `delete-forward-p' is defined and returns non-nil, it
459 deletes forward. Otherwise it deletes backward.
461 Note: This is the way in XEmacs to choose the correct action for the
462 [delete] key, whichever key that means. Other flavors don't use this
463 function to control that."
464 (interactive "*P")
465 (if (and (fboundp 'delete-forward-p)
466 (delete-forward-p))
467 (c-electric-delete-forward arg)
468 (c-electric-backspace arg)))
470 ;; This function is only used in XEmacs.
471 (defun c-hungry-delete ()
472 "Delete a non-whitespace char, or all whitespace up to the next non-whitespace char.
473 The direction of deletion depends on the configuration: If the
474 function `delete-forward-p' is defined and returns non-nil, it deletes
475 forward using `c-hungry-delete-forward'. Otherwise it deletes
476 backward using `c-hungry-backspace'.
478 Note: This is the way in XEmacs to choose the correct action for the
479 [delete] key, whichever key that means. Other flavors don't use this
480 function to control that."
481 (interactive)
482 (if (and (fboundp 'delete-forward-p)
483 (delete-forward-p))
484 (c-hungry-delete-forward)
485 (c-hungry-delete-backwards)))
487 (defun c-electric-pound (arg)
488 "Insert a \"#\".
489 If `c-electric-flag' is set, handle it specially according to the variable
490 `c-electric-pound-behavior'. If a numeric ARG is supplied, or if point is
491 inside a literal or a macro, nothing special happens."
492 (interactive "*P")
493 (if (c-save-buffer-state ()
494 (or arg
495 (not c-electric-flag)
496 (not (memq 'alignleft c-electric-pound-behavior))
497 (save-excursion
498 (skip-chars-backward " \t")
499 (not (bolp)))
500 (save-excursion
501 (and (= (forward-line -1) 0)
502 (progn (end-of-line)
503 (eq (char-before) ?\\))))
504 (c-in-literal)))
505 ;; do nothing special
506 (self-insert-command (prefix-numeric-value arg))
507 ;; place the pound character at the left edge
508 (let ((pos (- (point-max) (point)))
509 (bolp (bolp)))
510 (beginning-of-line)
511 (delete-horizontal-space)
512 (insert (c-last-command-char))
513 (and (not bolp)
514 (goto-char (- (point-max) pos)))
517 (defun c-point-syntax ()
518 ;; Return the syntactic context of the construct at point. (This is NOT
519 ;; nec. the same as the s.c. of the line point is on). N.B. This won't work
520 ;; between the `#' of a cpp thing and what follows (see c-opt-cpp-prefix).
521 (c-save-buffer-state (;; shut this up too
522 (c-echo-syntactic-information-p nil)
523 syntax)
524 (c-tentative-buffer-changes
525 ;; insert a newline to isolate the construct at point for syntactic
526 ;; analysis.
527 (insert-char ?\n 1)
528 ;; In AWK (etc.) or in a macro, make sure this CR hasn't changed
529 ;; the syntax. (There might already be an escaped NL there.)
530 (when (or
531 (save-excursion
532 (c-skip-ws-backward (c-point 'bopl))
533 (c-at-vsemi-p))
534 (let ((pt (point)))
535 (save-excursion
536 (backward-char)
537 (and (c-beginning-of-macro)
538 (progn (c-end-of-macro)
539 (< (point) pt))))))
540 (backward-char)
541 (insert-char ?\\ 1)
542 (forward-char))
543 (let ((c-syntactic-indentation-in-macros t)
544 (c-auto-newline-analysis t))
545 ;; Turn on syntactic macro analysis to help with auto
546 ;; newlines only.
547 (setq syntax (c-guess-basic-syntax))
548 nil))
549 syntax))
551 (defun c-brace-newlines (syntax)
552 ;; A brace stands at point. SYNTAX is the syntactic context of this brace
553 ;; (not necessarily the same as the S.C. of the line it is on). Return
554 ;; NEWLINES, the list containing some combination of the symbols `before'
555 ;; and `after' saying where newlines should be inserted.
556 (c-save-buffer-state
557 ((syms
558 ;; This is the list of brace syntactic symbols that can hang.
559 ;; If any new ones are added to c-offsets-alist, they should be
560 ;; added here as well.
562 ;; The order of this list is important; if SYNTAX has several
563 ;; elements, the element that "wins" is the earliest in SYMS.
564 '(arglist-cont-nonempty ; e.g. an array literal.
565 class-open class-close defun-open defun-close
566 inline-open inline-close
567 brace-list-open brace-list-close
568 brace-list-intro brace-entry-open
569 block-open block-close
570 substatement-open statement-case-open
571 extern-lang-open extern-lang-close
572 namespace-open namespace-close
573 module-open module-close
574 composition-open composition-close
575 inexpr-class-open inexpr-class-close
576 ;; `statement-cont' is here for the case with a brace
577 ;; list opener inside a statement. C.f. CASE B.2 in
578 ;; `c-guess-continued-construct'.
579 statement-cont))
580 ;; shut this up too
581 (c-echo-syntactic-information-p nil)
582 symb-newlines) ; e.g. (substatement-open . (after))
584 (setq symb-newlines
585 ;; Do not try to insert newlines around a special
586 ;; (Pike-style) brace list.
587 (if (and c-special-brace-lists
588 (save-excursion
589 (c-safe (if (= (char-before) ?{)
590 (forward-char -1)
591 (c-forward-sexp -1))
592 (c-looking-at-special-brace-list))))
594 ;; Seek the matching entry in c-hanging-braces-alist.
595 (or (c-lookup-lists
596 syms
597 ;; Substitute inexpr-class and class-open or
598 ;; class-close with inexpr-class-open or
599 ;; inexpr-class-close.
600 (if (assq 'inexpr-class syntax)
601 (cond ((assq 'class-open syntax)
602 '((inexpr-class-open)))
603 ((assq 'class-close syntax)
604 '((inexpr-class-close)))
605 (t syntax))
606 syntax)
607 c-hanging-braces-alist)
608 '(ignore before after)))) ; Default, when not in c-h-b-l.
610 ;; If syntax is a function symbol, then call it using the
611 ;; defined semantics.
612 (if (and (not (consp (cdr symb-newlines)))
613 (functionp (cdr symb-newlines)))
614 (let ((c-syntactic-context syntax))
615 (funcall (cdr symb-newlines)
616 (car symb-newlines)
617 (point)))
618 (cdr symb-newlines))))
620 (defun c-try-one-liner ()
621 ;; Point is just after a newly inserted }. If the non-whitespace
622 ;; content of the braces is a single line of code, compact the whole
623 ;; construct to a single line, if this line isn't too long. The Right
624 ;; Thing is done with comments.
626 ;; Point will be left after the }, regardless of whether the clean-up is
627 ;; done. Return NON-NIL if the clean-up happened, NIL if it didn't.
629 (let ((here (point))
630 (pos (- (point-max) (point)))
631 mbeg1 mend1 mbeg4 mend4
632 eol-col cmnt-pos cmnt-col cmnt-gap)
634 (when
635 (save-excursion
636 (save-restriction
637 ;; Avoid backtracking over a very large block. The one we
638 ;; deal with here can never be more than three lines.
639 (narrow-to-region (save-excursion
640 (forward-line -2)
641 (point))
642 (point))
643 (and (c-safe (c-backward-sexp))
644 (progn
645 (forward-char)
646 (narrow-to-region (point) (1- here)) ; innards of {.}
647 (looking-at
648 (cc-eval-when-compile
649 (concat
650 "\\(" ; (match-beginning 1)
651 "[ \t]*\\([\r\n][ \t]*\\)?" ; WS with opt. NL
652 "\\)" ; (match-end 1)
653 "[^ \t\r\n]+\\([ \t]+[^ \t\r\n]+\\)*" ; non-WS
654 "\\(" ; (match-beginning 4)
655 "[ \t]*\\([\r\n][ \t]*\\)?" ; WS with opt. NL
656 "\\)\\'"))))))) ; (match-end 4) at EOB.
658 (if (c-tentative-buffer-changes
659 (setq mbeg1 (match-beginning 1) mend1 (match-end 1)
660 mbeg4 (match-beginning 4) mend4 (match-end 4))
661 (backward-char) ; back over the `}'
662 (save-excursion
663 (setq cmnt-pos (and (c-backward-single-comment)
664 (- (point) (- mend1 mbeg1)))))
665 (delete-region mbeg4 mend4)
666 (delete-region mbeg1 mend1)
667 (setq eol-col (save-excursion (end-of-line) (current-column)))
669 ;; Necessary to put the closing brace before any line
670 ;; oriented comment to keep it syntactically significant.
671 ;; This isn't necessary for block comments, but the result
672 ;; looks nicer anyway.
673 (when cmnt-pos
674 (delete-char 1) ; the `}' has blundered into a comment
675 (goto-char cmnt-pos)
676 (setq cmnt-col (1+ (current-column)))
677 (setq cmnt-pos (1+ cmnt-pos)) ; we're inserting a `}'
678 (c-skip-ws-backward)
679 (insert-char ?\} 1) ; reinsert the `}' before the comment.
680 (setq cmnt-gap (- cmnt-col (current-column)))
681 (when (zerop cmnt-gap)
682 (insert-char ?\ 1) ; Put a space before a bare comment.
683 (setq cmnt-gap 1)))
685 (or (null c-max-one-liner-length)
686 (zerop c-max-one-liner-length)
687 (<= eol-col c-max-one-liner-length)
688 ;; Can we trim space before comment to make the line fit?
689 (and cmnt-gap
690 (< (- eol-col cmnt-gap) c-max-one-liner-length)
691 (progn (goto-char cmnt-pos)
692 (backward-delete-char-untabify
693 (- eol-col c-max-one-liner-length))
694 t))))
695 (goto-char (- (point-max) pos))))))
697 (defun c-electric-brace (arg)
698 "Insert a brace.
700 If `c-electric-flag' is non-nil, the brace is not inside a literal and a
701 numeric ARG hasn't been supplied, the command performs several electric
702 actions:
704 \(a) If the auto-newline feature is turned on (indicated by \"/la\" on
705 the mode line) newlines are inserted before and after the brace as
706 directed by the settings in `c-hanging-braces-alist'.
708 \(b) Any auto-newlines are indented. The original line is also
709 reindented unless `c-syntactic-indentation' is nil.
711 \(c) If auto-newline is turned on, various newline cleanups based on the
712 settings of `c-cleanup-list' are done."
714 (interactive "*P")
715 (let (safepos literal
716 ;; We want to inhibit blinking the paren since this would be
717 ;; most disruptive. We'll blink it ourselves later on.
718 (old-blink-paren blink-paren-function)
719 blink-paren-function case-fold-search)
721 (c-save-buffer-state ()
722 (setq safepos (c-safe-position (point) (c-parse-state))
723 literal (c-in-literal safepos)))
725 ;; Insert the brace. Note that expand-abbrev might reindent
726 ;; the line here if there's a preceding "else" or something.
727 (self-insert-command (prefix-numeric-value arg))
729 (when (and c-electric-flag (not literal) (not arg))
730 (if (not (looking-at "[ \t]*\\\\?$"))
731 (if c-syntactic-indentation
732 (indent-according-to-mode))
734 (let ( ;; shut this up too
735 (c-echo-syntactic-information-p nil)
736 newlines
737 ln-syntax br-syntax syntax) ; Syntactic context of the original line,
738 ; of the brace itself, of the line the brace ends up on.
739 (c-save-buffer-state ((c-syntactic-indentation-in-macros t)
740 (c-auto-newline-analysis t))
741 (setq ln-syntax (c-guess-basic-syntax)))
742 (if c-syntactic-indentation
743 (c-indent-line ln-syntax))
745 (when c-auto-newline
746 (backward-char)
747 (setq br-syntax (c-point-syntax)
748 newlines (c-brace-newlines br-syntax))
750 ;; Insert the BEFORE newline, if wanted, and reindent the newline.
751 (if (and (memq 'before newlines)
752 (> (current-column) (current-indentation)))
753 (if c-syntactic-indentation
754 ;; Only a plain newline for now - it's indented
755 ;; after the cleanups when the line has its final
756 ;; appearance.
757 (newline)
758 (c-newline-and-indent)))
759 (forward-char)
761 ;; `syntax' is the syntactic context of the line which ends up
762 ;; with the brace on it.
763 (setq syntax (if (memq 'before newlines) br-syntax ln-syntax))
765 ;; Do all appropriate clean ups
766 (let ((here (point))
767 (pos (- (point-max) (point)))
768 mbeg mend
771 ;; `}': clean up empty defun braces
772 (when (c-save-buffer-state ()
773 (and (memq 'empty-defun-braces c-cleanup-list)
774 (eq (c-last-command-char) ?\})
775 (c-intersect-lists '(defun-close class-close inline-close)
776 syntax)
777 (progn
778 (forward-char -1)
779 (c-skip-ws-backward)
780 (eq (char-before) ?\{))
781 ;; make sure matching open brace isn't in a comment
782 (not (c-in-literal))))
783 (delete-region (point) (1- here))
784 (setq here (- (point-max) pos)))
785 (goto-char here)
787 ;; `}': compact to a one-liner defun?
788 (save-match-data
789 (when
790 (and (eq (c-last-command-char) ?\})
791 (memq 'one-liner-defun c-cleanup-list)
792 (c-intersect-lists '(defun-close) syntax)
793 (c-try-one-liner))
794 (setq here (- (point-max) pos))))
796 ;; `{': clean up brace-else-brace and brace-elseif-brace
797 (when (eq (c-last-command-char) ?\{)
798 (cond
799 ((and (memq 'brace-else-brace c-cleanup-list)
800 (re-search-backward
801 (concat "}"
802 "\\([ \t\n]\\|\\\\\n\\)*"
803 "else"
804 "\\([ \t\n]\\|\\\\\n\\)*"
806 "\\=")
807 nil t))
808 (delete-region (match-beginning 0) (match-end 0))
809 (insert-and-inherit "} else {"))
810 ((and (memq 'brace-elseif-brace c-cleanup-list)
811 (progn
812 (goto-char (1- here))
813 (setq mend (point))
814 (c-skip-ws-backward)
815 (setq mbeg (point))
816 (eq (char-before) ?\)))
817 (zerop (c-save-buffer-state nil (c-backward-token-2 1 t)))
818 (eq (char-after) ?\()
819 ; (progn
820 ; (setq tmp (point))
821 (re-search-backward
822 (concat "}"
823 "\\([ \t\n]\\|\\\\\n\\)*"
824 "else"
825 "\\([ \t\n]\\|\\\\\n\\)+"
826 "if"
827 "\\([ \t\n]\\|\\\\\n\\)*"
828 "\\=")
829 nil t);)
830 ;(eq (match-end 0) tmp);
832 (delete-region mbeg mend)
833 (goto-char mbeg)
834 (insert ?\ ))))
836 (goto-char (- (point-max) pos))
838 ;; Indent the line after the cleanups since it might
839 ;; very well indent differently due to them, e.g. if
840 ;; c-indent-one-line-block is used together with the
841 ;; one-liner-defun cleanup.
842 (when c-syntactic-indentation
843 (c-indent-line)))
845 ;; does a newline go after the brace?
846 (if (memq 'after newlines)
847 (c-newline-and-indent))
848 ))))
850 ;; blink the paren
851 (and (eq (c-last-command-char) ?\})
852 (not executing-kbd-macro)
853 old-blink-paren
854 (save-excursion
855 (c-save-buffer-state nil
856 (c-backward-syntactic-ws safepos))
857 (funcall old-blink-paren)))))
859 (defun c-electric-slash (arg)
860 "Insert a slash character.
862 If the slash is inserted immediately after the comment prefix in a c-style
863 comment, the comment might get closed by removing whitespace and possibly
864 inserting a \"*\". See the variable `c-cleanup-list'.
866 Indent the line as a comment, if:
868 1. The slash is second of a \"//\" line oriented comment introducing
869 token and we are on a comment-only-line, or
871 2. The slash is part of a \"*/\" token that closes a block oriented
872 comment.
874 If a numeric ARG is supplied, point is inside a literal, or
875 `c-syntactic-indentation' is nil or `c-electric-flag' is nil, indentation
876 is inhibited."
877 (interactive "*P")
878 (let ((literal (c-save-buffer-state () (c-in-literal)))
879 indentp
880 ;; shut this up
881 (c-echo-syntactic-information-p nil))
883 ;; comment-close-slash cleanup? This DOESN'T need `c-electric-flag' or
884 ;; `c-syntactic-indentation' set.
885 (when (and (not arg)
886 (eq literal 'c)
887 (memq 'comment-close-slash c-cleanup-list)
888 (eq (c-last-command-char) ?/)
889 (looking-at (concat "[ \t]*\\("
890 (regexp-quote comment-end) "\\)?$"))
891 ; (eq c-block-comment-ender "*/") ; C-style comments ALWAYS end in */
892 (save-excursion
893 (save-restriction
894 (narrow-to-region (point-min) (point))
895 (back-to-indentation)
896 (looking-at (concat c-current-comment-prefix "[ \t]*$")))))
897 (delete-region (progn (forward-line 0) (point))
898 (progn (end-of-line) (point)))
899 (insert-char ?* 1)) ; the / comes later. ; Do I need a t (retain sticky properties) here?
901 (setq indentp (and (not arg)
902 c-syntactic-indentation
903 c-electric-flag
904 (eq (c-last-command-char) ?/)
905 (eq (char-before) (if literal ?* ?/))))
906 (self-insert-command (prefix-numeric-value arg))
907 (if indentp
908 (indent-according-to-mode))))
910 (defun c-electric-star (arg)
911 "Insert a star character.
912 If `c-electric-flag' and `c-syntactic-indentation' are both non-nil, and
913 the star is the second character of a C style comment starter on a
914 comment-only-line, indent the line as a comment. If a numeric ARG is
915 supplied, point is inside a literal, or `c-syntactic-indentation' is nil,
916 this indentation is inhibited."
918 (interactive "*P")
919 (self-insert-command (prefix-numeric-value arg))
920 ;; if we are in a literal, or if arg is given do not reindent the
921 ;; current line, unless this star introduces a comment-only line.
922 (if (c-save-buffer-state ()
923 (and c-syntactic-indentation
924 c-electric-flag
925 (not arg)
926 (eq (c-in-literal) 'c)
927 (eq (char-before) ?*)
928 (save-excursion
929 (forward-char -1)
930 (skip-chars-backward "*")
931 (if (eq (char-before) ?/)
932 (forward-char -1))
933 (skip-chars-backward " \t")
934 (bolp))))
935 (let (c-echo-syntactic-information-p) ; shut this up
936 (indent-according-to-mode))
939 (defun c-electric-semi&comma (arg)
940 "Insert a comma or semicolon.
942 If `c-electric-flag' is non-nil, point isn't inside a literal and a
943 numeric ARG hasn't been supplied, the command performs several electric
944 actions:
946 \(a) When the auto-newline feature is turned on (indicated by \"/la\" on
947 the mode line) a newline might be inserted. See the variable
948 `c-hanging-semi&comma-criteria' for how newline insertion is determined.
950 \(b) Any auto-newlines are indented. The original line is also
951 reindented unless `c-syntactic-indentation' is nil.
953 \(c) If auto-newline is turned on, a comma following a brace list or a
954 semicolon following a defun might be cleaned up, depending on the
955 settings of `c-cleanup-list'."
956 (interactive "*P")
957 (let* (lim literal c-syntactic-context
958 (here (point))
959 ;; shut this up
960 (c-echo-syntactic-information-p nil))
962 (c-save-buffer-state ()
963 (setq lim (c-most-enclosing-brace (c-parse-state))
964 literal (c-in-literal lim)))
966 (self-insert-command (prefix-numeric-value arg))
968 (if (and c-electric-flag (not literal) (not arg))
969 ;; do all cleanups and newline insertions if c-auto-newline is on.
970 (if (or (not c-auto-newline)
971 (not (looking-at "[ \t]*\\\\?$")))
972 (if c-syntactic-indentation
973 (c-indent-line))
974 ;; clean ups: list-close-comma or defun-close-semi
975 (let ((pos (- (point-max) (point))))
976 (if (c-save-buffer-state ()
977 (and (or (and
978 (eq (c-last-command-char) ?,)
979 (memq 'list-close-comma c-cleanup-list))
980 (and
981 (eq (c-last-command-char) ?\;)
982 (memq 'defun-close-semi c-cleanup-list)))
983 (progn
984 (forward-char -1)
985 (c-skip-ws-backward)
986 (eq (char-before) ?}))
987 ;; make sure matching open brace isn't in a comment
988 (not (c-in-literal lim))))
989 (delete-region (point) here))
990 (goto-char (- (point-max) pos)))
991 ;; reindent line
992 (when c-syntactic-indentation
993 (setq c-syntactic-context (c-guess-basic-syntax))
994 (c-indent-line c-syntactic-context))
995 ;; check to see if a newline should be added
996 (let ((criteria c-hanging-semi&comma-criteria)
997 answer add-newline-p)
998 (while criteria
999 (setq answer (funcall (car criteria)))
1000 ;; only nil value means continue checking
1001 (if (not answer)
1002 (setq criteria (cdr criteria))
1003 (setq criteria nil)
1004 ;; only 'stop specifically says do not add a newline
1005 (setq add-newline-p (not (eq answer 'stop)))
1007 (if add-newline-p
1008 (c-newline-and-indent))
1009 )))))
1011 (defun c-electric-colon (arg)
1012 "Insert a colon.
1014 If `c-electric-flag' is non-nil, the colon is not inside a literal and a
1015 numeric ARG hasn't been supplied, the command performs several electric
1016 actions:
1018 \(a) If the auto-newline feature is turned on (indicated by \"/la\" on
1019 the mode line) newlines are inserted before and after the colon based on
1020 the settings in `c-hanging-colons-alist'.
1022 \(b) Any auto-newlines are indented. The original line is also
1023 reindented unless `c-syntactic-indentation' is nil.
1025 \(c) If auto-newline is turned on, whitespace between two colons will be
1026 \"cleaned up\" leaving a scope operator, if this action is set in
1027 `c-cleanup-list'."
1029 (interactive "*P")
1030 (let* ((bod (c-point 'bod))
1031 (literal (c-save-buffer-state () (c-in-literal bod)))
1032 newlines is-scope-op
1033 ;; shut this up
1034 (c-echo-syntactic-information-p nil))
1035 (self-insert-command (prefix-numeric-value arg))
1036 ;; Any electric action?
1037 (if (and c-electric-flag (not literal) (not arg))
1038 ;; Unless we're at EOL, only re-indentation happens.
1039 (if (not (looking-at "[ \t]*\\\\?$"))
1040 (if c-syntactic-indentation
1041 (indent-according-to-mode))
1043 ;; scope-operator clean-up?
1044 (let ((pos (- (point-max) (point)))
1045 (here (point)))
1046 (if (c-save-buffer-state () ; Why do we need this? [ACM, 2003-03-12]
1047 (and c-auto-newline
1048 (memq 'scope-operator c-cleanup-list)
1049 (eq (char-before) ?:)
1050 (progn
1051 (forward-char -1)
1052 (c-skip-ws-backward)
1053 (eq (char-before) ?:))
1054 (not (c-in-literal))
1055 (not (eq (char-after (- (point) 2)) ?:))))
1056 (progn
1057 (delete-region (point) (1- here))
1058 (setq is-scope-op t)))
1059 (goto-char (- (point-max) pos)))
1061 ;; indent the current line if it's done syntactically.
1062 (if c-syntactic-indentation
1063 ;; Cannot use the same syntax analysis as we find below,
1064 ;; since that's made with c-syntactic-indentation-in-macros
1065 ;; always set to t.
1066 (indent-according-to-mode))
1068 ;; Calculate where, if anywhere, we want newlines.
1069 (c-save-buffer-state
1070 ((c-syntactic-indentation-in-macros t)
1071 (c-auto-newline-analysis t)
1072 ;; Turn on syntactic macro analysis to help with auto newlines
1073 ;; only.
1074 (syntax (c-guess-basic-syntax))
1075 (elem syntax))
1076 ;; Translate substatement-label to label for this operation.
1077 (while elem
1078 (if (eq (car (car elem)) 'substatement-label)
1079 (setcar (car elem) 'label))
1080 (setq elem (cdr elem)))
1081 ;; some language elements can only be determined by checking
1082 ;; the following line. Let's first look for ones that can be
1083 ;; found when looking on the line with the colon
1084 (setq newlines
1085 (and c-auto-newline
1086 (or (c-lookup-lists '(case-label label access-label)
1087 syntax c-hanging-colons-alist)
1088 (c-lookup-lists '(member-init-intro inher-intro)
1089 (progn
1090 (insert ?\n)
1091 (unwind-protect
1092 (c-guess-basic-syntax)
1093 (delete-char -1)))
1094 c-hanging-colons-alist)))))
1095 ;; does a newline go before the colon? Watch out for already
1096 ;; non-hung colons. However, we don't unhang them because that
1097 ;; would be a cleanup (and anti-social).
1098 (if (and (memq 'before newlines)
1099 (not is-scope-op)
1100 (save-excursion
1101 (skip-chars-backward ": \t")
1102 (not (bolp))))
1103 (let ((pos (- (point-max) (point))))
1104 (forward-char -1)
1105 (c-newline-and-indent)
1106 (goto-char (- (point-max) pos))))
1107 ;; does a newline go after the colon?
1108 (if (and (memq 'after (cdr-safe newlines))
1109 (not is-scope-op))
1110 (c-newline-and-indent))
1111 ))))
1113 (defun c-electric-lt-gt (arg)
1114 "Insert a \"<\" or \">\" character.
1115 If the current language uses angle bracket parens (e.g. template
1116 arguments in C++), try to find out if the inserted character is a
1117 paren and give it paren syntax if appropriate.
1119 If `c-electric-flag' and `c-syntactic-indentation' are both non-nil, the
1120 line will be reindented if the inserted character is a paren or if it
1121 finishes a C++ style stream operator in C++ mode. Exceptions are when a
1122 numeric argument is supplied, or the point is inside a literal."
1124 (interactive "*P")
1125 (let ((c-echo-syntactic-information-p nil)
1126 final-pos found-delim case-fold-search)
1128 (self-insert-command (prefix-numeric-value arg))
1129 (setq final-pos (point))
1131 ;;;; 2010-01-31: There used to be code here to put a syntax-table text
1132 ;;;; property on the new < or > and its mate (if any) when they are template
1133 ;;;; parens. This is now done in an after-change function.
1135 ;; Indent the line if appropriate.
1136 (when (and c-electric-flag c-syntactic-indentation c-recognize-<>-arglists)
1137 (setq found-delim
1138 (if (eq (c-last-command-char) ?<)
1139 ;; If a <, basically see if it's got "template" before it .....
1140 (or (and (progn
1141 (backward-char)
1142 (= (point)
1143 (progn (c-beginning-of-current-token) (point))))
1144 (progn
1145 (c-backward-token-2)
1146 (looking-at c-opt-<>-sexp-key)))
1147 ;; ..... or is a C++ << operator.
1148 (and (c-major-mode-is 'c++-mode)
1149 (progn
1150 (goto-char (1- final-pos))
1151 (c-beginning-of-current-token)
1152 (looking-at "<<"))
1153 (>= (match-end 0) final-pos)))
1155 ;; It's a >. Either a template/generic terminator ...
1156 (or (c-get-char-property (1- final-pos) 'syntax-table)
1157 ;; or a C++ >> operator.
1158 (and (c-major-mode-is 'c++-mode)
1159 (progn
1160 (goto-char (1- final-pos))
1161 (c-beginning-of-current-token)
1162 (looking-at ">>"))
1163 (>= (match-end 0) final-pos))))))
1165 (goto-char final-pos)
1166 (when found-delim
1167 (indent-according-to-mode)
1168 (when (and (eq (char-before) ?>)
1169 (not executing-kbd-macro)
1170 blink-paren-function)
1171 ;; From now (2016-01-01), the syntax-table text properties on < and >
1172 ;; are applied in an after-change function, not during redisplay. Hence
1173 ;; we no longer need to call (sit-for 0) for blink paren to work.
1174 (funcall blink-paren-function)))))
1176 (defun c-electric-paren (arg)
1177 "Insert a parenthesis.
1179 If `c-syntactic-indentation' and `c-electric-flag' are both non-nil, the
1180 line is reindented unless a numeric ARG is supplied, or the parenthesis
1181 is inserted inside a literal.
1183 Whitespace between a function name and the parenthesis may get added or
1184 removed; see the variable `c-cleanup-list'.
1186 Also, if `c-electric-flag' and `c-auto-newline' are both non-nil, some
1187 newline cleanups are done if appropriate; see the variable `c-cleanup-list'."
1188 (interactive "*P")
1189 (let ((literal (c-save-buffer-state () (c-in-literal)))
1190 ;; shut this up
1191 (c-echo-syntactic-information-p nil)
1192 case-fold-search)
1193 (self-insert-command (prefix-numeric-value arg))
1195 (if (and (not arg) (not literal))
1196 (let* ( ;; We want to inhibit blinking the paren since this will
1197 ;; be most disruptive. We'll blink it ourselves
1198 ;; afterwards.
1199 (old-blink-paren blink-paren-function)
1200 blink-paren-function)
1201 (if (and c-syntactic-indentation c-electric-flag)
1202 (indent-according-to-mode))
1204 ;; If we're at EOL, check for new-line clean-ups.
1205 (when (and c-electric-flag c-auto-newline
1206 (looking-at "[ \t]*\\\\?$"))
1208 ;; clean up brace-elseif-brace
1209 (when
1210 (and (memq 'brace-elseif-brace c-cleanup-list)
1211 (eq (c-last-command-char) ?\()
1212 (re-search-backward
1213 (concat "}"
1214 "\\([ \t\n]\\|\\\\\n\\)*"
1215 "else"
1216 "\\([ \t\n]\\|\\\\\n\\)+"
1217 "if"
1218 "\\([ \t\n]\\|\\\\\n\\)*"
1220 "\\=")
1221 nil t)
1222 (not (c-save-buffer-state () (c-in-literal))))
1223 (delete-region (match-beginning 0) (match-end 0))
1224 (insert-and-inherit "} else if ("))
1226 ;; clean up brace-catch-brace
1227 (when
1228 (and (memq 'brace-catch-brace c-cleanup-list)
1229 (eq (c-last-command-char) ?\()
1230 (re-search-backward
1231 (concat "}"
1232 "\\([ \t\n]\\|\\\\\n\\)*"
1233 "catch"
1234 "\\([ \t\n]\\|\\\\\n\\)*"
1236 "\\=")
1237 nil t)
1238 (not (c-save-buffer-state () (c-in-literal))))
1239 (delete-region (match-beginning 0) (match-end 0))
1240 (insert-and-inherit "} catch (")))
1242 ;; Check for clean-ups at function calls. These two DON'T need
1243 ;; `c-electric-flag' or `c-syntactic-indentation' set.
1244 ;; Point is currently just after the inserted paren.
1245 (let (beg (end (1- (point))))
1246 (cond
1248 ;; space-before-funcall clean-up?
1249 ((and (memq 'space-before-funcall c-cleanup-list)
1250 (eq (c-last-command-char) ?\()
1251 (save-excursion
1252 (backward-char)
1253 (skip-chars-backward " \t")
1254 (setq beg (point))
1255 (and (c-save-buffer-state () (c-on-identifier))
1256 ;; Don't add a space into #define FOO()....
1257 (not (and (c-beginning-of-macro)
1258 (c-forward-over-cpp-define-id)
1259 (eq (point) beg))))))
1260 (save-excursion
1261 (delete-region beg end)
1262 (goto-char beg)
1263 (insert ?\ )))
1265 ;; compact-empty-funcall clean-up?
1266 ((c-save-buffer-state ()
1267 (and (memq 'compact-empty-funcall c-cleanup-list)
1268 (eq (c-last-command-char) ?\))
1269 (save-excursion
1270 (c-safe (backward-char 2))
1271 (when (looking-at "()")
1272 (setq end (point))
1273 (skip-chars-backward " \t")
1274 (setq beg (point))
1275 (c-on-identifier)))))
1276 (delete-region beg end))))
1277 (and (eq last-input-event ?\))
1278 (not executing-kbd-macro)
1279 old-blink-paren
1280 (funcall old-blink-paren))))))
1282 (defun c-electric-continued-statement ()
1283 "Reindent the current line if appropriate.
1285 This function is used to reindent the line after a keyword which
1286 continues an earlier statement is typed, e.g. an \"else\" or the
1287 \"while\" in a do-while block.
1289 The line is reindented if there is nothing but whitespace before the
1290 keyword on the line, the keyword is not inserted inside a literal, and
1291 `c-electric-flag' and `c-syntactic-indentation' are both non-nil."
1292 (let (;; shut this up
1293 (c-echo-syntactic-information-p nil))
1294 (when (c-save-buffer-state ()
1295 (and c-electric-flag
1296 c-syntactic-indentation
1297 (not (eq (c-last-command-char) ?_))
1298 (= (save-excursion
1299 (skip-syntax-backward "w")
1300 (point))
1301 (c-point 'boi))
1302 (not (c-in-literal (c-point 'bod)))))
1303 ;; Have to temporarily insert a space so that
1304 ;; c-guess-basic-syntax recognizes the keyword. Follow the
1305 ;; space with a nonspace to avoid messing up any whitespace
1306 ;; sensitive meddling that might be done, e.g. by
1307 ;; `c-backslash-region'.
1308 (insert-and-inherit " x")
1309 (unwind-protect
1310 (indent-according-to-mode)
1311 (delete-char -2)))))
1315 (declare-function subword-forward "subword" (&optional arg))
1316 (declare-function subword-backward "subword" (&optional arg))
1318 (cond
1319 ((and (fboundp 'subword-mode) (not (fboundp 'c-subword-mode)))
1320 ;; Recent Emacsen come with their own subword support. Use that.
1321 (define-obsolete-function-alias 'c-subword-mode 'subword-mode "24.3")
1322 (define-obsolete-variable-alias 'c-subword-mode 'subword-mode "24.3"))
1324 ;; Autoload directive for emacsen that doesn't have an older CC Mode
1325 ;; version in the dist.
1326 (autoload 'c-subword-mode "cc-subword"
1327 "Mode enabling subword movement and editing keys." t)))
1329 (declare-function c-forward-subword "ext:cc-subword" (&optional arg))
1330 (declare-function c-backward-subword "ext:cc-subword" (&optional arg))
1332 ;; "nomenclature" functions + c-scope-operator.
1333 (defun c-forward-into-nomenclature (&optional arg)
1334 "Compatibility alias for `c-forward-subword'."
1335 (interactive "p")
1336 (if (fboundp 'subword-mode)
1337 (progn
1338 (require 'subword)
1339 (subword-forward arg))
1340 (require 'cc-subword)
1341 (c-forward-subword arg)))
1342 (make-obsolete 'c-forward-into-nomenclature
1343 (if (fboundp 'subword-mode) 'subword-forward 'c-forward-subword)
1344 "23.2")
1346 (defun c-backward-into-nomenclature (&optional arg)
1347 "Compatibility alias for `c-backward-subword'."
1348 (interactive "p")
1349 (if (fboundp 'subword-mode)
1350 (progn
1351 (require 'subword)
1352 (subword-backward arg))
1353 (require 'cc-subword)
1354 (c-backward-subword arg)))
1355 (make-obsolete
1356 'c-backward-into-nomenclature
1357 (if (fboundp 'subword-mode) 'subword-backward 'c-backward-subword) "23.2")
1359 (defun c-scope-operator ()
1360 "Insert a double colon scope operator at point.
1361 No indentation or other \"electric\" behavior is performed."
1362 (interactive "*")
1363 (insert-and-inherit "::"))
1366 ;; Movement (etc.) by defuns.
1367 (defun c-in-function-trailer-p (&optional lim)
1368 ;; Return non-nil if point is between the closing brace and the semicolon of
1369 ;; a brace construct which needs a semicolon, e.g. within the "variables"
1370 ;; portion of a declaration like "struct foo {...} bar ;".
1372 ;; Return the position of the main declaration. Otherwise, return nil.
1373 ;; Point is assumed to be at the top level and outside of any macro or
1374 ;; literal.
1376 ;; If LIM is non-nil, it is the bound on a the backward search for the
1377 ;; beginning of the declaration.
1379 ;; This function might do hidden buffer changes.
1380 (and c-opt-block-decls-with-vars-key
1381 (save-excursion
1382 (c-syntactic-skip-backward "^;}" lim)
1383 (let ((eo-block (point))
1384 bod)
1385 (and (eq (char-before) ?\})
1386 (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1387 (setq bod (point))
1388 ;; Look for struct or union or ... If we find one, it might
1389 ;; be the return type of a function, or the like. Exclude
1390 ;; this case.
1391 (c-syntactic-re-search-forward
1392 (concat "[;=([{]\\|\\("
1393 c-opt-block-decls-with-vars-key
1394 "\\)")
1395 eo-block t t t)
1396 (match-beginning 1) ; Is there a "struct" etc., somewhere?
1397 (not (eq (char-before) ?_))
1398 (c-syntactic-re-search-forward "[;=([{]" eo-block t t t)
1399 (eq (char-before) ?\{)
1400 bod)))))
1402 (defun c-where-wrt-brace-construct ()
1403 ;; Determine where we are with respect to functions (or other brace
1404 ;; constructs, included in the term "function" in the rest of this comment).
1405 ;; Point is assumed to be outside any macro or literal.
1406 ;; This is used by c-\(beginning\|end\)-of-defun.
1408 ;; Return one of these symbols:
1409 ;; at-header : we're at the start of a function's header.
1410 ;; in-header : we're inside a function's header, this extending right
1411 ;; up to the brace. This bit includes any k&r declarations.
1412 ;; in-block : we're inside a function's brace block.
1413 ;; in-trailer : we're in the area between the "}" and ";" of something
1414 ;; like "struct foo {...} bar, baz;".
1415 ;; at-function-end : we're just after the closing brace (or semicolon) that
1416 ;; terminates the function.
1417 ;; outwith-function: we're not at or in any function. Being inside a
1418 ;; non-brace construct also counts as 'outwith-function'.
1420 ;; This function might do hidden buffer changes.
1421 (save-excursion
1422 (let* (kluge-start
1423 decl-result brace-decl-p
1424 (start (point))
1425 (paren-state (c-parse-state))
1426 (least-enclosing (c-least-enclosing-brace paren-state)))
1428 (cond
1429 ((and least-enclosing
1430 (eq (char-after least-enclosing) ?\{))
1431 'in-block)
1432 ((c-in-function-trailer-p)
1433 'in-trailer)
1434 ((and (not least-enclosing)
1435 (consp paren-state)
1436 (consp (car paren-state))
1437 (eq start (cdar paren-state)))
1438 'at-function-end)
1440 ;; Find the start of the current declaration. NOTE: If we're in the
1441 ;; variables after a "struct/eval" type block, we don't get to the
1442 ;; real declaration here - we detect and correct for this later.
1444 ;;If we're in the parameters' parens, move back out of them.
1445 (if least-enclosing (goto-char least-enclosing))
1446 ;; Kluge so that c-beginning-of-decl-1 won't go back if we're already
1447 ;; at a declaration.
1448 (if (or (and (eolp) (not (eobp))) ; EOL is matched by "\\s>"
1449 (not (looking-at
1450 "\\([;#]\\|\\'\\|\\s(\\|\\s)\\|\\s\"\\|\\s\\\\|\\s$\\|\\s<\\|\\s>\\|\\s!\\)")))
1451 (forward-char))
1452 (setq kluge-start (point))
1453 (setq decl-result
1454 (car (c-beginning-of-decl-1
1455 ;; NOTE: If we're in a K&R region, this might be the start
1456 ;; of a parameter declaration, not the actual function.
1457 ;; It might also leave us at a label or "label" like
1458 ;; "private:".
1459 (and least-enclosing ; LIMIT for c-b-of-decl-1
1460 (c-safe-position least-enclosing paren-state)))))
1462 ;; Has the declaration we've gone back to got braces?
1463 (or (eq decl-result 'label)
1464 (setq brace-decl-p
1465 (save-excursion
1466 (and (c-syntactic-re-search-forward "[;{]" nil t t)
1467 (or (eq (char-before) ?\{)
1468 (and c-recognize-knr-p
1469 ;; Might have stopped on the
1470 ;; ';' in a K&R argdecl. In
1471 ;; that case the declaration
1472 ;; should contain a block.
1473 (c-in-knr-argdecl)))))))
1475 (cond
1476 ((or (eq decl-result 'label) ; e.g. "private:" or invalid syntax.
1477 (= (point) kluge-start)) ; might be BOB or unbalanced parens.
1478 'outwith-function)
1479 ((eq decl-result 'same)
1480 (if brace-decl-p
1481 (if (eq (point) start)
1482 'at-header
1483 'in-header)
1484 'outwith-function))
1485 ((eq decl-result 'previous)
1486 (if (and (not brace-decl-p)
1487 (c-in-function-trailer-p))
1488 'at-function-end
1489 'outwith-function))
1490 (t (error
1491 "c-where-wrt-brace-construct: c-beginning-of-decl-1 returned %s"
1492 decl-result))))))))
1494 (defun c-backward-to-nth-BOF-{ (n where)
1495 ;; Skip to the opening brace of the Nth function before point. If
1496 ;; point is inside a function, this counts as the first. Point must be
1497 ;; outside any comment/string or macro.
1499 ;; N must be strictly positive.
1500 ;; WHERE describes the position of point, one of the symbols `at-header',
1501 ;; `in-header', `in-block', `in-trailer', `at-function-end',
1502 ;; `outwith-function' as returned by c-where-wrt-brace-construct.
1504 ;; If we run out of functions, leave point at BOB. Return zero on success,
1505 ;; otherwise the number of {s still to go.
1507 ;; This function may do hidden buffer changes
1508 (cond
1509 ;; What we do to go back the first defun depends on where we start.
1510 ((bobp))
1511 ((eq where 'in-block)
1512 (goto-char (c-least-enclosing-brace (c-parse-state)))
1513 (setq n (1- n)))
1514 ((eq where 'in-header)
1515 (c-syntactic-re-search-forward "{")
1516 (backward-char)
1517 (setq n (1- n)))
1518 ((memq where '(at-header outwith-function at-function-end in-trailer))
1519 (c-syntactic-skip-backward "^}")
1520 (when (eq (char-before) ?\})
1521 (backward-sexp)
1522 (setq n (1- n))))
1523 (t (error "Unknown `where' %s in c-backward-to-nth-EOF-{" where)))
1525 ;; Each time round the loop, go back to a "{" at the outermost level.
1526 (while (and (> n 0) (not (bobp)))
1527 (c-parse-state) ; This call speeds up the following one
1528 ; by a factor of ~6. Hmmm. 2006/4/5.
1529 (c-syntactic-skip-backward "^}")
1530 (when (eq (char-before) ?\})
1531 (backward-sexp)
1532 (setq n (1- n))))
1535 (defun c-narrow-to-most-enclosing-decl-block (&optional inclusive level)
1536 ;; If we are inside a decl-block (in the sense of c-looking-at-decl-block),
1537 ;; i.e. something like namespace{} or extern{}, narrow to the insides of
1538 ;; that block (NOT including the enclosing braces) if INCLUSIVE is nil,
1539 ;; otherwise include the braces and the declaration which introduces them.
1540 ;; If the closing brace is missing, (point-max) is used instead. LEVEL, if
1541 ;; non-nil, says narrow to the LEVELth decl-block outward, default value
1542 ;; being 1.
1543 (let ((paren-state (c-parse-state))
1544 encl-decl)
1545 (setq level (or level 1))
1546 (while (> level 0)
1547 (setq encl-decl (c-most-enclosing-decl-block paren-state))
1548 (if encl-decl
1549 (progn
1550 (while (> (c-pull-open-brace paren-state) encl-decl))
1551 (setq level (1- level)))
1552 (setq level 0)))
1553 (if encl-decl
1554 (save-excursion
1555 (narrow-to-region
1556 (if inclusive
1557 (progn (goto-char encl-decl)
1558 (c-beginning-of-decl-1)
1559 (point))
1560 (1+ encl-decl))
1561 (progn
1562 (goto-char encl-decl)
1563 (or (c-safe (forward-list)
1564 (if inclusive
1565 (point)
1566 (1- (point))))
1567 (point-max))))))))
1569 (defun c-widen-to-enclosing-decl-scope (paren-state orig-point-min orig-point-max)
1570 ;; Narrow the buffer to the innermost declaration scope (e.g. a class, a
1571 ;; namespace or the "whole buffer") recorded in PAREN-STATE, the bounding
1572 ;; braces NOT being included in the resulting region. On no account may the
1573 ;; final region exceed that bounded by ORIG-POINT-MIN, ORIG-POINT-MAX.
1574 ;; PAREN-STATE is a list of buffer positions in the style of
1575 ;; (c-parse-state), one of which will be that of the desired opening brace,
1576 ;; if there is one.
1578 ;; Return the position of the enclosing opening brace, or nil
1579 (let (encl-decl) ; putative position of decl-scope's opening brace.
1580 (save-restriction
1581 (narrow-to-region orig-point-min orig-point-max)
1582 (setq encl-decl (and paren-state
1583 (c-most-enclosing-decl-block paren-state))))
1584 (if encl-decl
1585 (progn
1586 (widen)
1587 (narrow-to-region (1+ encl-decl)
1588 (save-excursion
1589 (goto-char encl-decl)
1590 (or (c-safe (forward-list)
1591 (1- (point)))
1592 orig-point-max)))
1593 encl-decl)
1594 (narrow-to-region orig-point-min orig-point-max)
1595 nil)))
1597 (eval-and-compile
1598 (defmacro c-while-widening-to-decl-block (condition)
1599 ;; Repeatedly evaluate CONDITION until it returns nil. After each
1600 ;; evaluation, if `c-defun-tactic' is set appropriately, widen to innards
1601 ;; of the next enclosing declaration block (e.g. namespace, class), or the
1602 ;; buffer's original restriction.
1604 ;; This is a very special purpose macro, which assumes the existence of
1605 ;; several variables. It is for use only in c-beginning-of-defun and
1606 ;; c-end-of-defun.
1607 `(while
1608 (and ,condition
1609 (eq c-defun-tactic 'go-outward)
1610 lim)
1611 (setq paren-state (c-whack-state-after lim paren-state))
1612 (setq lim (c-widen-to-enclosing-decl-scope
1613 paren-state orig-point-min orig-point-max))
1614 (setq where 'in-block))))
1616 (defun c-beginning-of-defun (&optional arg)
1617 "Move backward to the beginning of a defun.
1618 Every top level declaration that contains a brace paren block is
1619 considered to be a defun.
1621 With a positive argument, move backward that many defuns. A negative
1622 argument -N means move forward to the Nth following beginning. Return
1623 t unless search stops due to beginning or end of buffer.
1625 Unlike the built-in `beginning-of-defun' this tries to be smarter
1626 about finding the char with open-parenthesis syntax that starts the
1627 defun."
1629 (interactive "p")
1630 (or arg (setq arg 1))
1632 (or (not (eq this-command 'c-beginning-of-defun))
1633 (eq last-command 'c-beginning-of-defun)
1634 (c-region-is-active-p)
1635 (push-mark))
1637 (c-save-buffer-state
1638 (beginning-of-defun-function
1639 end-of-defun-function
1640 (paren-state (c-parse-state))
1641 (orig-point-min (point-min)) (orig-point-max (point-max))
1642 lim ; Position of { which has been widened to.
1643 where pos case-fold-search)
1645 (save-restriction
1646 (if (eq c-defun-tactic 'go-outward)
1647 (setq lim (c-widen-to-enclosing-decl-scope ; e.g. class, namespace.
1648 paren-state orig-point-min orig-point-max)))
1650 ;; Move back out of any macro/comment/string we happen to be in.
1651 (c-beginning-of-macro)
1652 (setq pos (c-literal-start))
1653 (if pos (goto-char pos))
1655 (setq where (c-where-wrt-brace-construct))
1657 (if (< arg 0)
1658 ;; Move forward to the closing brace of a function.
1659 (progn
1660 (if (memq where '(at-function-end outwith-function))
1661 (setq arg (1+ arg)))
1662 (if (< arg 0)
1663 (c-while-widening-to-decl-block
1664 (< (setq arg (- (c-forward-to-nth-EOF-} (- arg) where))) 0)))
1665 ;; Move forward to the next opening brace....
1666 (when (and (= arg 0)
1667 (progn
1668 (c-while-widening-to-decl-block
1669 (not (c-syntactic-re-search-forward "{" nil 'eob)))
1670 (eq (char-before) ?{)))
1671 (backward-char)
1672 ;; ... and backward to the function header.
1673 (c-beginning-of-decl-1)
1676 ;; Move backward to the opening brace of a function, making successively
1677 ;; larger portions of the buffer visible as necessary.
1678 (when (> arg 0)
1679 (c-while-widening-to-decl-block
1680 (> (setq arg (c-backward-to-nth-BOF-{ arg where)) 0)))
1682 (when (eq arg 0)
1683 ;; Go backward to this function's header.
1684 (c-beginning-of-decl-1)
1686 (setq pos (point))
1687 ;; We're now there, modulo comments and whitespace.
1688 ;; Try to be line oriented; position point at the closest
1689 ;; preceding boi that isn't inside a comment, but if we hit
1690 ;; the previous declaration then we use the current point
1691 ;; instead.
1692 (while (and (/= (point) (c-point 'boi))
1693 (c-backward-single-comment)))
1694 (if (/= (point) (c-point 'boi))
1695 (goto-char pos)))
1697 (c-keep-region-active)
1698 (= arg 0)))))
1700 (defun c-forward-to-nth-EOF-} (n where)
1701 ;; Skip to the closing brace of the Nth function after point. If
1702 ;; point is inside a function, this counts as the first. Point must be
1703 ;; outside any comment/string or macro.
1705 ;; N must be strictly positive.
1706 ;; WHERE describes the position of point, one of the symbols `at-header',
1707 ;; `in-header', `in-block', `in-trailer', `at-function-end',
1708 ;; `outwith-function' as returned by c-where-wrt-brace-construct.
1710 ;; If we run out of functions, leave point at EOB. Return zero on success,
1711 ;; otherwise the number of }s still to go.
1713 ;; This function may do hidden buffer changes.
1715 (cond
1716 ;; What we do to go forward over the first defun depends on where we
1717 ;; start. We go to the closing brace of that defun, even when we go
1718 ;; backwards to it (in a "struct foo {...} bar ;").
1719 ((eobp))
1720 ((eq where 'in-block)
1721 (goto-char (c-least-enclosing-brace (c-parse-state)))
1722 (forward-sexp)
1723 (setq n (1- n)))
1724 ((eq where 'in-trailer)
1725 (c-syntactic-skip-backward "^}")
1726 (setq n (1- n)))
1727 ((memq where '(at-function-end outwith-function at-header in-header))
1728 (when (c-syntactic-re-search-forward "{" nil 'eob)
1729 (backward-char)
1730 (forward-sexp)
1731 (setq n (1- n))))
1732 (t (error "c-forward-to-nth-EOF-}: `where' is %s" where)))
1734 ;; Each time round the loop, go forward to a "}" at the outermost level.
1735 (while (and (> n 0) (not (eobp)))
1736 ;(c-parse-state) ; This call speeds up the following one by a factor
1737 ; of ~6. Hmmm. 2006/4/5.
1738 (when (c-syntactic-re-search-forward "{" nil 'eob)
1739 (backward-char)
1740 (forward-sexp))
1741 (setq n (1- n)))
1744 (defun c-end-of-defun (&optional arg)
1745 "Move forward to the end of a top level declaration.
1746 With argument, do it that many times. Negative argument -N means move
1747 back to Nth preceding end. Returns t unless search stops due to
1748 beginning or end of buffer.
1750 An end of a defun occurs right after the close-parenthesis that matches
1751 the open-parenthesis that starts a defun; see `beginning-of-defun'."
1752 (interactive "p")
1753 (or arg (setq arg 1))
1755 (or (not (eq this-command 'c-end-of-defun))
1756 (eq last-command 'c-end-of-defun)
1757 (c-region-is-active-p)
1758 (push-mark))
1760 (c-save-buffer-state
1761 (beginning-of-defun-function
1762 end-of-defun-function
1763 (paren-state (c-parse-state))
1764 (orig-point-min (point-min)) (orig-point-max (point-max))
1766 where pos case-fold-search)
1768 (save-restriction
1769 (if (eq c-defun-tactic 'go-outward)
1770 (setq lim (c-widen-to-enclosing-decl-scope ; e.g. class, namespace
1771 paren-state orig-point-min orig-point-max)))
1773 ;; Move back out of any macro/comment/string we happen to be in.
1774 (c-beginning-of-macro)
1775 (setq pos (c-literal-start))
1776 (if pos (goto-char pos))
1778 (setq where (c-where-wrt-brace-construct))
1780 (if (< arg 0)
1781 ;; Move backwards to the } of a function
1782 (progn
1783 (if (memq where '(at-header outwith-function))
1784 (setq arg (1+ arg)))
1785 (if (< arg 0)
1786 (c-while-widening-to-decl-block
1787 (< (setq arg (- (c-backward-to-nth-BOF-{ (- arg) where))) 0)))
1788 (if (= arg 0)
1789 (c-while-widening-to-decl-block
1790 (progn (c-syntactic-skip-backward "^}")
1791 (not (eq (char-before) ?}))))))
1793 ;; Move forward to the } of a function
1794 (if (> arg 0)
1795 (c-while-widening-to-decl-block
1796 (> (setq arg (c-forward-to-nth-EOF-} arg where)) 0))))
1798 ;; Do we need to move forward from the brace to the semicolon?
1799 (when (eq arg 0)
1800 (if (c-in-function-trailer-p) ; after "}" of struct/enum, etc.
1801 (c-syntactic-re-search-forward ";"))
1803 (setq pos (point))
1804 ;; We're there now, modulo comments and whitespace.
1805 ;; Try to be line oriented; position point after the next
1806 ;; newline that isn't inside a comment, but if we hit the
1807 ;; next declaration then we use the current point instead.
1808 (while (and (not (bolp))
1809 (not (looking-at "\\s *$"))
1810 (c-forward-single-comment)))
1811 (cond ((bolp))
1812 ((looking-at "\\s *$")
1813 (forward-line 1))
1815 (goto-char pos))))
1817 (c-keep-region-active)
1818 (= arg 0))))
1820 (defun c-defun-name ()
1821 "Return the name of the current defun, or NIL if there isn't one.
1822 \"Defun\" here means a function, or other top level construct
1823 with a brace block."
1824 (interactive)
1825 (c-save-buffer-state
1826 (beginning-of-defun-function end-of-defun-function
1827 where pos name-end case-fold-search)
1829 (save-restriction
1830 (widen)
1831 (save-excursion
1832 ;; Move back out of any macro/comment/string we happen to be in.
1833 (c-beginning-of-macro)
1834 (setq pos (c-literal-start))
1835 (if pos (goto-char pos))
1837 (setq where (c-where-wrt-brace-construct))
1839 ;; Move to the beginning of the current defun, if any, if we're not
1840 ;; already there.
1841 (if (eq where 'outwith-function)
1843 (unless (eq where 'at-header)
1844 (c-backward-to-nth-BOF-{ 1 where)
1845 (c-beginning-of-decl-1))
1846 (when (looking-at c-typedef-key)
1847 (goto-char (match-end 0))
1848 (c-forward-syntactic-ws))
1850 ;; Pick out the defun name, according to the type of defun.
1851 (cond
1852 ;; struct, union, enum, or similar:
1853 ((looking-at c-type-prefix-key)
1854 (let ((key-pos (point)))
1855 (c-forward-token-2 1) ; over "struct ".
1856 (cond
1857 ((looking-at c-symbol-key) ; "struct foo { ..."
1858 (buffer-substring-no-properties key-pos (match-end 0)))
1859 ((eq (char-after) ?{) ; "struct { ... } foo"
1860 (when (c-go-list-forward)
1861 (c-forward-syntactic-ws)
1862 (when (looking-at c-symbol-key) ; a bit bogus - there might
1863 ; be several identifiers.
1864 (match-string-no-properties 0)))))))
1866 ((looking-at "DEFUN\\s-*(") ;"DEFUN\\_>") think of XEmacs!
1867 ;; DEFUN ("file-name-directory", Ffile_name_directory, Sfile_name_directory, ...) ==> Ffile_name_directory
1868 ;; DEFUN(POSIX::STREAM-LOCK, stream lockp &key BLOCK SHARED START LENGTH) ==> POSIX::STREAM-LOCK
1869 (down-list 1)
1870 (c-forward-syntactic-ws)
1871 (when (eq (char-after) ?\")
1872 (forward-sexp 1)
1873 (c-forward-token-2)) ; over the comma and following WS.
1874 (buffer-substring-no-properties
1875 (point)
1876 (progn
1877 (c-forward-token-2)
1878 (when (looking-at ":") ; CLISP: DEFUN(PACKAGE:LISP-SYMBOL,...)
1879 (skip-chars-forward "^,"))
1880 (c-backward-syntactic-ws)
1881 (point))))
1883 ((looking-at "DEF[a-zA-Z0-9_]* *( *\\([^, ]*\\) *,")
1884 ;; DEFCHECKER(sysconf_arg,prefix=_SC,default=, ...) ==> sysconf_arg
1885 ;; DEFFLAGSET(syslog_opt_flags,LOG_PID ...) ==> syslog_opt_flags
1886 (match-string-no-properties 1))
1888 ;; Objc selectors.
1889 ((assq 'objc-method-intro (c-guess-basic-syntax))
1890 (let ((bound (save-excursion (c-end-of-statement) (point)))
1891 (kw-re (concat "\\(?:" c-symbol-key "\\)?:"))
1892 (stretches))
1893 (when (c-syntactic-re-search-forward c-symbol-key bound t t t)
1894 (push (match-string-no-properties 0) stretches)
1895 (while (c-syntactic-re-search-forward kw-re bound t t t)
1896 (push (match-string-no-properties 0) stretches)))
1897 (apply 'concat (nreverse stretches))))
1900 ;; Normal function or initializer.
1901 (when (c-syntactic-re-search-forward "[{(]" nil t)
1902 (backward-char)
1903 (c-backward-syntactic-ws)
1904 (when (eq (char-before) ?\=) ; struct foo bar = {0, 0} ;
1905 (c-backward-token-2)
1906 (c-backward-syntactic-ws))
1907 (setq name-end (point))
1908 (c-back-over-compound-identifier)
1909 (and (looking-at c-symbol-start)
1910 (buffer-substring-no-properties (point) name-end))))))))))
1912 (defun c-declaration-limits (near)
1913 ;; Return a cons of the beginning and end positions of the current
1914 ;; top level declaration or macro. If point is not inside any then
1915 ;; nil is returned, unless NEAR is non-nil in which case the closest
1916 ;; following one is chosen instead (if there is any). The end
1917 ;; position is at the next line, providing there is one before the
1918 ;; declaration.
1920 ;; This function might do hidden buffer changes.
1921 (save-excursion
1922 (save-restriction
1923 (let ((start (point))
1924 (paren-state (c-parse-state))
1925 lim pos end-pos where)
1926 ;; Narrow enclosing brace blocks out, as required by the values of
1927 ;; `c-defun-tactic', `near', and the position of point.
1928 (when (eq c-defun-tactic 'go-outward)
1929 (let ((bounds
1930 (save-restriction
1931 (if (and (not (save-excursion (c-beginning-of-macro)))
1932 (save-restriction
1933 (c-narrow-to-most-enclosing-decl-block)
1934 (memq (c-where-wrt-brace-construct)
1935 '(at-function-end outwith-function)))
1936 (not near))
1937 (c-narrow-to-most-enclosing-decl-block nil 2)
1938 (c-narrow-to-most-enclosing-decl-block))
1939 (cons (point-min) (point-max)))))
1940 (narrow-to-region (car bounds) (cdr bounds))))
1941 (setq paren-state (c-parse-state))
1944 ;; Note: Some code duplication in `c-beginning-of-defun' and
1945 ;; `c-end-of-defun'.
1946 (catch 'exit
1947 (unless (c-safe
1948 (goto-char (c-least-enclosing-brace paren-state))
1949 ;; If we moved to the outermost enclosing paren
1950 ;; then we can use c-safe-position to set the
1951 ;; limit. Can't do that otherwise since the
1952 ;; earlier paren pair on paren-state might very
1953 ;; well be part of the declaration we should go
1954 ;; to.
1955 (setq lim (c-safe-position (point) paren-state))
1957 ;; At top level. Make sure we aren't inside a literal.
1958 (setq pos (c-literal-start
1959 (c-safe-position (point) paren-state)))
1960 (if pos (goto-char pos)))
1962 (when (c-beginning-of-macro)
1963 (throw 'exit
1964 (cons (point)
1965 (save-excursion
1966 (c-end-of-macro)
1967 (forward-line 1)
1968 (point)))))
1970 (setq pos (point))
1971 (setq where (and (not (save-excursion (c-beginning-of-macro)))
1972 (c-where-wrt-brace-construct)))
1973 (when (and (not (eq where 'at-header))
1974 (or (and near
1975 (memq where
1976 '(at-function-end outwith-function)))
1977 (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1978 (= pos (point))))
1979 ;; We moved back over the previous defun. Skip to the next
1980 ;; one. Not using c-forward-syntactic-ws here since we
1981 ;; should not skip a macro. We can also be directly after
1982 ;; the block in a `c-opt-block-decls-with-vars-key'
1983 ;; declaration, but then we won't move significantly far
1984 ;; here.
1985 (goto-char pos)
1986 (c-forward-comments)
1988 (when (and near (c-beginning-of-macro))
1989 (throw 'exit
1990 (cons (point)
1991 (save-excursion
1992 (c-end-of-macro)
1993 (forward-line 1)
1994 (point))))))
1996 (if (eobp) (throw 'exit nil))
1998 ;; Check if `c-beginning-of-decl-1' put us after the block in a
1999 ;; declaration that doesn't end there. We're searching back and
2000 ;; forth over the block here, which can be expensive.
2001 (setq pos (point))
2002 (if (and c-opt-block-decls-with-vars-key
2003 (progn
2004 (c-backward-syntactic-ws)
2005 (eq (char-before) ?}))
2006 (eq (car (c-beginning-of-decl-1))
2007 'previous)
2008 (save-excursion
2009 (c-end-of-decl-1)
2010 (and (> (point) pos)
2011 (setq end-pos (point)))))
2013 (goto-char pos))
2015 (if (and (not near) (> (point) start))
2018 ;; Try to be line oriented; position the limits at the
2019 ;; closest preceding boi, and after the next newline, that
2020 ;; isn't inside a comment, but if we hit a neighboring
2021 ;; declaration then we instead use the exact declaration
2022 ;; limit in that direction.
2023 (cons (progn
2024 (setq pos (point))
2025 (while (and (/= (point) (c-point 'boi))
2026 (c-backward-single-comment)))
2027 (if (/= (point) (c-point 'boi))
2029 (point)))
2030 (progn
2031 (if end-pos
2032 (goto-char end-pos)
2033 (c-end-of-decl-1))
2034 (setq pos (point))
2035 (while (and (not (bolp))
2036 (not (looking-at "\\s *$"))
2037 (c-forward-single-comment)))
2038 (cond ((bolp)
2039 (point))
2040 ((looking-at "\\s *$")
2041 (forward-line 1)
2042 (point))
2044 pos))))))
2045 (and (not near)
2046 (goto-char (point-min))
2047 (c-forward-decl-or-cast-1 -1 nil nil)
2048 (eq (char-after) ?\{)
2049 (cons (point-min) (point-max))))))))
2051 (defun c-mark-function ()
2052 "Put mark at end of the current top-level declaration or macro, point at beginning.
2053 If point is not inside any then the closest following one is
2054 chosen. Each successive call of this command extends the marked
2055 region by one function.
2057 A mark is left where the command started, unless the region is already active
2058 \(in Transient Mark mode).
2060 As opposed to \\[c-beginning-of-defun] and \\[c-end-of-defun], this
2061 function does not require the declaration to contain a brace block."
2062 (interactive)
2064 (let (decl-limits case-fold-search)
2065 (c-save-buffer-state nil
2066 ;; We try to be line oriented, unless there are several
2067 ;; declarations on the same line.
2068 (if (looking-at c-syntactic-eol)
2069 (c-backward-token-2 1 nil (c-point 'bol)))
2070 (setq decl-limits (c-declaration-limits t)))
2072 (if (not decl-limits)
2073 (error "Cannot find any declaration")
2074 (let* ((extend-region-p
2075 (and (eq this-command 'c-mark-function)
2076 (eq last-command 'c-mark-function)))
2077 (push-mark-p (and (eq this-command 'c-mark-function)
2078 (not extend-region-p)
2079 (not (c-region-is-active-p)))))
2080 (if push-mark-p (push-mark))
2081 (if extend-region-p
2082 (progn
2083 (exchange-point-and-mark)
2084 (setq decl-limits (c-declaration-limits t))
2085 (when (not decl-limits)
2086 (exchange-point-and-mark)
2087 (error "Cannot find any declaration"))
2088 (goto-char (cdr decl-limits))
2089 (exchange-point-and-mark))
2090 (goto-char (car decl-limits))
2091 (push-mark (cdr decl-limits) nil t))))))
2093 (defun c-cpp-define-name ()
2094 "Return the name of the current CPP macro, or NIL if we're not in one."
2095 (interactive)
2096 (let (case-fold-search)
2097 (save-excursion
2098 (and c-opt-cpp-macro-define-start
2099 (c-beginning-of-macro)
2100 (looking-at c-opt-cpp-macro-define-start)
2101 (match-string-no-properties 1)))))
2104 ;; Movement by statements.
2105 (defun c-in-comment-line-prefix-p ()
2106 ;; Point is within a comment. Is it also within a comment-prefix?
2107 ;; Space at BOL which precedes a comment-prefix counts as part of it.
2109 ;; This function might do hidden buffer changes.
2110 (let ((here (point)))
2111 (save-excursion
2112 (beginning-of-line)
2113 (skip-chars-forward " \t")
2114 (and (looking-at c-current-comment-prefix)
2115 (/= (match-beginning 0) (match-end 0))
2116 (< here (match-end 0))))))
2118 (defun c-narrow-to-comment-innards (range)
2119 ;; Narrow to the "inside" of the comment (block) defined by range, as
2120 ;; follows:
2122 ;; A c-style block comment has its opening "/*" and its closing "*/" (if
2123 ;; present) removed. A c++-style line comment retains its opening "//" but
2124 ;; has any final NL removed. If POINT is currently outwith these innards,
2125 ;; move it to the appropriate boundary.
2127 ;; This narrowing simplifies the sentence movement functions, since it
2128 ;; eliminates awkward things at the boundaries of the comment (block).
2130 ;; This function might do hidden buffer changes.
2131 (let* ((lit-type (c-literal-type range))
2132 (beg (if (eq lit-type 'c) (+ (car range) 2) (car range)))
2133 (end (if (eq lit-type 'c)
2134 (if (and (eq (char-before (cdr range)) ?/)
2135 (eq (char-before (1- (cdr range))) ?*))
2136 (- (cdr range) 2)
2137 (point-max))
2138 (if (eq (cdr range) (point-max))
2139 (point-max)
2140 (- (cdr range) 1)))))
2141 (if (> (point) end)
2142 (goto-char end)) ; This would be done automatically by ...
2143 (if (< (point) beg)
2144 (goto-char beg)) ; ... narrow-to-region but is not documented.
2145 (narrow-to-region beg end)))
2147 (defun c-beginning-of-sentence-in-comment (range)
2148 ;; Move backwards to the "beginning of a sentence" within the comment
2149 ;; defined by RANGE, a cons of its starting and ending positions. If we
2150 ;; find a BOS, return NIL. Otherwise, move point to just before the start
2151 ;; of the comment and return T.
2153 ;; The BOS is either text which follows a regexp match of sentence-end,
2154 ;; or text which is a beginning of "paragraph".
2155 ;; Comment-prefixes are treated like WS when calculating BOSes or BOPs.
2157 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2158 ;; It is not a general function, but is intended only for calling from
2159 ;; c-move-over-sentence. Not all preconditions have been explicitly stated.
2161 ;; This function might do hidden buffer changes.
2162 (save-match-data
2163 (let ((start-point (point)))
2164 (save-restriction
2165 (c-narrow-to-comment-innards range) ; This may move point back.
2166 (let* ((here (point))
2167 last
2168 (here-filler ; matches WS and comment-prefixes at point.
2169 (concat "\\=\\(^[ \t]*\\(" c-current-comment-prefix "\\)"
2170 "\\|[ \t\n\r\f]\\)*"))
2171 (prefix-at-bol-here ; matches WS and prefix at BOL, just before point
2172 (concat "^[ \t]*\\(" c-current-comment-prefix "\\)[ \t\n\r\f]*\\="))
2173 ;; First, find the previous paragraph start, if any.
2174 (par-beg ; point where non-WS/non-prefix text of paragraph starts.
2175 (save-excursion
2176 (forward-paragraph -1) ; uses cc-mode values of
2177 ; paragraph-\(start\|separate\)
2178 (if (> (re-search-forward here-filler nil t) here)
2179 (goto-char here))
2180 (when (>= (point) here)
2181 (forward-paragraph -2)
2182 (if (> (re-search-forward here-filler nil t) here)
2183 (goto-char here)))
2184 (point))))
2186 ;; Now seek successively earlier sentence ends between PAR-BEG and
2187 ;; HERE, until the "start of sentence" following it is earlier than
2188 ;; HERE, or we hit PAR-BEG. Beware of comment prefixes!
2189 (while (and (re-search-backward (c-sentence-end) par-beg 'limit)
2190 (setq last (point))
2191 (goto-char (match-end 0)) ; tentative beginning of sentence
2192 (or (>= (point) here)
2193 (and (not (bolp)) ; Found a non-blank comment-prefix?
2194 (save-excursion
2195 (if (re-search-backward prefix-at-bol-here nil t)
2196 (/= (match-beginning 1) (match-end 1)))))
2197 (progn ; Skip the crud to find a real b-o-s.
2198 (if (c-in-comment-line-prefix-p)
2199 (beginning-of-line))
2200 (re-search-forward here-filler) ; always succeeds.
2201 (>= (point) here))))
2202 (goto-char last))
2203 (re-search-forward here-filler)))
2205 (if (< (point) start-point)
2207 (goto-char (car range))
2208 t))))
2210 (defun c-end-of-sentence-in-comment (range)
2211 ;; Move forward to the "end of a sentence" within the comment defined by
2212 ;; RANGE, a cons of its starting and ending positions (enclosing the opening
2213 ;; comment delimiter and the terminating */ or newline). If we find an EOS,
2214 ;; return NIL. Otherwise, move point to just after the end of the comment
2215 ;; and return T.
2217 ;; The EOS is just after the non-WS part of the next match of the regexp
2218 ;; sentence-end. Typically, this is just after one of [.!?]. If there is
2219 ;; no sentence-end match following point, any WS before the end of the
2220 ;; comment will count as EOS, providing we're not already in it.
2222 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2223 ;; It is not a general function, but is intended only for calling from
2224 ;; c-move-over-sentence.
2226 ;; This function might do hidden buffer changes.
2227 (save-match-data
2228 (let ((start-point (point))
2229 ;; (lit-type (c-literal-type range)) ; Commented out, 2005/11/23, ACM
2231 (save-restriction
2232 (c-narrow-to-comment-innards range) ; This might move point forwards.
2233 (let* ((here (point))
2234 (par-end ; EOL position of last text in current/next paragraph.
2235 (save-excursion
2236 ;; The cc-mode values of paragraph-\(start\|separate\), set
2237 ;; in c-setup-paragraph-variables, are used in the
2238 ;; following.
2239 (forward-paragraph 1)
2240 (if (eq (preceding-char) ?\n) (forward-char -1))
2241 (when (<= (point) here) ; can happen, e.g., when HERE is at EOL.
2242 (goto-char here)
2243 (forward-paragraph 2)
2244 (if (eq (preceding-char) ?\n) (forward-char -1)))
2245 (point)))
2247 last
2248 (prefix-at-bol-here
2249 (concat "^[ \t]*\\(" c-current-comment-prefix "\\)\\=")))
2250 ;; Go forward one "comment-prefix which looks like sentence-end"
2251 ;; each time round the following:
2252 (while (and (re-search-forward (c-sentence-end) par-end 'limit)
2253 (progn
2254 (setq last (point))
2255 (skip-chars-backward " \t\n")
2256 (or (and (not (bolp))
2257 (re-search-backward prefix-at-bol-here nil t)
2258 (/= (match-beginning 1) (match-end 1)))
2259 (<= (point) here))))
2260 (goto-char last))
2262 ;; Take special action if we're up against the end of a comment (of
2263 ;; either sort): Leave point just after the last non-ws text.
2264 (if (eq (point) (point-max))
2265 (while (or (/= (skip-chars-backward " \t\n") 0)
2266 (and (re-search-backward prefix-at-bol-here nil t)
2267 (/= (match-beginning 1) (match-end 1))))))))
2269 (if (> (point) start-point)
2271 (goto-char (cdr range))
2272 t))))
2274 (defun c-beginning-of-sentence-in-string (range)
2275 ;; Move backwards to the "beginning of a sentence" within the string defined
2276 ;; by RANGE, a cons of its starting and ending positions (enclosing the
2277 ;; string quotes). If we find a BOS, return NIL. Otherwise, move point to
2278 ;; just before the start of the string and return T.
2280 ;; The BOS is either the text which follows a regexp match of sentence-end
2281 ;; or text which is a beginning of "paragraph". For the purposes of
2282 ;; determining paragraph boundaries, escaped newlines are treated as
2283 ;; ordinary newlines.
2285 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2286 ;; It is not a general function, but is intended only for calling from
2287 ;; c-move-over-sentence.
2289 ;; This function might do hidden buffer changes.
2290 (save-match-data
2291 (let* ((here (point)) last
2292 (end (1- (cdr range)))
2293 (here-filler ; matches WS and escaped newlines at point.
2294 "\\=\\([ \t\n\r\f]\\|\\\\[\n\r]\\)*")
2295 ;; Enhance paragraph-start and paragraph-separate also to recognize
2296 ;; blank lines terminated by escaped EOLs. IT MAY WELL BE that
2297 ;; these values should be customizable user options, or something.
2298 (paragraph-start c-string-par-start)
2299 (paragraph-separate c-string-par-separate)
2301 (par-beg ; beginning of current (or previous) paragraph.
2302 (save-excursion
2303 (save-restriction
2304 (narrow-to-region (1+ (car range)) end)
2305 (forward-paragraph -1) ; uses above values of
2306 ; paragraph-\(start\|separate\)
2307 (if (> (re-search-forward here-filler nil t) here)
2308 (goto-char here))
2309 (when (>= (point) here)
2310 (forward-paragraph -2)
2311 (if (> (re-search-forward here-filler nil t) here)
2312 (goto-char here)))
2313 (point)))))
2314 ;; Now see if we can find a sentence end after PAR-BEG.
2315 (while (and (re-search-backward c-sentence-end-with-esc-eol par-beg 'limit)
2316 (setq last (point))
2317 (goto-char (match-end 0))
2318 (or (> (point) end)
2319 (progn
2320 (re-search-forward
2321 here-filler end t) ; always succeeds. Use end rather
2322 ; than here, in case point starts
2323 ; beyond the closing quote.
2324 (>= (point) here))))
2325 (goto-char last))
2326 (re-search-forward here-filler here t)
2327 (if (< (point) here)
2329 (goto-char (car range))
2330 t))))
2332 (defun c-end-of-sentence-in-string (range)
2333 ;; Move forward to the "end of a sentence" within the string defined by
2334 ;; RANGE, a cons of its starting and ending positions. If we find an EOS,
2335 ;; return NIL. Otherwise, move point to just after the end of the string
2336 ;; and return T.
2338 ;; The EOS is just after the non-WS part of the next match of the regexp
2339 ;; sentence-end. Typically, this is just after one of [.!?]. If there is
2340 ;; no sentence-end match following point, any WS before the end of the
2341 ;; string will count as EOS, providing we're not already in it.
2343 ;; This code was adapted from GNU Emacs's forward-sentence in paragraphs.el.
2344 ;; It is not a general function, but is intended only for calling from
2345 ;; c-move-over-sentence.
2347 ;; This function might do hidden buffer changes.
2348 (save-match-data
2349 (let* ((here (point))
2350 last
2351 ;; Enhance paragraph-start and paragraph-separate to recognize
2352 ;; blank lines terminated by escaped EOLs.
2353 (paragraph-start c-string-par-start)
2354 (paragraph-separate c-string-par-separate)
2356 (par-end ; EOL position of last text in current/next paragraph.
2357 (save-excursion
2358 (save-restriction
2359 (narrow-to-region (car range) (1- (cdr range)))
2360 ;; The above values of paragraph-\(start\|separate\) are used
2361 ;; in the following.
2362 (forward-paragraph 1)
2363 (setq last (point))
2364 ;; (re-search-backward filler-here nil t) would find an empty
2365 ;; string. Therefore we simulate it by the following:
2366 (while (or (/= (skip-chars-backward " \t\n\r\f") 0)
2367 (re-search-backward "\\\\\\($\\)\\=" nil t)))
2368 (unless (> (point) here)
2369 (goto-char last)
2370 (forward-paragraph 1)
2371 (while (or (/= (skip-chars-backward " \t\n\r\f") 0)
2372 (re-search-backward "\\\\\\($\\)\\=" nil t))))
2373 (point)))))
2374 ;; Try to go forward a sentence.
2375 (when (re-search-forward c-sentence-end-with-esc-eol par-end 'limit)
2376 (setq last (point))
2377 (while (or (/= (skip-chars-backward " \t\n") 0)
2378 (re-search-backward "\\\\\\($\\)\\=" nil t))))
2379 ;; Did we move a sentence, or did we hit the end of the string?
2380 (if (> (point) here)
2382 (goto-char (cdr range))
2383 t))))
2385 (defun c-ascertain-preceding-literal ()
2386 ;; Point is not in a literal (i.e. comment or string (include AWK regexp)).
2387 ;; If a literal is the next thing (aside from whitespace) to be found before
2388 ;; point, return a cons of its start.end positions (enclosing the
2389 ;; delimiters). Otherwise return NIL.
2391 ;; This function might do hidden buffer changes.
2392 (save-excursion
2393 (c-collect-line-comments
2394 (let ((here (point))
2395 pos)
2396 (if (c-backward-single-comment)
2397 (cons (point) (progn (c-forward-single-comment) (point)))
2398 (save-restriction
2399 ;; to prevent `looking-at' seeing a " at point.
2400 (narrow-to-region (point-min) here)
2401 (when
2403 ;; An EOL can act as an "open string" terminator in AWK.
2404 (looking-at c-ws*-string-limit-regexp)
2405 (and (not (bobp))
2406 (progn (backward-char)
2407 (looking-at c-string-limit-regexp))))
2408 (goto-char (match-end 0)) ; just after the string terminator.
2409 (setq pos (point))
2410 (c-safe (c-backward-sexp 1) ; move back over the string.
2411 (cons (point) pos)))))))))
2413 (defun c-ascertain-following-literal ()
2414 ;; Point is not in a literal (i.e. comment or string (include AWK regexp)).
2415 ;; If a literal is the next thing (aside from whitespace) following point,
2416 ;; return a cons of its start.end positions (enclosing the delimiters).
2417 ;; Otherwise return NIL.
2419 ;; This function might do hidden buffer changes.
2420 (save-excursion
2421 (c-collect-line-comments
2422 (let (pos)
2423 (c-skip-ws-forward)
2424 (if (looking-at c-string-limit-regexp) ; string-delimiter.
2425 (cons (point) (or (c-safe (progn (c-forward-sexp 1) (point)))
2426 (point-max)))
2427 (setq pos (point))
2428 (if (c-forward-single-comment)
2429 (cons pos (point))))))))
2431 (defun c-after-statement-terminator-p () ; Should we pass in LIM here?
2432 ;; Does point immediately follow a statement "terminator"? A virtual
2433 ;; semicolon is regarded here as such. So is an opening brace ;-)
2435 ;; This function might do hidden buffer changes.
2436 (or (save-excursion
2437 (backward-char)
2438 (and (looking-at "[;{}]")
2439 (not (and c-special-brace-lists ; Pike special brace lists.
2440 (eq (char-after) ?{)
2441 (c-looking-at-special-brace-list)))))
2442 (c-at-vsemi-p)
2443 ;; The following (for macros) is not strict about exactly where we are
2444 ;; wrt white space at the end of the macro. Doesn't seem to matter too
2445 ;; much. ACM 2004/3/29.
2446 (let (eom)
2447 (save-excursion
2448 (if (c-beginning-of-macro)
2449 (setq eom (progn (c-end-of-macro)
2450 (point)))))
2451 (when eom
2452 (save-excursion
2453 (c-forward-comments)
2454 (>= (point) eom))))))
2456 (defun c-back-over-illiterals (macro-start)
2457 ;; Move backwards over code which isn't a literal (i.e. comment or string),
2458 ;; stopping before reaching BOB or a literal or the boundary of a
2459 ;; preprocessor statement or the "beginning of a statement". MACRO-START is
2460 ;; the position of the '#' beginning the current preprocessor directive, or
2461 ;; NIL if we're not in such.
2463 ;; Return a cons (A.B), where
2464 ;; A is NIL if we moved back to a BOS (and know it), T otherwise (we
2465 ;; didn't move, or we hit a literal, or we're not sure about BOS).
2466 ;; B is MACRO-BOUNDARY if we are about to cross the boundary out of or
2467 ;; into a macro, otherwise LITERAL if we've hit a literal, otherwise NIL
2469 ;; The total collection of returned values is as follows:
2470 ;; (nil . nil): Found a BOS whilst remaining inside the illiterals.
2471 ;; (t . literal): No BOS found: only a comment/string. We _might_ be at
2472 ;; a BOS - the caller must check this.
2473 ;; (nil . macro-boundary): only happens with non-nil macro-start. We've
2474 ;; moved and reached the opening # of the macro.
2475 ;; (t . macro-boundary): Every other circumstance in which we're at a
2476 ;; macro-boundary. We might be at a BOS.
2478 ;; Point is left either at the beginning-of-statement, or at the last non-ws
2479 ;; code before encountering the literal/BOB or macro-boundary.
2481 ;; Note that this function moves within either preprocessor commands
2482 ;; (macros) or normal code, but will not cross a boundary between the two,
2483 ;; or between two distinct preprocessor commands.
2485 ;; Stop before `{' and after `;', `{', `}' and `};' when not followed by `}'
2486 ;; or `)', but on the other side of the syntactic ws. Move by sexps and
2487 ;; move into parens. Also stop before `#' when it's at boi on a line.
2489 ;; This function might do hidden buffer changes.
2490 (save-match-data
2491 (let ((here (point))
2492 last) ; marks the position of non-ws code, what'll be BOS if, say, a
2493 ; semicolon precedes it.
2494 (catch 'done
2495 (while t ;; We go back one "token" each iteration of the loop.
2496 (setq last (point))
2497 (cond
2498 ;; Stop at the token after a comment.
2499 ((c-backward-single-comment) ; Also functions as backwards-ws.
2500 (goto-char last)
2501 (throw 'done '(t . literal)))
2503 ;; If we've gone back over a LF, we might have moved into or out of
2504 ;; a preprocessor line.
2505 ((and (save-excursion
2506 (beginning-of-line)
2507 (re-search-forward "\\(^\\|[^\\]\\)[\n\r]" last t))
2508 (if macro-start
2509 (< (point) macro-start)
2510 (c-beginning-of-macro)))
2511 (goto-char last)
2512 ;; Return a car of NIL ONLY if we've hit the opening # of a macro.
2513 (throw 'done (cons (or (eq (point) here)
2514 (not macro-start))
2515 'macro-boundary)))
2517 ;; Have we found a virtual semicolon? If so, stop, unless the next
2518 ;; statement is where we started from.
2519 ((and (c-at-vsemi-p)
2520 (< last here)
2521 (not (memq (char-after last) '(?\) ?})))) ; we've moved back from ) or }
2522 (goto-char last)
2523 (throw 'done '(nil . nil)))
2525 ;; Hit the beginning of the buffer/region?
2526 ((bobp)
2527 (if (/= here last)
2528 (goto-char last))
2529 (throw 'done '(nil . nil)))
2531 ;; Move back a character.
2532 ((progn (backward-char) nil))
2534 ;; Stop at "{" (unless it's a PIKE special brace list.)
2535 ((eq (char-after) ?\{)
2536 (if (and c-special-brace-lists
2537 (c-looking-at-special-brace-list))
2538 (skip-syntax-backward "w_") ; Speedup only.
2539 (if (/= here last)
2540 (goto-char last))
2541 (throw 'done '(nil . nil))))
2543 ;; Have we reached the start of a macro? This always counts as
2544 ;; BOS. (N.B. I don't think (eq (point) here) can ever be true
2545 ;; here. FIXME!!! ACM 2004/3/29)
2546 ((and macro-start (eq (point) macro-start))
2547 (throw 'done (cons (eq (point) here) 'macro-boundary)))
2549 ;; Stop at token just after "}" or ";".
2550 ((looking-at "[;}]")
2551 ;; If we've gone back over ;, {, or }, we're done.
2552 (if (or (= here last)
2553 (memq (char-after last) '(?\) ?}))) ; we've moved back from ) or }
2554 (if (and (eq (char-before) ?}) ; If };, treat them as a unit.
2555 (eq (char-after) ?\;))
2556 (backward-char))
2557 (goto-char last) ; To the statement starting after the ; or }.
2558 (throw 'done '(nil . nil))))
2560 ;; Stop at the token after a string.
2561 ((looking-at c-string-limit-regexp) ; Just gone back over a string terminator?
2562 (goto-char last)
2563 (throw 'done '(t . literal)))
2565 ;; Nothing special: go back word characters.
2566 (t (skip-syntax-backward "w_")) ; Speedup only.
2567 ))))))
2569 (defun c-forward-over-illiterals (macro-end allow-early-stop)
2570 ;; Move forwards over code, stopping before reaching EOB or a literal
2571 ;; (i.e. a comment/string) or the boundary of a preprocessor statement or
2572 ;; the "end of a statement". MACRO-END is the position of the EOL/EOB which
2573 ;; terminates the current preprocessor directive, or NIL if we're not in
2574 ;; such.
2576 ;; ALLOW-EARLY-STOP is non-nil if it is permissible to return without moving
2577 ;; forward at all, should we encounter a `{'. This is an ugly kludge, but
2578 ;; seems unavoidable. Depending on the context this function is called
2579 ;; from, we _sometimes_ need to stop there. Currently (2004/4/3),
2580 ;; ALLOW-EARLY-STOP is applied only to open braces, not to virtual
2581 ;; semicolons, or anything else.
2583 ;; Return a cons (A.B), where
2584 ;; A is NIL if we moved forward to an EOS, or stay at one (when
2585 ;; ALLOW-EARLY-STOP is set), T otherwise (we hit a literal).
2586 ;; B is 'MACRO-BOUNDARY if we are about to cross the boundary out of or
2587 ;; into a macro, otherwise 'LITERAL if we've hit a literal, otherwise NIL
2589 ;; Point is left either after the end-of-statement, or at the last non-ws
2590 ;; code before encountering the literal, or the # of the preprocessor
2591 ;; statement, or at EOB [or just after last non-WS stuff??].
2593 ;; As a clarification of "after the end-of-statement", if a comment or
2594 ;; whitespace follows a completed AWK statement, that statement is treated
2595 ;; as ending just after the last non-ws character before the comment.
2597 ;; Note that this function moves within either preprocessor commands
2598 ;; (macros) or normal code, but not both within the same invocation.
2600 ;; Stop before `{', `}', and `#' when it's at boi on a line, but on the
2601 ;; other side of the syntactic ws, and after `;', `}' and `};'. Only
2602 ;; stop before `{' if at top level or inside braces, though. Move by
2603 ;; sexps and move into parens. Also stop at eol of lines with `#' at
2604 ;; the boi.
2606 ;; This function might do hidden buffer changes.
2607 (let ((here (point))
2608 last)
2609 (catch 'done
2610 (while t ;; We go one "token" forward each time round this loop.
2611 (setq last (point))
2613 ;; If we've moved forward to a virtual semicolon, we're done.
2614 (if (and (> last here) ; Should we check ALLOW-EARLY-STOP, here? 2004/4/3
2615 (c-at-vsemi-p))
2616 (throw 'done '(nil . nil)))
2618 (c-skip-ws-forward)
2619 (cond
2620 ;; Gone past the end of a macro?
2621 ((and macro-end (> (point) macro-end))
2622 (goto-char last)
2623 (throw 'done (cons (eq (point) here) 'macro-boundary)))
2625 ;; About to hit a comment?
2626 ((save-excursion (c-forward-single-comment))
2627 (goto-char last)
2628 (throw 'done '(t . literal)))
2630 ;; End of buffer?
2631 ((eobp)
2632 (if (/= here last)
2633 (goto-char last))
2634 (throw 'done '(nil . nil)))
2636 ;; If we encounter a '{', stop just after the previous token.
2637 ((and (eq (char-after) ?{)
2638 (not (and c-special-brace-lists
2639 (c-looking-at-special-brace-list)))
2640 (or allow-early-stop (/= here last))
2641 (save-excursion ; Is this a check that we're NOT at top level?
2642 ;;;; NO! This seems to check that (i) EITHER we're at the top level; OR (ii) The next enclosing
2643 ;;;; level of bracketing is a '{'. HMM. Doesn't seem to make sense.
2644 ;;;; 2003/8/8 This might have something to do with the GCC extension "Statement Expressions", e.g.
2645 ;;;; while ({stmt1 ; stmt2 ; exp ;}). This form excludes such Statement Expressions.
2646 (or (not (c-safe (up-list -1) t))
2647 (= (char-after) ?{))))
2648 (goto-char last)
2649 (throw 'done '(nil . nil)))
2651 ;; End of a PIKE special brace list? If so, step over it and continue.
2652 ((and c-special-brace-lists
2653 (eq (char-after) ?})
2654 (save-excursion
2655 (and (c-safe (up-list -1) t)
2656 (c-looking-at-special-brace-list))))
2657 (forward-char)
2658 (skip-syntax-forward "w_")) ; Speedup only.
2660 ;; Have we got a '}' after having moved? If so, stop after the
2661 ;; previous token.
2662 ((and (eq (char-after) ?})
2663 (/= here last))
2664 (goto-char last)
2665 (throw 'done '(nil . nil)))
2667 ;; Stop if we encounter a preprocessor line. Continue if we
2668 ;; hit a naked #
2669 ((and c-opt-cpp-prefix
2670 (not macro-end)
2671 (eq (char-after) ?#)
2672 (= (point) (c-point 'boi)))
2673 (if (= (point) here) ; Not a macro, therefore naked #.
2674 (forward-char)
2675 (throw 'done '(t . macro-boundary))))
2677 ;; Stop after a ';', '}', or "};"
2678 ((looking-at ";\\|};?")
2679 (goto-char (match-end 0))
2680 (throw 'done '(nil . nil)))
2682 ;; Found a string (this subsumes AWK regexps)?
2683 ((looking-at c-string-limit-regexp)
2684 (goto-char last)
2685 (throw 'done '(t . literal)))
2688 (forward-char) ; Can't fail - we checked (eobp) earlier on.
2689 (skip-syntax-forward "w_") ; Speedup only.
2690 (when (and macro-end (> (point) macro-end))
2691 (goto-char last)
2692 (throw 'done (cons (eq (point) here) 'macro-boundary))))
2693 )))))
2695 (defun c-one-line-string-p (range)
2696 ;; Is the literal defined by RANGE a string contained in a single line?
2698 ;; This function might do hidden buffer changes.
2699 (save-excursion
2700 (goto-char (car range))
2701 (and (looking-at c-string-limit-regexp)
2702 (progn (skip-chars-forward "^\n" (cdr range))
2703 (eq (point) (cdr range))))))
2705 (defun c-beginning-of-statement (&optional count lim sentence-flag)
2706 "Go to the beginning of the innermost C statement.
2707 With prefix arg, go back N - 1 statements. If already at the
2708 beginning of a statement then go to the beginning of the closest
2709 preceding one, moving into nested blocks if necessary (use
2710 \\[backward-sexp] to skip over a block). If within or next to a
2711 comment or multiline string, move by sentences instead of statements.
2713 When called from a program, this function takes 3 optional args: the
2714 repetition count, a buffer position limit which is the farthest back
2715 to search for the syntactic context, and a flag saying whether to do
2716 sentence motion in or near comments and multiline strings.
2718 Note that for use in programs, `c-beginning-of-statement-1' is
2719 usually better. It has much better defined semantics than this one,
2720 which is intended for interactive use, and might therefore change to
2721 be more \"DWIM:ey\"."
2722 (interactive (list (prefix-numeric-value current-prefix-arg)
2723 nil t))
2724 (if (< count 0)
2725 (c-end-of-statement (- count) lim sentence-flag)
2726 (c-save-buffer-state
2727 ((count (or count 1))
2728 last ; start point for going back ONE chunk. Updated each chunk movement.
2729 (macro-fence
2730 (save-excursion (and (not (bobp)) (c-beginning-of-macro) (point))))
2731 res ; result from sub-function call
2732 not-bos ; "not beginning-of-statement"
2733 (range (c-collect-line-comments (c-literal-limits lim)))) ; (start.end) of current literal or NIL
2735 ;; Go back one statement at each iteration of the following loop.
2736 (while (and (/= count 0)
2737 (or (not lim) (> (point) lim)))
2738 ;; Go back one "chunk" each time round the following loop, stopping
2739 ;; when we reach a statement boundary, etc.
2740 (setq last (point))
2741 (while
2742 (cond ; Each arm of this cond returns NIL on reaching a desired
2743 ; statement boundary, non-NIL otherwise.
2744 ((bobp)
2745 (setq count 0)
2746 nil)
2748 (range ; point is within or approaching a literal.
2749 (cond
2750 ;; Single line string or sentence-flag is null => skip the
2751 ;; entire literal.
2752 ((or (null sentence-flag)
2753 (c-one-line-string-p range))
2754 (goto-char (car range))
2755 (setq range (c-ascertain-preceding-literal))
2756 ;; N.B. The following is essentially testing for an AWK regexp
2757 ;; at BOS:
2758 ;; Was the previous non-ws thing an end of statement?
2759 (save-excursion
2760 (if macro-fence
2761 (c-backward-comments)
2762 (c-backward-syntactic-ws))
2763 (not (or (bobp) (c-after-statement-terminator-p)))))
2765 ;; Comment inside a statement or a multi-line string.
2766 (t (when (setq res ; returns non-nil when we go out of the literal
2767 (if (eq (c-literal-type range) 'string)
2768 (c-beginning-of-sentence-in-string range)
2769 (c-beginning-of-sentence-in-comment range)))
2770 (setq range (c-ascertain-preceding-literal)))
2771 res)))
2773 ;; Non-literal code.
2774 (t (setq res (c-back-over-illiterals macro-fence))
2775 (setq not-bos ; "not reached beginning-of-statement".
2776 (or (= (point) last)
2777 (memq (char-after) '(?\) ?\}))
2778 (and
2779 (car res)
2780 ;; We're at a tentative BOS. The next form goes
2781 ;; back over WS looking for an end of previous
2782 ;; statement.
2783 (not (save-excursion
2784 (if macro-fence
2785 (c-backward-comments)
2786 (c-backward-syntactic-ws))
2787 (or (bobp) (c-after-statement-terminator-p)))))))
2788 ;; Are we about to move backwards into or out of a
2789 ;; preprocessor command? If so, locate its beginning.
2790 (when (eq (cdr res) 'macro-boundary)
2791 (save-excursion
2792 (beginning-of-line)
2793 (setq macro-fence
2794 (and (not (bobp))
2795 (progn (c-skip-ws-backward) (c-beginning-of-macro))
2796 (point)))))
2797 ;; Are we about to move backwards into a literal?
2798 (when (memq (cdr res) '(macro-boundary literal))
2799 (setq range (c-ascertain-preceding-literal)))
2800 not-bos))
2801 (setq last (point)))
2803 (if (/= count 0) (setq count (1- count))))
2804 (c-keep-region-active))))
2806 (defun c-end-of-statement (&optional count lim sentence-flag)
2807 "Go to the end of the innermost C statement.
2808 With prefix arg, go forward N - 1 statements. Move forward to the end
2809 of the next statement if already at end, and move into nested blocks
2810 \(use \\[forward-sexp] to skip over a block). If within or next to a
2811 comment or multiline string, move by sentences instead of statements.
2813 When called from a program, this function takes 3 optional args: the
2814 repetition count, a buffer position limit which is the farthest back
2815 to search for the syntactic context, and a flag saying whether to do
2816 sentence motion in or near comments and multiline strings."
2817 (interactive (list (prefix-numeric-value current-prefix-arg)
2818 nil t))
2819 (setq count (or count 1))
2820 (if (< count 0) (c-beginning-of-statement (- count) lim sentence-flag)
2822 (c-save-buffer-state
2823 (here ; start point for going forward ONE statement. Updated each statement.
2824 (macro-fence
2825 (save-excursion
2826 (and (not (eobp)) (c-beginning-of-macro)
2827 (progn (c-end-of-macro) (point)))))
2829 (range (c-collect-line-comments (c-literal-limits lim)))) ; (start.end) of current literal or NIL
2831 ;; Go back/forward one statement at each iteration of the following loop.
2832 (while (and (/= count 0)
2833 (or (not lim) (< (point) lim)))
2834 (setq here (point)) ; ONLY HERE is HERE updated
2836 ;; Go forward one "chunk" each time round the following loop, stopping
2837 ;; when we reach a statement boundary, etc.
2838 (while
2839 (cond ; Each arm of this cond returns NIL on reaching a desired
2840 ; statement boundary, non-NIL otherwise.
2841 ((eobp)
2842 (setq count 0)
2843 nil)
2845 (range ; point is within a literal.
2846 (cond
2847 ;; sentence-flag is null => skip the entire literal.
2848 ;; or a Single line string.
2849 ((or (null sentence-flag)
2850 (c-one-line-string-p range))
2851 (goto-char (cdr range))
2852 (setq range (c-ascertain-following-literal))
2853 ;; Is there a virtual semicolon here (e.g. for AWK)?
2854 (not (c-at-vsemi-p)))
2856 ;; Comment or multi-line string.
2857 (t (when (setq res ; gets non-nil when we go out of the literal
2858 (if (eq (c-literal-type range) 'string)
2859 (c-end-of-sentence-in-string range)
2860 (c-end-of-sentence-in-comment range)))
2861 (setq range (c-ascertain-following-literal)))
2862 ;; If we've just come forward out of a literal, check for
2863 ;; vsemi. (N.B. AWK can't have a vsemi after a comment, but
2864 ;; some other language may do in the future)
2865 (and res
2866 (not (c-at-vsemi-p))))))
2868 ;; Non-literal code.
2869 (t (setq res (c-forward-over-illiterals macro-fence
2870 (> (point) here)))
2871 ;; Are we about to move forward into or out of a
2872 ;; preprocessor command?
2873 (when (eq (cdr res) 'macro-boundary)
2874 (setq macro-fence
2875 (save-excursion
2876 (if macro-fence
2877 (progn
2878 (end-of-line)
2879 (and (not (eobp))
2880 (progn (c-skip-ws-forward)
2881 (c-beginning-of-macro))
2882 (progn (c-end-of-macro)
2883 (point))))
2884 (and (not (eobp))
2885 (c-beginning-of-macro)
2886 (progn (c-end-of-macro) (point)))))))
2887 ;; Are we about to move forward into a literal?
2888 (when (memq (cdr res) '(macro-boundary literal))
2889 (setq range (c-ascertain-following-literal)))
2890 (car res))))
2892 (if (/= count 0) (setq count (1- count))))
2893 (c-keep-region-active))))
2896 ;; set up electric character functions to work with pending-del,
2897 ;; (a.k.a. delsel) mode. All symbols get the t value except
2898 ;; the functions which delete, which gets 'supersede, and (from Emacs
2899 ;; 25) `c-electric-brace' and `c-electric-paren' get special handling
2900 ;; so as to work gracefully with `electric-pair-mode'.
2901 (mapc
2902 (function
2903 (lambda (sym)
2904 (put sym 'delete-selection t) ; for delsel (Emacs)
2905 (put sym 'pending-delete t))) ; for pending-del (XEmacs)
2906 '(c-electric-pound
2907 c-electric-slash
2908 c-electric-star
2909 c-electric-semi&comma
2910 c-electric-lt-gt
2911 c-electric-colon))
2912 (mapc
2913 (function
2914 (lambda (sym)
2915 (put sym 'delete-selection (if (fboundp 'delete-selection-uses-region-p)
2916 'delete-selection-uses-region-p
2918 (put sym 'pending-delete t)))
2919 '(c-electric-brace
2920 c-electric-paren))
2921 (put 'c-electric-delete 'delete-selection 'supersede) ; delsel
2922 (put 'c-electric-delete 'pending-delete 'supersede) ; pending-del
2923 (put 'c-electric-backspace 'delete-selection 'supersede) ; delsel
2924 (put 'c-electric-backspace 'pending-delete 'supersede) ; pending-del
2925 (put 'c-electric-delete-forward 'delete-selection 'supersede) ; delsel
2926 (put 'c-electric-delete-forward 'pending-delete 'supersede) ; pending-del
2929 ;; Inserting/indenting comments
2930 (defun c-calc-comment-indent (entry)
2931 ;; This function might do hidden buffer changes.
2932 (if (symbolp entry)
2933 (setq entry (or (assq entry c-indent-comment-alist)
2934 (assq 'other c-indent-comment-alist)
2935 '(default . (column . nil)))))
2936 (let ((action (car (cdr entry)))
2937 (value (cdr (cdr entry)))
2938 (col (current-column)))
2939 (cond ((eq action 'space)
2940 (+ col value))
2941 ((eq action 'column)
2942 (unless value (setq value comment-column))
2943 (if (bolp)
2944 ;; Do not pad with one space if we're at bol.
2945 value
2946 (max (1+ col) value)))
2947 ((eq action 'align)
2948 (or (save-excursion
2949 (beginning-of-line)
2950 (unless (bobp)
2951 (backward-char)
2952 (let ((lim (c-literal-limits (c-point 'bol) t)))
2953 (when (consp lim)
2954 (goto-char (car lim))
2955 (when (looking-at "/[/*]") ; FIXME!!! Adapt for AWK! (ACM, 2005/11/18)
2956 ;; Found comment to align with.
2957 (if (bolp)
2958 ;; Do not pad with one space if we're at bol.
2960 (max (1+ col) (current-column))))))))
2961 ;; Recurse to handle value as a new spec.
2962 (c-calc-comment-indent (cdr entry)))))))
2964 (defun c-comment-indent ()
2965 "Used by `indent-for-comment' to create and indent comments.
2966 See `c-indent-comment-alist' for a description."
2967 (save-excursion
2968 (end-of-line)
2969 (c-save-buffer-state
2970 ((eot (let ((lim (c-literal-limits (c-point 'bol) t)))
2971 (or (when (consp lim)
2972 (goto-char (car lim))
2973 (when (looking-at "/[/*]")
2974 (skip-chars-backward " \t")
2975 (point)))
2976 (progn
2977 (skip-chars-backward " \t")
2978 (point)))))
2979 (line-type
2980 (cond ((looking-at "^/[/*]")
2981 'anchored-comment)
2982 ((progn (beginning-of-line)
2983 (eq (point) eot))
2984 'empty-line)
2985 ((progn (back-to-indentation)
2986 (and (eq (char-after) ?})
2987 (eq (point) (1- eot))))
2988 'end-block)
2989 ((and (looking-at "#[ \t]*\\(endif\\|else\\)")
2990 (eq (match-end 0) eot))
2991 'cpp-end-block)
2993 'other)))
2994 case-fold-search)
2995 (if (and (memq line-type '(anchored-comment empty-line))
2996 c-indent-comments-syntactically-p)
2997 (let ((c-syntactic-context (c-guess-basic-syntax)))
2998 ;; BOGOSITY ALERT: if we're looking at the eol, its
2999 ;; because indent-for-comment hasn't put the comment-start
3000 ;; in the buffer yet. this will screw up the syntactic
3001 ;; analysis so we kludge in the necessary info. Another
3002 ;; kludge is that if we're at the bol, then we really want
3003 ;; to ignore any anchoring as specified by
3004 ;; c-comment-only-line-offset since it doesn't apply here.
3005 (if (eolp)
3006 (c-add-syntax 'comment-intro))
3007 (let ((c-comment-only-line-offset
3008 (if (consp c-comment-only-line-offset)
3009 c-comment-only-line-offset
3010 (cons c-comment-only-line-offset
3011 c-comment-only-line-offset))))
3012 (c-get-syntactic-indentation c-syntactic-context)))
3013 (goto-char eot)
3014 (c-calc-comment-indent line-type)))))
3017 ;; used by outline-minor-mode
3018 (defun c-outline-level ()
3019 (let (buffer-invisibility-spec);; This so that `current-column' DTRT
3020 ;; in otherwise-hidden text.
3021 (save-excursion
3022 (skip-chars-forward "\t ")
3023 (current-column))))
3026 ;; Movement by CPP conditionals.
3027 (defun c-up-conditional (count)
3028 "Move back to the containing preprocessor conditional, leaving mark behind.
3029 A prefix argument acts as a repeat count. With a negative argument,
3030 move forward to the end of the containing preprocessor conditional.
3032 \"#elif\" is treated like \"#else\" followed by \"#if\", so the
3033 function stops at them when going backward, but not when going
3034 forward."
3035 (interactive "p")
3036 (let ((new-point (c-scan-conditionals (- count) -1)))
3037 (push-mark)
3038 (goto-char new-point))
3039 (c-keep-region-active))
3041 (defun c-up-conditional-with-else (count)
3042 "Move back to the containing preprocessor conditional, including \"#else\".
3043 Just like `c-up-conditional', except it also stops at \"#else\"
3044 directives."
3045 (interactive "p")
3046 (let ((new-point (c-scan-conditionals (- count) -1 t)))
3047 (push-mark)
3048 (goto-char new-point))
3049 (c-keep-region-active))
3051 (defun c-down-conditional (count)
3052 "Move forward into the next preprocessor conditional, leaving mark behind.
3053 A prefix argument acts as a repeat count. With a negative argument,
3054 move backward into the previous preprocessor conditional.
3056 \"#elif\" is treated like \"#else\" followed by \"#if\", so the
3057 function stops at them when going forward, but not when going
3058 backward."
3059 (interactive "p")
3060 (let ((new-point (c-scan-conditionals count 1)))
3061 (push-mark)
3062 (goto-char new-point))
3063 (c-keep-region-active))
3065 (defun c-down-conditional-with-else (count)
3066 "Move forward into the next preprocessor conditional, including \"#else\".
3067 Just like `c-down-conditional', except it also stops at \"#else\"
3068 directives."
3069 (interactive "p")
3070 (let ((new-point (c-scan-conditionals count 1 t)))
3071 (push-mark)
3072 (goto-char new-point))
3073 (c-keep-region-active))
3075 (defun c-backward-conditional (count &optional target-depth with-else)
3076 "Move back across a preprocessor conditional, leaving mark behind.
3077 A prefix argument acts as a repeat count. With a negative argument,
3078 move forward across a preprocessor conditional.
3080 The optional arguments TARGET-DEPTH and WITH-ELSE are historical,
3081 and have the same meanings as in `c-scan-conditionals'. If you
3082 are calling c-forward-conditional from a program, you might want
3083 to call `c-scan-conditionals' directly instead."
3084 (interactive "p")
3085 (let ((new-point (c-scan-conditionals (- count) target-depth with-else)))
3086 (push-mark)
3087 (goto-char new-point))
3088 (c-keep-region-active))
3090 (defun c-forward-conditional (count &optional target-depth with-else)
3091 "Move forward across a preprocessor conditional, leaving mark behind.
3092 A prefix argument acts as a repeat count. With a negative argument,
3093 move backward across a preprocessor conditional.
3095 If there aren't enough conditionals after \(or before) point, an
3096 error is signaled.
3098 \"#elif\" is treated like \"#else\" followed by \"#if\", except that
3099 the nesting level isn't changed when tracking subconditionals.
3101 The optional arguments TARGET-DEPTH and WITH-ELSE are historical,
3102 and have the same meanings as in `c-scan-conditionals'. If you
3103 are calling c-forward-conditional from a program, you might want
3104 to call `c-scan-conditionals' directly instead."
3105 (interactive "p")
3106 (let ((new-point (c-scan-conditionals count target-depth with-else)))
3107 (push-mark)
3108 (goto-char new-point)))
3110 (defun c-scan-conditionals (count &optional target-depth with-else)
3111 "Scan forward across COUNT preprocessor conditionals.
3112 With a negative argument, scan backward across preprocessor
3113 conditionals. Return the end position. Point is not moved.
3115 If there aren't enough preprocessor conditionals, throw an error.
3117 \"#elif\" is treated like \"#else\" followed by \"#if\", except that
3118 the nesting level isn't changed when tracking subconditionals.
3120 The optional argument TARGET-DEPTH specifies the wanted nesting depth
3121 after each scan. E.g. if TARGET-DEPTH is -1, the end position will be
3122 outside the enclosing conditional. A non-integer non-nil TARGET-DEPTH
3123 counts as -1.
3125 If the optional argument WITH-ELSE is non-nil, \"#else\" directives
3126 are treated as conditional clause limits. Normally they are ignored."
3127 (let* ((forward (> count 0))
3128 (increment (if forward -1 1))
3129 (search-function (if forward 're-search-forward 're-search-backward))
3130 new case-fold-search)
3131 (unless (integerp target-depth)
3132 (setq target-depth (if target-depth -1 0)))
3133 (save-excursion
3134 (while (/= count 0)
3135 (let ((depth 0)
3136 ;; subdepth is the depth in "uninteresting" subtrees,
3137 ;; i.e. those that takes us farther from the target
3138 ;; depth instead of closer.
3139 (subdepth 0)
3140 found)
3141 (save-excursion
3142 ;; Find the "next" significant line in the proper direction.
3143 (while (and (not found)
3144 ;; Rather than searching for a # sign that
3145 ;; comes at the beginning of a line aside from
3146 ;; whitespace, search first for a string
3147 ;; starting with # sign. Then verify what
3148 ;; precedes it. This is faster on account of
3149 ;; the fastmap feature of the regexp matcher.
3150 (funcall search-function
3151 "#[ \t]*\\(if\\|elif\\|endif\\|else\\)"
3152 nil t))
3153 (beginning-of-line)
3154 ;; Now verify it is really a preproc line.
3155 (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\|else\\)")
3156 (let (dchange (directive (match-string 1)))
3157 (cond ((string= directive "if")
3158 (setq dchange (- increment)))
3159 ((string= directive "endif")
3160 (setq dchange increment))
3161 ((= subdepth 0)
3162 ;; When we're not in an "uninteresting"
3163 ;; subtree, we might want to act on "elif"
3164 ;; and "else" too.
3165 (if (cond (with-else
3166 ;; Always move toward the target depth.
3167 (setq dchange
3168 (if (> target-depth 0) 1 -1)))
3169 ((string= directive "elif")
3170 (setq dchange (- increment))))
3171 ;; Ignore the change if it'd take us
3172 ;; into an "uninteresting" subtree.
3173 (if (eq (> dchange 0) (<= target-depth 0))
3174 (setq dchange nil)))))
3175 (when dchange
3176 (when (or (/= subdepth 0)
3177 (eq (> dchange 0) (<= target-depth 0)))
3178 (setq subdepth (+ subdepth dchange)))
3179 (setq depth (+ depth dchange))
3180 ;; If we are trying to move across, and we find an
3181 ;; end before we find a beginning, get an error.
3182 (if (and (< depth target-depth) (< dchange 0))
3183 (error (if forward
3184 "No following conditional at this level"
3185 "No previous conditional at this level"))))
3186 ;; When searching forward, start from next line so
3187 ;; that we don't find the same line again.
3188 (if forward (forward-line 1))
3189 ;; We found something if we've arrived at the
3190 ;; target depth.
3191 (if (and dchange (= depth target-depth))
3192 (setq found (point))))
3193 ;; else
3194 (if forward (forward-line 1)))))
3195 (or found
3196 (error "No containing preprocessor conditional"))
3197 (goto-char (setq new found)))
3198 (setq count (+ count increment))))
3199 (c-keep-region-active)
3200 new))
3203 ;; commands to indent lines, regions, defuns, and expressions
3204 (defun c-indent-command (&optional arg)
3205 "Indent current line as C code, and/or insert some whitespace.
3207 If `c-tab-always-indent' is t, always just indent the current line.
3208 If nil, indent the current line only if point is at the left margin or
3209 in the line's indentation; otherwise insert some whitespace[*]. If
3210 other than nil or t, then some whitespace[*] is inserted only within
3211 literals (comments and strings), but the line is always reindented.
3213 If `c-syntactic-indentation' is t, indentation is done according to
3214 the syntactic context. A numeric argument, regardless of its value,
3215 means indent rigidly all the lines of the expression starting after
3216 point so that this line becomes properly indented. The relative
3217 indentation among the lines of the expression is preserved.
3219 If `c-syntactic-indentation' is nil, the line is just indented one
3220 step according to `c-basic-offset'. In this mode, a numeric argument
3221 indents a number of such steps, positive or negative, and an empty
3222 prefix argument is equivalent to -1.
3224 [*] The amount and kind of whitespace inserted is controlled by the
3225 variable `c-insert-tab-function', which is called to do the actual
3226 insertion of whitespace. Normally the function in this variable
3227 just inserts a tab character, or the equivalent number of spaces,
3228 depending on the variable `indent-tabs-mode'."
3230 (interactive "P")
3231 (let ((indent-function
3232 (if c-syntactic-indentation
3233 (symbol-function 'indent-according-to-mode)
3234 (lambda ()
3235 (let ((c-macro-start c-macro-start)
3236 (steps (if (equal arg '(4))
3238 (prefix-numeric-value arg))))
3239 (c-shift-line-indentation (* steps c-basic-offset))
3240 (when (and c-auto-align-backslashes
3241 (save-excursion
3242 (end-of-line)
3243 (eq (char-before) ?\\))
3244 (c-query-and-set-macro-start))
3245 ;; Realign the line continuation backslash if inside a macro.
3246 (c-backslash-region (point) (point) nil t)))
3247 ))))
3248 (if (and c-syntactic-indentation arg)
3249 ;; If c-syntactic-indentation and got arg, always indent this
3250 ;; line as C and shift remaining lines of expression the same
3251 ;; amount.
3252 (let ((shift-amt (save-excursion
3253 (back-to-indentation)
3254 (current-column)))
3255 beg end)
3256 (c-indent-line)
3257 (setq shift-amt (- (save-excursion
3258 (back-to-indentation)
3259 (current-column))
3260 shift-amt))
3261 (save-excursion
3262 (if (eq c-tab-always-indent t)
3263 (beginning-of-line)) ; FIXME!!! What is this here for? ACM 2005/10/31
3264 (setq beg (point))
3265 (c-forward-sexp 1)
3266 (setq end (point))
3267 (goto-char beg)
3268 (forward-line 1)
3269 (setq beg (point)))
3270 (if (> end beg)
3271 (indent-code-rigidly beg end shift-amt "#")))
3272 ;; Else use c-tab-always-indent to determine behavior.
3273 (cond
3274 ;; CASE 1: indent when at column zero or in line's indentation,
3275 ;; otherwise insert a tab
3276 ((not c-tab-always-indent)
3277 (if (save-excursion
3278 (skip-chars-backward " \t")
3279 (not (bolp)))
3280 (funcall c-insert-tab-function)
3281 (funcall indent-function)))
3282 ;; CASE 2: just indent the line
3283 ((eq c-tab-always-indent t)
3284 (funcall indent-function))
3285 ;; CASE 3: if in a literal, insert a tab, but always indent the
3286 ;; line
3288 (if (c-save-buffer-state () (c-in-literal))
3289 (funcall c-insert-tab-function))
3290 (funcall indent-function)
3291 )))))
3293 (defun c-indent-exp (&optional shutup-p)
3294 "Indent each line in the balanced expression following point syntactically.
3295 If optional SHUTUP-P is non-nil, no errors are signaled if no
3296 balanced expression is found."
3297 (interactive "*P")
3298 (let ((here (point-marker))
3299 end)
3300 (set-marker-insertion-type here t)
3301 (unwind-protect
3302 (let ((start (save-restriction
3303 ;; Find the closest following open paren that
3304 ;; ends on another line.
3305 (narrow-to-region (point-min) (c-point 'eol))
3306 (let (beg (end (point)))
3307 (while (and (setq beg (c-down-list-forward end))
3308 (setq end (c-up-list-forward beg))))
3309 (and beg
3310 (eq (char-syntax (char-before beg)) ?\()
3311 (1- beg))))))
3312 ;; sanity check
3313 (if (not start)
3314 (unless shutup-p
3315 (error "Cannot find start of balanced expression to indent"))
3316 (goto-char start)
3317 (setq end (c-safe (scan-sexps (point) 1)))
3318 (if (not end)
3319 (unless shutup-p
3320 (error "Cannot find end of balanced expression to indent"))
3321 (forward-line)
3322 (if (< (point) end)
3323 (c-indent-region (point) end)))))
3324 (goto-char here)
3325 (set-marker here nil))))
3327 (defun c-indent-defun ()
3328 "Indent the current top-level declaration or macro syntactically.
3329 In the macro case this also has the effect of realigning any line
3330 continuation backslashes, unless `c-auto-align-backslashes' is nil."
3331 (interactive "*")
3332 (let ((here (point-marker)) decl-limits case-fold-search)
3333 (unwind-protect
3334 (progn
3335 (c-save-buffer-state nil
3336 ;; We try to be line oriented, unless there are several
3337 ;; declarations on the same line.
3338 (if (looking-at c-syntactic-eol)
3339 (c-backward-token-2 1 nil (c-point 'bol))
3340 (c-forward-token-2 0 nil (c-point 'eol)))
3341 (setq decl-limits (c-declaration-limits nil)))
3342 (if decl-limits
3343 (c-indent-region (car decl-limits)
3344 (cdr decl-limits))))
3345 (goto-char here)
3346 (set-marker here nil))))
3348 (defun c-indent-region (start end &optional quiet)
3349 "Indent syntactically every line whose first char is between START
3350 and END inclusive. If the optional argument QUIET is non-nil then no
3351 syntactic errors are reported, even if `c-report-syntactic-errors' is
3352 non-nil."
3353 (save-excursion
3354 (goto-char end)
3355 (skip-chars-backward " \t\n\r\f\v")
3356 (setq end (point))
3357 (goto-char start)
3358 ;; Advance to first nonblank line.
3359 (beginning-of-line)
3360 (skip-chars-forward " \t\n\r\f\v")
3361 (setq start (point))
3362 (beginning-of-line)
3363 (setq c-parsing-error
3364 (or (let ((endmark (copy-marker end))
3365 (c-parsing-error nil)
3366 ;; shut up any echo msgs on indiv lines
3367 (c-echo-syntactic-information-p nil)
3368 (ml-macro-start ; Start pos of multi-line macro.
3369 (and (c-save-buffer-state ()
3370 (save-excursion (c-beginning-of-macro)))
3371 (eq (char-before (c-point 'eol)) ?\\)
3372 start))
3373 (c-fix-backslashes nil)
3374 syntax)
3375 (unwind-protect
3376 (progn
3377 (c-progress-init start end 'c-indent-region)
3379 (while (and (bolp) ;; One line each time round the loop.
3380 (not (eobp))
3381 (< (point) endmark))
3382 ;; update progress
3383 (c-progress-update)
3384 ;; skip empty lines
3385 (unless (or (looking-at "\\s *$")
3386 (and ml-macro-start (looking-at "\\s *\\\\$")))
3387 ;; Get syntax and indent.
3388 (c-save-buffer-state nil
3389 (setq syntax (c-guess-basic-syntax)))
3390 (c-indent-line syntax t t))
3392 (if ml-macro-start
3393 ;; End of current multi-line macro?
3394 (when (and c-auto-align-backslashes
3395 (not (eq (char-before (c-point 'eol)) ?\\)))
3396 ;; Fixup macro backslashes.
3397 (c-backslash-region ml-macro-start (c-point 'bonl) nil)
3398 (setq ml-macro-start nil))
3399 ;; New multi-line macro?
3400 (if (and (assq 'cpp-macro syntax)
3401 (eq (char-before (c-point 'eol)) ?\\))
3402 (setq ml-macro-start (point))))
3404 (forward-line))
3406 (if (and ml-macro-start c-auto-align-backslashes)
3407 (c-backslash-region ml-macro-start (c-point 'bopl) nil t)))
3408 (set-marker endmark nil)
3409 (c-progress-fini 'c-indent-region))
3410 (c-echo-parsing-error quiet))
3411 c-parsing-error))))
3413 (defun c-fn-region-is-active-p ()
3414 ;; Function version of the macro for use in places that aren't
3415 ;; compiled, e.g. in the menus.
3416 (c-region-is-active-p))
3418 (defun c-indent-line-or-region (&optional arg region)
3419 "Indent active region, current line, or block starting on this line.
3420 In Transient Mark mode, when the region is active, reindent the region.
3421 Otherwise, with a prefix argument, rigidly reindent the expression
3422 starting on the current line.
3423 Otherwise reindent just the current line."
3424 (interactive
3425 (list current-prefix-arg (c-region-is-active-p)))
3426 (if region
3427 (c-indent-region (region-beginning) (region-end))
3428 (c-indent-command arg)))
3430 ;; for progress reporting
3431 (defvar c-progress-info nil)
3433 (defun c-progress-init (start end context)
3434 (cond
3435 ;; Be silent
3436 ((not c-progress-interval))
3437 ;; Start the progress update messages. If this Emacs doesn't have
3438 ;; a built-in timer, just be dumb about it.
3439 ((not (fboundp 'current-time))
3440 (message "Indenting region... (this may take a while)"))
3441 ;; If progress has already been initialized, do nothing. otherwise
3442 ;; initialize the counter with a vector of:
3443 ;; [start end lastsec context]
3444 (c-progress-info)
3445 (t (setq c-progress-info (vector start
3446 (save-excursion
3447 (goto-char end)
3448 (point-marker))
3449 (nth 1 (current-time))
3450 context))
3451 (message "Indenting region..."))
3454 (defun c-progress-update ()
3455 (if (not (and c-progress-info c-progress-interval))
3457 (let ((now (nth 1 (current-time)))
3458 (start (aref c-progress-info 0))
3459 (end (aref c-progress-info 1))
3460 (lastsecs (aref c-progress-info 2)))
3461 ;; should we update? currently, update happens every 2 seconds,
3462 ;; what's the right value?
3463 (if (< c-progress-interval (- now lastsecs))
3464 (progn
3465 (message "Indenting region... (%d%% complete)"
3466 (floor (* 100.0 (- (point) start)) (- end start)))
3467 (aset c-progress-info 2 now)))
3470 (defun c-progress-fini (context)
3471 (if (not c-progress-interval)
3473 (if (or (eq context (aref c-progress-info 3))
3474 (eq context t))
3475 (progn
3476 (set-marker (aref c-progress-info 1) nil)
3477 (setq c-progress-info nil)
3478 (message "Indenting region... done")))))
3482 ;;; This page handles insertion and removal of backslashes for C macros.
3484 (defun c-backslash-region (from to delete-flag &optional line-mode)
3485 "Insert, align, or delete end-of-line backslashes on the lines in the region.
3486 With no argument, inserts backslashes and aligns existing backslashes.
3487 With an argument, deletes the backslashes. The backslash alignment is
3488 done according to the settings in `c-backslash-column',
3489 `c-backslash-max-column' and `c-auto-align-backslashes'.
3491 This function does not modify blank lines at the start of the region.
3492 If the region ends at the start of a line and the macro doesn't
3493 continue below it, the backslash (if any) at the end of the previous
3494 line is deleted.
3496 You can put the region around an entire macro definition and use this
3497 command to conveniently insert and align the necessary backslashes."
3498 (interactive "*r\nP")
3499 (let ((endmark (make-marker))
3500 ;; Keep the backslash trimming functions from changing the
3501 ;; whitespace around point, since in this case it's only the
3502 ;; position of point that tells the indentation of the line.
3503 (point-pos (if (save-excursion
3504 (skip-chars-backward " \t")
3505 (and (bolp) (looking-at "[ \t]*\\\\?$")))
3506 (point-marker)
3507 (point-min)))
3508 column longest-line-col bs-col-after-end)
3509 (save-excursion
3510 (goto-char to)
3511 (if (and (not line-mode) (bobp))
3512 ;; Nothing to do if to is at bob, since we should back up
3513 ;; and there's no line to back up to.
3515 (when (and (not line-mode) (bolp))
3516 ;; Do not back up the to line if line-mode is set, to make
3517 ;; e.g. c-newline-and-indent consistent regardless whether
3518 ;; the (newline) call leaves point at bol or not.
3519 (backward-char)
3520 (setq to (point)))
3521 (if delete-flag
3522 (progn
3523 (set-marker endmark (point))
3524 (goto-char from)
3525 (c-delete-backslashes-forward endmark point-pos))
3526 ;; Set bs-col-after-end to the column of any backslash
3527 ;; following the region, or nil if there is none.
3528 (setq bs-col-after-end
3529 (and (progn (end-of-line)
3530 (eq (char-before) ?\\))
3531 (= (forward-line 1) 0)
3532 (progn (end-of-line)
3533 (eq (char-before) ?\\))
3534 (1- (current-column))))
3535 (when line-mode
3536 ;; Back up the to line if line-mode is set, since the line
3537 ;; after the newly inserted line break should not be
3538 ;; touched in c-newline-and-indent.
3539 (setq to (max from (or (c-safe (c-point 'eopl)) from)))
3540 (unless bs-col-after-end
3541 ;; Set bs-col-after-end to non-nil in any case, since we
3542 ;; do not want to delete the backslash at the last line.
3543 (setq bs-col-after-end t)))
3544 (if (and line-mode
3545 (not c-auto-align-backslashes))
3546 (goto-char from)
3547 ;; Compute the smallest column number past the ends of all
3548 ;; the lines.
3549 (setq longest-line-col 0)
3550 (goto-char to)
3551 (if bs-col-after-end
3552 ;; Include one more line in the max column
3553 ;; calculation, since the to line will be backslashed
3554 ;; too.
3555 (forward-line 1))
3556 (end-of-line)
3557 (while (and (>= (point) from)
3558 (progn
3559 (if (eq (char-before) ?\\)
3560 (forward-char -1))
3561 (skip-chars-backward " \t")
3562 (setq longest-line-col (max longest-line-col
3563 (1+ (current-column))))
3564 (beginning-of-line)
3565 (not (bobp))))
3566 (backward-char))
3567 ;; Try to align with surrounding backslashes.
3568 (goto-char from)
3569 (beginning-of-line)
3570 (if (and (not (bobp))
3571 (progn (backward-char)
3572 (eq (char-before) ?\\)))
3573 (progn
3574 (setq column (1- (current-column)))
3575 (if (numberp bs-col-after-end)
3576 ;; Both a preceding and a following backslash.
3577 ;; Choose the greatest of them.
3578 (setq column (max column bs-col-after-end)))
3579 (goto-char from))
3580 ;; No preceding backslash. Try to align with one
3581 ;; following the region. Disregard the backslash at the
3582 ;; to line since it's likely to be bogus (e.g. when
3583 ;; called from c-newline-and-indent).
3584 (if (numberp bs-col-after-end)
3585 (setq column bs-col-after-end))
3586 ;; Don't modify blank lines at start of region.
3587 (goto-char from)
3588 (while (and (< (point) to) (bolp) (eolp))
3589 (forward-line 1)))
3590 (if (and column (< column longest-line-col))
3591 ;; Don't try to align with surrounding backslashes if
3592 ;; any line is too long.
3593 (setq column nil))
3594 (unless column
3595 ;; Impose minimum limit and tab width alignment only if
3596 ;; we can't align with surrounding backslashes.
3597 (if (> (% longest-line-col tab-width) 0)
3598 (setq longest-line-col
3599 (* (/ (+ longest-line-col tab-width -1)
3600 tab-width)
3601 tab-width)))
3602 (setq column (max c-backslash-column
3603 longest-line-col)))
3604 ;; Always impose maximum limit.
3605 (setq column (min column c-backslash-max-column)))
3606 (if bs-col-after-end
3607 ;; Add backslashes on all lines if the macro continues
3608 ;; after the to line.
3609 (progn
3610 (set-marker endmark to)
3611 (c-append-backslashes-forward endmark column point-pos))
3612 ;; Add backslashes on all lines except the last, and
3613 ;; remove any on the last line.
3614 (if (save-excursion
3615 (goto-char to)
3616 (beginning-of-line)
3617 (if (not (bobp))
3618 (set-marker endmark (1- (point)))))
3619 (progn
3620 (c-append-backslashes-forward endmark column point-pos)
3621 ;; The function above leaves point on the line
3622 ;; following endmark.
3623 (set-marker endmark (point)))
3624 (set-marker endmark to))
3625 (c-delete-backslashes-forward endmark point-pos)))))
3626 (set-marker endmark nil)
3627 (if (markerp point-pos)
3628 (set-marker point-pos nil))))
3630 (defun c-append-backslashes-forward (to-mark column point-pos)
3631 (let ((state (parse-partial-sexp (c-point 'bol) (point))))
3632 (if column
3633 (while
3634 (and
3635 (<= (point) to-mark)
3637 (let ((start (point)) (inserted nil) end col)
3638 (end-of-line)
3639 (unless (eq (char-before) ?\\)
3640 (insert ?\\)
3641 (setq inserted t))
3642 (setq state (parse-partial-sexp
3643 start (point) nil nil state))
3644 (backward-char)
3645 (setq col (current-column))
3647 ;; Avoid unnecessary changes of the buffer.
3648 (cond ((and (not inserted) (nth 3 state))
3649 ;; Don't realign backslashes in string literals
3650 ;; since that would change them.
3653 ((< col column)
3654 (delete-region
3655 (point)
3656 (progn
3657 (skip-chars-backward
3658 " \t" (if (>= (point) point-pos) point-pos))
3659 (point)))
3660 (indent-to column))
3662 ((and (= col column)
3663 (memq (char-before) '(?\ ?\t))))
3665 ((progn
3666 (setq end (point))
3667 (or (/= (skip-chars-backward
3668 " \t" (if (>= (point) point-pos) point-pos))
3670 (/= (char-after) ?\ )))
3671 (delete-region (point) end)
3672 (indent-to column 1)))
3674 (zerop (forward-line 1)))
3675 (bolp))) ; forward-line has funny behavior at eob.
3677 ;; Make sure there are backslashes with at least one space in
3678 ;; front of them.
3679 (while
3680 (and
3681 (<= (point) to-mark)
3683 (let ((start (point)))
3684 (end-of-line)
3685 (setq state (parse-partial-sexp
3686 start (point) nil nil state))
3688 (if (eq (char-before) ?\\)
3689 (unless (nth 3 state)
3690 (backward-char)
3691 (unless (and (memq (char-before) '(?\ ?\t))
3692 (/= (point) point-pos))
3693 (insert ?\ )))
3695 (if (and (memq (char-before) '(?\ ?\t))
3696 (/= (point) point-pos))
3697 (insert ?\\)
3698 (insert ?\ ?\\)))
3700 (zerop (forward-line 1)))
3701 (bolp)))))) ; forward-line has funny behavior at eob.
3703 (defun c-delete-backslashes-forward (to-mark point-pos)
3704 (while
3705 (and (<= (point) to-mark)
3706 (progn
3707 (end-of-line)
3708 (if (eq (char-before) ?\\)
3709 (delete-region
3710 (point)
3711 (progn (backward-char)
3712 (skip-chars-backward " \t" (if (>= (point) point-pos)
3713 point-pos))
3714 (point))))
3715 (zerop (forward-line 1)))
3716 (bolp)))) ; forward-line has funny behavior at eob.
3720 ;;; Line breaking and paragraph filling.
3722 (defvar c-auto-fill-prefix t)
3723 (defvar c-lit-limits nil)
3724 (defvar c-lit-type nil)
3726 ;; The filling code is based on a simple theory; leave the intricacies
3727 ;; of the text handling to the currently active mode for that
3728 ;; (e.g. adaptive-fill-mode or filladapt-mode) and do as little as
3729 ;; possible to make them work correctly wrt the comment and string
3730 ;; separators, one-line paragraphs etc. Unfortunately, when it comes
3731 ;; to it, there's quite a lot of special cases to handle which makes
3732 ;; the code anything but simple. The intention is that it will work
3733 ;; with any well-written text filling package that preserves a fill
3734 ;; prefix.
3736 ;; We temporarily mask comment starters and enders as necessary for
3737 ;; the filling code to do its job on a seemingly normal text block.
3738 ;; We do _not_ mask the fill prefix, so it's up to the filling code to
3739 ;; preserve it correctly (especially important when filling C++ style
3740 ;; line comments). By default, we set up and use adaptive-fill-mode,
3741 ;; which is standard in all supported Emacs flavors.
3743 (defun c-guess-fill-prefix (lit-limits lit-type)
3744 ;; Determine the appropriate comment fill prefix for a block or line
3745 ;; comment. Return a cons of the prefix string and the column where
3746 ;; it ends. If fill-prefix is set, it'll override. Note that this
3747 ;; function also uses the value of point in some heuristics.
3749 ;; This function might do hidden buffer changes.
3751 (let* ((here (point))
3752 (prefix-regexp (concat "[ \t]*\\("
3753 c-current-comment-prefix
3754 "\\)[ \t]*"))
3755 (comment-start-regexp (if (eq lit-type 'c++)
3756 prefix-regexp
3757 comment-start-skip))
3758 prefix-line comment-prefix res comment-text-end)
3760 (cond
3761 (fill-prefix
3762 (setq res (cons fill-prefix
3763 ;; Ugly way of getting the column after the fill
3764 ;; prefix; it'd be nice with a current-column
3765 ;; that works on strings..
3766 (let ((start (point)))
3767 (unwind-protect
3768 (progn
3769 (insert-and-inherit "\n" fill-prefix)
3770 (current-column))
3771 (delete-region start (point)))))))
3773 ((eq lit-type 'c++)
3774 (save-excursion
3775 ;; Set fallback for comment-prefix if none is found.
3776 (setq comment-prefix "// "
3777 comment-text-end (cdr lit-limits))
3779 (beginning-of-line)
3780 (if (> (point) (car lit-limits))
3781 ;; The current line is not the comment starter, so the
3782 ;; comment has more than one line, and it can therefore be
3783 ;; used to find the comment fill prefix.
3784 (setq prefix-line (point))
3786 (goto-char (car lit-limits))
3787 (if (and (= (forward-line 1) 0)
3788 (< (point) (cdr lit-limits)))
3789 ;; The line after the comment starter is inside the
3790 ;; comment, so we can use it.
3791 (setq prefix-line (point))
3793 ;; The comment is only one line. Take the comment prefix
3794 ;; from it and keep the indentation.
3795 (goto-char (car lit-limits))
3796 (if (looking-at prefix-regexp)
3797 (goto-char (match-end 0))
3798 (forward-char 2)
3799 (skip-chars-forward " \t"))
3801 (let (str col)
3802 (if (eq (c-point 'boi) (car lit-limits))
3803 ;; There is only whitespace before the comment
3804 ;; starter; take the prefix straight from this line.
3805 (setq str (buffer-substring-no-properties
3806 (c-point 'bol) (point))
3807 col (current-column))
3809 ;; There is code before the comment starter, so we
3810 ;; have to temporarily insert and indent a new line to
3811 ;; get the right space/tab mix in the indentation.
3812 (let ((prefix-len (- (point) (car lit-limits)))
3813 tmp)
3814 (unwind-protect
3815 (progn
3816 (goto-char (car lit-limits))
3817 (indent-to (prog1 (current-column)
3818 (insert ?\n)))
3819 (setq tmp (point))
3820 (forward-char prefix-len)
3821 (setq str (buffer-substring-no-properties
3822 (c-point 'bol) (point))
3823 col (current-column)))
3824 (delete-region (car lit-limits) tmp))))
3826 (setq res
3827 (if (or (string-match "\\s \\'" str) (not (eolp)))
3828 (cons str col)
3829 ;; The prefix ends the line with no whitespace
3830 ;; after it. Default to a single space.
3831 (cons (concat str " ") (1+ col))))
3832 )))))
3835 (setq comment-text-end
3836 (save-excursion
3837 (goto-char (- (cdr lit-limits) 2))
3838 (if (looking-at "\\*/") (point) (cdr lit-limits))))
3840 (save-excursion
3841 (beginning-of-line)
3842 (if (and (> (point) (car lit-limits))
3843 (not (and (looking-at "[ \t]*\\*/")
3844 (eq (cdr lit-limits) (match-end 0)))))
3845 ;; The current line is not the comment starter and
3846 ;; contains more than just the ender, so it's good enough
3847 ;; to be used for the comment fill prefix.
3848 (setq prefix-line (point))
3849 (goto-char (car lit-limits))
3851 (cond ((or (/= (forward-line 1) 0)
3852 (>= (point) (cdr lit-limits))
3853 (and (looking-at "[ \t]*\\*/")
3854 (eq (cdr lit-limits) (match-end 0)))
3855 (and (looking-at prefix-regexp)
3856 (<= (1- (cdr lit-limits)) (match-end 0))))
3857 ;; The comment is either one line or the next line contains
3858 ;; just the comment ender. In this case we have no
3859 ;; information about a suitable comment prefix, so we resort
3860 ;; to c-block-comment-prefix.
3861 (setq comment-prefix (or c-block-comment-prefix "")))
3863 ((< here (point))
3864 ;; The point was on the comment opener line, so we might want
3865 ;; to treat this as a not yet closed comment.
3867 (if (and (match-beginning 1)
3868 (/= (match-beginning 1) (match-end 1)))
3869 ;; Above `prefix-regexp' matched a nonempty prefix on the
3870 ;; second line, so let's use it. Normally it should do
3871 ;; to set `prefix-line' and let the code below pick up
3872 ;; the whole prefix, but if there's no text after the
3873 ;; match then it will probably fall back to no prefix at
3874 ;; all if the comment isn't closed yet, so in that case
3875 ;; it's better to force use of the prefix matched now.
3876 (if (= (match-end 0) (c-point 'eol))
3877 (setq comment-prefix (match-string 1))
3878 (setq prefix-line (point)))
3880 ;; There's no nonempty prefix on the line after the
3881 ;; comment opener. If the line is empty, or if the
3882 ;; text on it has less or equal indentation than the
3883 ;; comment starter we assume it's an unclosed
3884 ;; comment starter, i.e. that
3885 ;; `c-block-comment-prefix' should be used.
3886 ;; Otherwise we assume it's a closed comment where
3887 ;; the prefix really is the empty string.
3888 ;; E.g. this is an unclosed comment:
3890 ;; /*
3891 ;; foo
3893 ;; But this is not:
3895 ;; /*
3896 ;; foo
3897 ;; */
3899 ;; (Looking for the presence of the comment closer
3900 ;; rarely works since it's probably the closer of
3901 ;; some comment further down when the comment
3902 ;; really is unclosed.)
3903 (if (<= (save-excursion (back-to-indentation)
3904 (current-column))
3905 (save-excursion (goto-char (car lit-limits))
3906 (current-column)))
3907 (setq comment-prefix (or c-block-comment-prefix ""))
3908 (setq prefix-line (point)))))
3911 ;; Otherwise the line after the comment starter is good
3912 ;; enough to find the prefix in.
3913 (setq prefix-line (point))))
3915 (when comment-prefix
3916 ;; Haven't got the comment prefix on any real line that we
3917 ;; can take it from, so we have to temporarily insert
3918 ;; `comment-prefix' on a line and indent it to find the
3919 ;; correct column and the correct mix of tabs and spaces.
3920 (setq res
3921 (let (tmp-pre tmp-post)
3922 (unwind-protect
3923 (progn
3925 (goto-char (car lit-limits))
3926 (if (looking-at comment-start-regexp)
3927 (goto-char (min (match-end 0)
3928 comment-text-end))
3929 (forward-char 2)
3930 (skip-chars-forward " \t"))
3932 (when (eq (char-syntax (char-before)) ?\ )
3933 ;; If there's ws on the current line, we'll use it
3934 ;; instead of what's ending comment-prefix.
3935 (setq comment-prefix
3936 (concat (substring comment-prefix
3937 0 (string-match
3938 "\\s *\\'"
3939 comment-prefix))
3940 (buffer-substring-no-properties
3941 (save-excursion
3942 (skip-chars-backward " \t")
3943 (point))
3944 (point)))))
3946 (setq tmp-pre (point-marker))
3948 ;; We insert an extra non-whitespace character
3949 ;; before the line break and after comment-prefix in
3950 ;; case it's "" or ends with whitespace.
3951 (insert-and-inherit "x\n" comment-prefix "x")
3952 (setq tmp-post (point-marker))
3954 (indent-according-to-mode)
3956 (goto-char (1- tmp-post))
3957 (cons (buffer-substring-no-properties
3958 (c-point 'bol) (point))
3959 (current-column)))
3961 (when tmp-post
3962 (delete-region tmp-pre tmp-post)
3963 (set-marker tmp-pre nil)
3964 (set-marker tmp-post nil))))))))))
3966 (or res ; Found a good prefix above.
3968 (save-excursion
3969 ;; prefix-line is the bol of a line on which we should try
3970 ;; to find the prefix.
3971 (let* (fb-string fb-endpos ; Contains any fallback prefix found.
3972 (test-line
3973 (lambda ()
3974 (when (and (looking-at prefix-regexp)
3975 (<= (match-end 0) comment-text-end))
3976 (unless (eq (match-end 0) (c-point 'eol))
3977 ;; The match is fine if there's text after it.
3978 (throw 'found (cons (buffer-substring-no-properties
3979 (match-beginning 0) (match-end 0))
3980 (progn (goto-char (match-end 0))
3981 (current-column)))))
3982 (unless fb-string
3983 ;; This match is better than nothing, so let's
3984 ;; remember it in case nothing better is found
3985 ;; on another line.
3986 (setq fb-string (buffer-substring-no-properties
3987 (match-beginning 0) (match-end 0))
3988 fb-endpos (match-end 0)))
3989 t))))
3991 (or (catch 'found
3992 ;; Search for a line which has text after the prefix
3993 ;; so that we get the proper amount of whitespace
3994 ;; after it. We start with the current line, then
3995 ;; search backwards, then forwards.
3997 (goto-char prefix-line)
3998 (when (and (funcall test-line)
3999 (or (/= (match-end 1) (match-end 0))
4000 ;; The whitespace is sucked up by the
4001 ;; first [ \t]* glob if the prefix is empty.
4002 (and (= (match-beginning 1) (match-end 1))
4003 (/= (match-beginning 0) (match-end 0)))))
4004 ;; If the current line doesn't have text but do
4005 ;; have whitespace after the prefix, we'll use it.
4006 (throw 'found (cons fb-string
4007 (progn (goto-char fb-endpos)
4008 (current-column)))))
4010 (if (eq lit-type 'c++)
4011 ;; For line comments we can search up to and
4012 ;; including the first line.
4013 (while (and (zerop (forward-line -1))
4014 (>= (point) (car lit-limits)))
4015 (funcall test-line))
4016 ;; For block comments we must stop before the
4017 ;; block starter.
4018 (while (and (zerop (forward-line -1))
4019 (> (point) (car lit-limits)))
4020 (funcall test-line)))
4022 (goto-char prefix-line)
4023 (while (and (zerop (forward-line 1))
4024 (< (point) (cdr lit-limits)))
4025 (funcall test-line))
4027 (goto-char prefix-line)
4028 nil)
4030 (when fb-string
4031 ;; A good line wasn't found, but at least we have a
4032 ;; fallback that matches the comment prefix regexp.
4033 (cond ((or (string-match "\\s \\'" fb-string)
4034 (progn
4035 (goto-char fb-endpos)
4036 (not (eolp))))
4037 ;; There are ws or text after the prefix, so
4038 ;; let's use it.
4039 (cons fb-string (current-column)))
4041 ((progn
4042 ;; Check if there's any whitespace padding
4043 ;; on the comment start line that we can
4044 ;; use after the prefix.
4045 (goto-char (car lit-limits))
4046 (if (looking-at comment-start-regexp)
4047 (goto-char (match-end 0))
4048 (forward-char 2)
4049 (skip-chars-forward " \t"))
4050 (or (not (eolp))
4051 (eq (char-syntax (char-before)) ?\ )))
4053 (setq fb-string (buffer-substring-no-properties
4054 (save-excursion
4055 (skip-chars-backward " \t")
4056 (point))
4057 (point)))
4058 (goto-char fb-endpos)
4059 (skip-chars-backward " \t")
4061 (let ((tmp (point)))
4062 ;; Got to mess in the buffer once again to
4063 ;; ensure the column gets correct. :P
4064 (unwind-protect
4065 (progn
4066 (insert-and-inherit fb-string)
4067 (cons (buffer-substring-no-properties
4068 (c-point 'bol)
4069 (point))
4070 (current-column)))
4071 (delete-region tmp (point)))))
4074 ;; Last resort: Just add a single space after
4075 ;; the prefix.
4076 (cons (concat fb-string " ")
4077 (progn (goto-char fb-endpos)
4078 (1+ (current-column)))))))
4080 ;; The line doesn't match the comment prefix regexp.
4081 (if comment-prefix
4082 ;; We have a fallback for line comments that we must use.
4083 (cons (concat (buffer-substring-no-properties
4084 prefix-line (c-point 'boi))
4085 comment-prefix)
4086 (progn (back-to-indentation)
4087 (+ (current-column) (length comment-prefix))))
4089 ;; Assume we are dealing with a "free text" block
4090 ;; comment where the lines doesn't have any comment
4091 ;; prefix at all and we should just fill it as
4092 ;; normal text.
4093 '("" . 0))))))
4096 (defun c-mask-paragraph (fill-paragraph apply-outside-literal fun &rest args)
4097 ;; Calls FUN with ARGS ar arguments while the current paragraph is
4098 ;; masked to allow adaptive filling to work correctly. That
4099 ;; includes narrowing the buffer and, if point is inside a comment,
4100 ;; masking the comment starter and ender appropriately.
4102 ;; FILL-PARAGRAPH is non-nil if called for whole paragraph filling.
4103 ;; The position of point is then less significant when doing masking
4104 ;; and narrowing.
4106 ;; If APPLY-OUTSIDE-LITERAL is nil then the function will be called
4107 ;; only if the point turns out to be inside a comment or a string.
4109 ;; Note that this function does not do any hidden buffer changes.
4111 (let (fill
4112 ;; beg and end limit the region to narrow. end is a marker.
4113 beg end
4114 ;; tmp-pre and tmp-post mark strings that are temporarily
4115 ;; inserted at the start and end of the region. tmp-pre is a
4116 ;; cons of the positions of the prepended string. tmp-post is
4117 ;; a marker pointing to the single character of the appended
4118 ;; string.
4119 tmp-pre tmp-post
4120 ;; If hang-ender-stuck isn't nil, the comment ender is
4121 ;; hanging. In that case it's set to the number of spaces
4122 ;; that should be between the text and the ender.
4123 hang-ender-stuck
4124 ;; auto-fill-spaces is the exact sequence of whitespace between a
4125 ;; comment's last word and the comment ender, temporarily replaced
4126 ;; with 'x's before calling FUN when FILL-PARAGRAPH is nil.
4127 auto-fill-spaces
4128 (here (point))
4129 (c-lit-limits c-lit-limits)
4130 (c-lit-type c-lit-type))
4132 ;; Restore point on undo. It's necessary since we do a lot of
4133 ;; hidden inserts and deletes below that should be as transparent
4134 ;; as possible.
4135 (if (and buffer-undo-list (not (eq buffer-undo-list t)))
4136 (setq buffer-undo-list (cons (point) buffer-undo-list)))
4138 ;; Determine the limits and type of the containing literal (if any):
4139 ;; C-LIT-LIMITS, C-LIT-TYPE; and the limits of the current paragraph:
4140 ;; BEG and END.
4141 (c-save-buffer-state ()
4142 (save-restriction
4143 ;; Widen to catch comment limits correctly.
4144 (widen)
4145 (unless c-lit-limits
4146 (setq c-lit-limits (c-literal-limits nil fill-paragraph)))
4147 (setq c-lit-limits (c-collect-line-comments c-lit-limits))
4148 (unless c-lit-type
4149 (setq c-lit-type (c-literal-type c-lit-limits))))
4151 (save-excursion
4152 (unless (c-safe (backward-char)
4153 (forward-paragraph)
4154 (>= (point) here))
4155 (goto-char here)
4156 (forward-paragraph))
4157 (setq end (point-marker)))
4158 (save-excursion
4159 (unless (c-safe (forward-char)
4160 (backward-paragraph)
4161 (<= (point) here))
4162 (goto-char here)
4163 (backward-paragraph))
4164 (setq beg (point))))
4166 (unwind-protect
4167 (progn
4168 ;; For each of the possible types of text (string, C comment ...)
4169 ;; determine BEG and END, the region we will narrow to. If we're in
4170 ;; a literal, constrain BEG and END to the limits of this literal.
4172 ;; For some of these text types, particularly a block comment, we
4173 ;; may need to massage whitespace near literal delimiters, so that
4174 ;; these don't get filled inappropriately.
4175 (cond
4177 ((eq c-lit-type 'c++) ; Line comment.
4178 (save-excursion
4179 ;; Limit to the comment or paragraph end, whichever
4180 ;; comes first.
4181 (set-marker end (min end (cdr c-lit-limits)))
4183 (when (<= beg (car c-lit-limits))
4184 ;; The region includes the comment starter, so we must
4185 ;; check it.
4186 (goto-char (car c-lit-limits))
4187 (back-to-indentation)
4188 (if (eq (point) (car c-lit-limits))
4189 ;; Include the first line in the region.
4190 (setq beg (c-point 'bol))
4191 ;; The first line contains code before the
4192 ;; comment. We must fake a line that doesn't.
4193 (setq tmp-pre t))))
4195 (setq apply-outside-literal t))
4197 ((eq c-lit-type 'c) ; Block comment.
4198 (when
4199 (or (> end (cdr c-lit-limits))
4200 (and (= end (cdr c-lit-limits))
4201 (eq (char-before end) ?/)
4202 (eq (char-before (1- end)) ?*)
4203 ;; disallow "/*/"
4204 (> (- (cdr c-lit-limits) (car c-lit-limits)) 3)))
4205 ;; There is a comment ender, and the region includes it. If
4206 ;; it's on its own line, it stays on its own line. If it's got
4207 ;; company on the line, it keeps (at least one word of) it.
4208 ;; "=====*/" counts as a comment ender here, but "===== */"
4209 ;; doesn't and "foo*/" doesn't.
4210 (unless
4211 (save-excursion
4212 (goto-char (cdr c-lit-limits))
4213 (beginning-of-line)
4214 ;; The following conjunct was added to avoid an
4215 ;; "Invalid search bound (wrong side of point)"
4216 ;; error in the subsequent re-search. Maybe
4217 ;; another fix would be needed (2007-12-08).
4218 ; (or (<= (- (cdr c-lit-limits) 2) (point))
4219 ; 2010-10-17 Construct removed.
4220 ; (or (< (- (cdr c-lit-limits) 2) (point))
4221 (and
4222 (search-forward-regexp
4223 (concat "\\=[ \t]*\\(" c-current-comment-prefix "\\)")
4224 (- (cdr c-lit-limits) 2) t)
4225 (not (search-forward-regexp
4226 "\\(\\s \\|\\sw\\)"
4227 (- (cdr c-lit-limits) 2) 'limit))
4228 ;; The comment ender IS on its own line. Exclude this
4229 ;; line from the filling.
4230 (set-marker end (c-point 'bol))));)
4232 ;; The comment ender is hanging. Replace all space between it
4233 ;; and the last word either by one or two 'x's (when
4234 ;; FILL-PARAGRAPH is non-nil), or a row of x's the same width
4235 ;; as the whitespace (when auto filling), and include it in
4236 ;; the region. We'll change them back to whitespace
4237 ;; afterwards. The effect of this is to glue the comment
4238 ;; ender to the last word in the comment during filling.
4239 (let* ((ender-start (save-excursion
4240 (goto-char (cdr c-lit-limits))
4241 (skip-syntax-backward "^w ")
4242 (point)))
4243 (ender-column (save-excursion
4244 (goto-char ender-start)
4245 (current-column)))
4246 (point-rel (- ender-start here))
4247 (sentence-ends-comment
4248 (save-excursion
4249 (goto-char ender-start)
4250 (and (search-backward-regexp
4251 (c-sentence-end) (c-point 'bol) t)
4252 (goto-char (match-end 0))
4253 (looking-at "[ \t]*")
4254 (= (match-end 0) ender-start))))
4255 spaces)
4257 (save-excursion
4258 ;; Insert a CR after the "*/", adjust END
4259 (goto-char (cdr c-lit-limits))
4260 (setq tmp-post (point-marker))
4261 (insert ?\n)
4262 (set-marker end (point))
4264 (forward-line -1) ; last line of the comment
4265 (if (and (looking-at (concat "[ \t]*\\(\\("
4266 c-current-comment-prefix
4267 "\\)[ \t]*\\)"))
4268 (eq ender-start (match-end 0)))
4269 ;; The comment ender is prefixed by nothing but a
4270 ;; comment line prefix. IS THIS POSSIBLE? (ACM,
4271 ;; 2006/4/28). Remove it along with surrounding ws.
4272 (setq spaces (- (match-end 1) (match-end 2)))
4273 (goto-char ender-start))
4274 (skip-chars-backward " \t\r\n") ; Surely this can be
4275 ; " \t"? "*/" is NOT alone on the line (ACM, 2005/8/18)
4277 ;; What's being tested here? 2006/4/20. FIXME!!!
4278 (if (/= (point) ender-start)
4279 (progn
4280 (if (<= here (point))
4281 ;; Don't adjust point below if it's
4282 ;; before the string we replace.
4283 (setq point-rel -1))
4284 ;; Keep one or two spaces between the
4285 ;; text and the ender, depending on how
4286 ;; many there are now.
4287 (unless spaces
4288 (setq spaces (- ender-column (current-column))))
4289 (setq auto-fill-spaces (c-delete-and-extract-region
4290 (point) ender-start))
4291 ;; paragraph filling condenses multiple spaces to
4292 ;; single or double spaces. auto-fill doesn't.
4293 (if fill-paragraph
4294 (setq spaces
4295 (max
4296 (min spaces
4297 (if (and sentence-ends-comment
4298 sentence-end-double-space)
4299 2 1))
4300 1)))
4301 ;; Insert the filler first to keep marks right.
4302 (insert-char ?x spaces t)
4303 (setq hang-ender-stuck spaces)
4304 (setq point-rel
4305 (and (>= point-rel 0)
4306 (- (point) (min point-rel spaces)))))
4307 (setq point-rel nil)))
4309 (if point-rel
4310 ;; Point was in the middle of the string we
4311 ;; replaced above, so put it back in the same
4312 ;; relative position, counting from the end.
4313 (goto-char point-rel)))
4316 (when (<= beg (car c-lit-limits))
4317 ;; The region includes the comment starter.
4318 (save-excursion
4319 (goto-char (car c-lit-limits))
4320 (if (looking-at (concat "\\(" comment-start-skip "\\)$"))
4321 ;; Begin with the next line.
4322 (setq beg (c-point 'bonl))
4323 ;; Fake the fill prefix in the first line.
4324 (setq tmp-pre t))))
4326 (setq apply-outside-literal t))
4328 ((eq c-lit-type 'string) ; String.
4329 (save-excursion
4330 (when (>= end (cdr c-lit-limits))
4331 (goto-char (1- (cdr c-lit-limits)))
4332 (setq tmp-post (point-marker))
4333 (insert ?\n)
4334 (set-marker end (point)))
4335 (when (<= beg (car c-lit-limits))
4336 (goto-char (1+ (car c-lit-limits)))
4337 (setq beg (if (looking-at "\\\\$")
4338 ;; Leave the start line if it's
4339 ;; nothing but an escaped newline.
4340 (1+ (match-end 0))
4341 (point)))))
4342 (setq apply-outside-literal t))
4344 ((eq c-lit-type 'pound) ; Macro
4345 ;; Narrow to the macro limits if they are nearer than the
4346 ;; paragraph limits. Don't know if this is necessary but
4347 ;; do it for completeness sake (doing auto filling at all
4348 ;; inside macros is bogus to begin with since the line
4349 ;; continuation backslashes aren't handled).
4350 (save-excursion
4351 (c-save-buffer-state ()
4352 (c-beginning-of-macro)
4353 (beginning-of-line)
4354 (if (> (point) beg)
4355 (setq beg (point)))
4356 (c-end-of-macro)
4357 (forward-line)
4358 (if (< (point) end)
4359 (set-marker end (point))))))
4361 (t ; Other code.
4362 ;; Try to avoid comments and macros in the paragraph to
4363 ;; avoid that the adaptive fill mode gets the prefix from
4364 ;; them.
4365 (c-save-buffer-state nil
4366 (save-excursion
4367 (goto-char beg)
4368 (c-forward-syntactic-ws end)
4369 (beginning-of-line)
4370 (setq beg (point))
4371 (goto-char end)
4372 (c-backward-syntactic-ws beg)
4373 (forward-line)
4374 (set-marker end (point))))))
4376 (when tmp-pre
4377 ;; Temporarily insert the fill prefix after the comment
4378 ;; starter so that the first line looks like any other
4379 ;; comment line in the narrowed region.
4380 (setq fill (c-save-buffer-state nil
4381 (c-guess-fill-prefix c-lit-limits c-lit-type)))
4382 (unless (string-match (concat "\\`[ \t]*\\("
4383 c-current-comment-prefix
4384 "\\)[ \t]*\\'")
4385 (car fill))
4386 ;; Oops, the prefix doesn't match the comment prefix
4387 ;; regexp. This could produce very confusing
4388 ;; results with adaptive fill packages together with
4389 ;; the insert prefix magic below, since the prefix
4390 ;; often doesn't appear at all. So let's warn about
4391 ;; it.
4392 (message "\
4393 Warning: Regexp from `c-comment-prefix-regexp' doesn't match the comment prefix %S"
4394 (car fill)))
4395 ;; Find the right spot on the line, break it, insert
4396 ;; the fill prefix and make sure we're back in the
4397 ;; same column by temporarily prefixing the first word
4398 ;; with a number of 'x'.
4399 (save-excursion
4400 (goto-char (car c-lit-limits))
4401 (if (looking-at (if (eq c-lit-type 'c++)
4402 c-current-comment-prefix
4403 comment-start-skip))
4404 (goto-char (match-end 0))
4405 (forward-char 2)
4406 (skip-chars-forward " \t"))
4407 (while (and (< (current-column) (cdr fill))
4408 (not (eolp)))
4409 (forward-char 1))
4410 (let ((col (current-column)))
4411 (setq beg (1+ (point))
4412 tmp-pre (list (point)))
4413 (unwind-protect
4414 (progn
4415 (insert-and-inherit "\n" (car fill))
4416 (insert-char ?x (- col (current-column)) t))
4417 (setcdr tmp-pre (point))))))
4419 (when apply-outside-literal
4420 ;; `apply-outside-literal' is always set to t here if
4421 ;; we're inside a literal.
4423 (let ((fill-prefix
4424 (or fill-prefix
4425 ;; Kludge: If the function that adapts the fill prefix
4426 ;; doesn't produce the required comment starter for
4427 ;; line comments, then force it by setting fill-prefix.
4428 (when (and (eq c-lit-type 'c++)
4429 ;; Kludge the kludge: filladapt-mode doesn't
4430 ;; have this problem, but it currently
4431 ;; doesn't override fill-context-prefix
4432 ;; (version 2.12).
4433 (not (and (boundp 'filladapt-mode)
4434 filladapt-mode))
4435 (not (string-match
4436 "\\`[ \t]*//"
4437 (or (fill-context-prefix beg end)
4438 ""))))
4439 (c-save-buffer-state nil
4440 (car (or fill (c-guess-fill-prefix
4441 c-lit-limits c-lit-type)))))))
4443 ;; Save the relative position of point if it's outside the
4444 ;; region we're going to narrow. Want to restore it in that
4445 ;; case, but otherwise it should be moved according to the
4446 ;; called function.
4447 (point-rel (cond ((< (point) beg) (- (point) beg))
4448 ((> (point) end) (- (point) end)))))
4450 ;; Preparations finally done! Now we can call the
4451 ;; actual function.
4452 (prog1
4453 (save-restriction
4454 (narrow-to-region beg end)
4455 (apply fun args))
4456 (if point-rel
4457 ;; Restore point if it was outside the region.
4458 (if (< point-rel 0)
4459 (goto-char (+ beg point-rel))
4460 (goto-char (+ end point-rel))))))))
4462 (when (consp tmp-pre)
4463 (delete-region (car tmp-pre) (cdr tmp-pre)))
4465 (when tmp-post
4466 (save-excursion
4467 (goto-char tmp-post)
4468 (delete-char 1))
4469 (when hang-ender-stuck
4470 ;; Preserve point even if it's in the middle of the string
4471 ;; we replace; save-excursion doesn't work in that case.
4472 (setq here (point))
4473 (goto-char tmp-post)
4474 (skip-syntax-backward "^w ")
4475 (forward-char (- hang-ender-stuck))
4476 (if (or fill-paragraph (not auto-fill-spaces))
4477 (insert-char ?\ hang-ender-stuck t)
4478 (insert auto-fill-spaces))
4479 (delete-char hang-ender-stuck)
4480 (goto-char here))
4481 (set-marker tmp-post nil))
4483 (set-marker end nil))))
4485 (defun c-fill-paragraph (&optional arg)
4486 "Like \\[fill-paragraph] but handles C and C++ style comments.
4487 If any of the current line is a comment or within a comment, fill the
4488 comment or the paragraph of it that point is in, preserving the
4489 comment indentation or line-starting decorations (see the
4490 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
4491 details).
4493 If point is inside multiline string literal, fill it. This currently
4494 does not respect escaped newlines, except for the special case when it
4495 is the very first thing in the string. The intended use for this rule
4496 is in situations like the following:
4498 char description[] = \"\\
4499 A very long description of something that you want to fill to make
4500 nicely formatted output.\";
4502 If point is in any other situation, i.e. in normal code, do nothing.
4504 Optional prefix ARG means justify paragraph as well."
4505 (interactive "*P")
4506 (let ((fill-paragraph-function
4507 ;; Avoid infinite recursion.
4508 (if (not (eq fill-paragraph-function 'c-fill-paragraph))
4509 fill-paragraph-function)))
4510 (c-mask-paragraph t nil 'fill-paragraph arg))
4511 ;; Always return t. This has the effect that if filling isn't done
4512 ;; above, it isn't done at all, and it's therefore effectively
4513 ;; disabled in normal code.
4516 (defun c-do-auto-fill ()
4517 ;; Do automatic filling if not inside a context where it should be
4518 ;; ignored.
4519 (let ((c-auto-fill-prefix
4520 ;; The decision whether the line should be broken is actually
4521 ;; done in c-indent-new-comment-line, which do-auto-fill
4522 ;; calls to break lines. We just set this special variable
4523 ;; so that we'll know when we're called from there. It's
4524 ;; also used to detect whether fill-prefix is user set or
4525 ;; generated automatically by do-auto-fill.
4526 fill-prefix))
4527 (c-mask-paragraph nil t 'do-auto-fill)))
4529 (defun c-indent-new-comment-line (&optional soft allow-auto-fill)
4530 "Break line at point and indent, continuing comment or macro if within one.
4531 If inside a comment and `comment-multi-line' is non-nil, the
4532 indentation and line prefix are preserved (see the
4533 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
4534 details). If inside a single line comment and `comment-multi-line' is
4535 nil, a new comment of the same type is started on the next line and
4536 indented as appropriate for comments. If inside a macro, a line
4537 continuation backslash is inserted and aligned as appropriate, and the
4538 new line is indented according to `c-syntactic-indentation'.
4540 If a fill prefix is specified, it overrides all the above."
4541 ;; allow-auto-fill is used from c-context-line-break to allow auto
4542 ;; filling to break the line more than once. Since this function is
4543 ;; used from auto-fill itself, that's normally disabled to avoid
4544 ;; unnecessary recursion.
4545 (interactive)
4546 (let ((fill-prefix fill-prefix)
4547 (do-line-break
4548 (lambda ()
4549 (delete-horizontal-space)
4550 (if soft
4551 (insert-and-inherit ?\n)
4552 (newline (if allow-auto-fill nil 1)))))
4553 ;; Already know the literal type and limits when called from
4554 ;; c-context-line-break.
4555 (c-lit-limits c-lit-limits)
4556 (c-lit-type c-lit-type)
4557 (c-macro-start c-macro-start))
4559 (c-save-buffer-state ()
4560 (when (not (eq c-auto-fill-prefix t))
4561 ;; Called from do-auto-fill.
4562 (unless c-lit-limits
4563 (setq c-lit-limits (c-literal-limits nil nil t)))
4564 (unless c-lit-type
4565 (setq c-lit-type (c-literal-type c-lit-limits)))
4566 (if (memq (cond ((c-query-and-set-macro-start) 'cpp)
4567 ((null c-lit-type) 'code)
4568 (t c-lit-type))
4569 c-ignore-auto-fill)
4570 (setq fill-prefix t) ; Used as flag in the cond.
4571 (if (and (null c-auto-fill-prefix)
4572 (eq c-lit-type 'c)
4573 (<= (c-point 'bol) (car c-lit-limits)))
4574 ;; The adaptive fill function has generated a prefix, but
4575 ;; we're on the first line in a block comment so it'll be
4576 ;; wrong. Ignore it to guess a better one below.
4577 (setq fill-prefix nil)
4578 (when (and (eq c-lit-type 'c++)
4579 (not (string-match (concat "\\`[ \t]*"
4580 c-line-comment-starter)
4581 (or fill-prefix ""))))
4582 ;; Kludge: If the function that adapted the fill prefix
4583 ;; doesn't produce the required comment starter for line
4584 ;; comments, then we ignore it.
4585 (setq fill-prefix nil)))
4588 (cond ((eq fill-prefix t)
4589 ;; A call from do-auto-fill which should be ignored.
4591 (fill-prefix
4592 ;; A fill-prefix overrides anything.
4593 (funcall do-line-break)
4594 (insert-and-inherit fill-prefix))
4595 ((c-save-buffer-state ()
4596 (unless c-lit-limits
4597 (setq c-lit-limits (c-literal-limits)))
4598 (unless c-lit-type
4599 (setq c-lit-type (c-literal-type c-lit-limits)))
4600 (memq c-lit-type '(c c++)))
4601 ;; Some sort of comment.
4602 (if (or comment-multi-line
4603 (save-excursion
4604 (goto-char (car c-lit-limits))
4605 (end-of-line)
4606 (< (point) (cdr c-lit-limits))))
4607 ;; Inside a comment that should be continued.
4608 (let ((fill (c-save-buffer-state nil
4609 (c-guess-fill-prefix
4610 (setq c-lit-limits
4611 (c-collect-line-comments c-lit-limits))
4612 c-lit-type)))
4613 (pos (point))
4614 (start-col (current-column))
4615 (comment-text-end
4616 (or (and (eq c-lit-type 'c)
4617 (save-excursion
4618 (goto-char (- (cdr c-lit-limits) 2))
4619 (if (looking-at "\\*/") (point))))
4620 (cdr c-lit-limits))))
4621 ;; Skip forward past the fill prefix in case
4622 ;; we're standing in it.
4624 ;; FIXME: This doesn't work well in cases like
4626 ;; /* Bla bla bla bla bla
4627 ;; bla bla
4629 ;; If point is on the 'B' then the line will be
4630 ;; broken after "Bla b".
4632 ;; If we have an empty comment, /* */, the next
4633 ;; lot of code pushes point to the */. We fix
4634 ;; this by never allowing point to end up to the
4635 ;; right of where it started.
4636 (while (and (< (current-column) (cdr fill))
4637 (not (eolp)))
4638 (forward-char 1))
4639 (if (and (> (point) comment-text-end)
4640 (> (c-point 'bol) (car c-lit-limits)))
4641 (progn
4642 ;; The skip takes us out of the (block)
4643 ;; comment; insert the fill prefix at bol
4644 ;; instead and keep the position.
4645 (setq pos (copy-marker pos t))
4646 (beginning-of-line)
4647 (insert-and-inherit (car fill))
4648 (if soft (insert-and-inherit ?\n) (newline 1))
4649 (goto-char pos)
4650 (set-marker pos nil))
4651 ;; Don't break in the middle of a comment starter
4652 ;; or ender.
4653 (cond ((> (point) comment-text-end)
4654 (goto-char comment-text-end))
4655 ((< (point) (+ (car c-lit-limits) 2))
4656 (goto-char (+ (car c-lit-limits) 2))))
4657 (funcall do-line-break)
4658 (insert-and-inherit (car fill))
4659 (if (> (current-column) start-col)
4660 (move-to-column start-col)))) ; can this hit the
4661 ; middle of a TAB?
4662 ;; Inside a comment that should be broken.
4663 (let ((comment-start comment-start)
4664 (comment-end comment-end)
4665 col)
4666 (if (eq c-lit-type 'c)
4667 (unless (string-match "[ \t]*/\\*" comment-start)
4668 (setq comment-start "/* " comment-end " */"))
4669 (unless (string-match "[ \t]*//" comment-start)
4670 (setq comment-start "// " comment-end "")))
4671 (setq col (save-excursion
4672 (back-to-indentation)
4673 (current-column)))
4674 (funcall do-line-break)
4675 (when (and comment-end (not (equal comment-end "")))
4676 (forward-char -1)
4677 (insert-and-inherit comment-end)
4678 (forward-char 1))
4679 ;; c-comment-indent may look at the current
4680 ;; indentation, so let's start out with the same
4681 ;; indentation as the previous one.
4682 (indent-to col)
4683 (insert-and-inherit comment-start)
4684 (indent-for-comment))))
4685 ((c-query-and-set-macro-start)
4686 ;; In a macro.
4687 (unless (looking-at "[ \t]*\\\\$")
4688 ;; Do not clobber the alignment of the line continuation
4689 ;; slash; c-backslash-region might look at it.
4690 (delete-horizontal-space))
4691 ;; Got an asymmetry here: In normal code this command
4692 ;; doesn't indent the next line syntactically, and otoh a
4693 ;; normal syntactically indenting newline doesn't continue
4694 ;; the macro.
4695 (c-newline-and-indent (if allow-auto-fill nil 1)))
4697 ;; Somewhere else in the code.
4698 (let ((col (save-excursion
4699 (beginning-of-line)
4700 (while (and (looking-at "[ \t]*\\\\?$")
4701 (= (forward-line -1) 0)))
4702 (current-indentation))))
4703 (funcall do-line-break)
4704 (indent-to col))))))
4706 (defalias 'c-comment-line-break-function 'c-indent-new-comment-line)
4707 (make-obsolete 'c-comment-line-break-function 'c-indent-new-comment-line "21.1")
4709 ;; advice for indent-new-comment-line for older Emacsen
4710 (unless (boundp 'comment-line-break-function)
4711 (defvar c-inside-line-break-advice nil)
4712 (defadvice indent-new-comment-line (around c-line-break-advice
4713 activate preactivate)
4714 "Call `c-indent-new-comment-line' if in CC Mode."
4715 (if (or c-inside-line-break-advice
4716 (not c-buffer-is-cc-mode))
4717 ad-do-it
4718 (let ((c-inside-line-break-advice t))
4719 (c-indent-new-comment-line (ad-get-arg 0))))))
4721 (defun c-context-line-break ()
4722 "Do a line break suitable to the context.
4724 When point is outside a comment or macro, insert a newline and indent
4725 according to the syntactic context, unless `c-syntactic-indentation'
4726 is nil, in which case the new line is indented as the previous
4727 non-empty line instead.
4729 When point is inside the content of a preprocessor directive, a line
4730 continuation backslash is inserted before the line break and aligned
4731 appropriately. The end of the cpp directive doesn't count as inside
4734 When point is inside a comment, continue it with the appropriate
4735 comment prefix (see the `c-comment-prefix-regexp' and
4736 `c-block-comment-prefix' variables for details). The end of a
4737 C++-style line comment doesn't count as inside it.
4739 When point is inside a string, only insert a backslash when it is also
4740 inside a preprocessor directive."
4742 (interactive "*")
4743 (let* (c-lit-limits c-lit-type
4744 (c-macro-start c-macro-start)
4745 case-fold-search)
4747 (c-save-buffer-state ()
4748 (setq c-lit-limits (c-literal-limits nil nil t)
4749 c-lit-type (c-literal-type c-lit-limits))
4750 (when (eq c-lit-type 'c++)
4751 (setq c-lit-limits (c-collect-line-comments c-lit-limits)))
4752 (c-query-and-set-macro-start))
4754 (cond
4755 ((or (eq c-lit-type 'c)
4756 (and (eq c-lit-type 'c++) ; C++ comment, but not at the very end of it.
4757 (< (save-excursion
4758 (skip-chars-forward " \t")
4759 (point))
4760 (1- (cdr c-lit-limits))))
4761 (and (numberp c-macro-start) ; Macro, but not at the very end of
4762 ; it, not in a string, and not in the
4763 ; cpp keyword.
4764 (not (eq c-lit-type 'string))
4765 (or (not (looking-at "\\s *$"))
4766 (eq (char-before) ?\\))
4767 (<= (save-excursion
4768 (goto-char c-macro-start)
4769 (if (looking-at c-opt-cpp-start)
4770 (goto-char (match-end 0)))
4771 (point))
4772 (point))))
4773 (let ((comment-multi-line t)
4774 (fill-prefix nil))
4775 (c-indent-new-comment-line nil t)))
4777 ((eq c-lit-type 'string)
4778 (if (and (numberp c-macro-start)
4779 (not (eq (char-before) ?\\)))
4780 (insert ?\\))
4781 (newline))
4783 (t (delete-horizontal-space)
4784 (newline)
4785 ;; c-indent-line may look at the current indentation, so let's
4786 ;; start out with the same indentation as the previous line.
4787 (let ((col (save-excursion
4788 (backward-char)
4789 (forward-line 0)
4790 (while (and (looking-at "[ \t]*\\\\?$")
4791 (= (forward-line -1) 0)))
4792 (current-indentation))))
4793 (indent-to col))
4794 (indent-according-to-mode)))))
4796 (defun c-context-open-line ()
4797 "Insert a line break suitable to the context and leave point before it.
4798 This is the `c-context-line-break' equivalent to `open-line', which is
4799 normally bound to C-o. See `c-context-line-break' for the details."
4800 (interactive "*")
4801 (let ((here (point)))
4802 (unwind-protect
4803 (progn
4804 ;; Temporarily insert a non-whitespace char to keep any
4805 ;; preceding whitespace intact.
4806 (insert ?x)
4807 (c-context-line-break))
4808 (goto-char here)
4809 (delete-char 1))))
4812 (cc-provide 'cc-cmds)
4814 ;; Local Variables:
4815 ;; indent-tabs-mode: t
4816 ;; tab-width: 8
4817 ;; End:
4818 ;;; cc-cmds.el ends here