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