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