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