]> code.delx.au - gnu-emacs/blob - lisp/progmodes/cc-cmds.el
Revision: miles@gnu.org--gnu-2005/emacs--unicode--0--patch-86
[gnu-emacs] / lisp / progmodes / cc-cmds.el
1 ;;; cc-cmds.el --- user level commands for CC Mode
2
3 ;; Copyright (C) 1985,1987,1992-2003, 2004, 2005 Free Software Foundation, Inc.
4
5 ;; Authors: 1998- Martin Stjernholm
6 ;; 1992-1999 Barry A. Warsaw
7 ;; 1987 Dave Detlefs and Stewart Clamen
8 ;; 1985 Richard M. Stallman
9 ;; Maintainer: bug-cc-mode@gnu.org
10 ;; Created: 22-Apr-1997 (split from cc-mode.el)
11 ;; Version: See cc-mode.el
12 ;; Keywords: c languages oop
13
14 ;; This file is part of GNU Emacs.
15
16 ;; GNU Emacs is free software; you can redistribute it and/or modify
17 ;; it under the terms of the GNU General Public License as published by
18 ;; the Free Software Foundation; either version 2, or (at your option)
19 ;; any later version.
20
21 ;; GNU Emacs is distributed in the hope that it will be useful,
22 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
23 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
24 ;; GNU General Public License for more details.
25
26 ;; You should have received a copy of the GNU General Public License
27 ;; along with GNU Emacs; see the file COPYING. If not, write to
28 ;; the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
29 ;; Boston, MA 02110-1301, USA.
30
31 ;;; Commentary:
32
33 ;;; Code:
34
35 (eval-when-compile
36 (let ((load-path
37 (if (and (boundp 'byte-compile-dest-file)
38 (stringp byte-compile-dest-file))
39 (cons (file-name-directory byte-compile-dest-file) load-path)
40 load-path)))
41 (load "cc-bytecomp" nil t)))
42
43 (cc-require 'cc-defs)
44 (cc-require 'cc-vars)
45 (cc-require 'cc-engine)
46
47 ;; Silence the compiler.
48 (cc-bytecomp-defvar delete-key-deletes-forward) ; XEmacs 20+
49 (cc-bytecomp-defun delete-forward-p) ; XEmacs 21+
50 (cc-bytecomp-obsolete-fun insert-and-inherit) ; Marked obsolete in XEmacs 19
51 (cc-bytecomp-defvar filladapt-mode) ; c-fill-paragraph contains a kludge
52 ; which looks at this.
53
54 \f
55 (defvar c-fix-backslashes t)
56
57 (defun c-indent-line (&optional syntax quiet ignore-point-pos)
58 "Indent the current line according to the syntactic context,
59 if `c-syntactic-indentation' is non-nil. Optional SYNTAX is the
60 syntactic information for the current line. Be silent about syntactic
61 errors if the optional argument QUIET is non-nil, even if
62 `c-report-syntactic-errors' is non-nil. Normally the position of
63 point is used to decide where the old indentation is on a lines that
64 is otherwise empty \(ignoring any line continuation backslash), but
65 that's not done if IGNORE-POINT-POS is non-nil. Returns the amount of
66 indentation change \(in columns)."
67 ;;
68 ;; This function does not do any hidden buffer changes.
69
70 (let ((line-cont-backslash (save-excursion
71 (end-of-line)
72 (eq (char-before) ?\\)))
73 (c-fix-backslashes c-fix-backslashes)
74 bs-col
75 shift-amt)
76 (when (and (not ignore-point-pos)
77 (save-excursion
78 (beginning-of-line)
79 (looking-at (if line-cont-backslash
80 "\\(\\s *\\)\\\\$"
81 "\\(\\s *\\)$")))
82 (<= (point) (match-end 1)))
83 ;; Delete all whitespace after point if there's only whitespace
84 ;; on the line, so that any code that does back-to-indentation
85 ;; or similar gets the current column in this case. If this
86 ;; removes a line continuation backslash it'll be restored
87 ;; at the end.
88 (unless c-auto-align-backslashes
89 ;; Should try to keep the backslash alignment
90 ;; in this case.
91 (save-excursion
92 (goto-char (match-end 0))
93 (setq bs-col (1- (current-column)))))
94 (delete-region (point) (match-end 0))
95 (setq c-fix-backslashes t))
96 (if c-syntactic-indentation
97 (setq c-parsing-error
98 (or (let ((c-parsing-error nil)
99 (c-syntactic-context
100 (or syntax
101 (and (boundp 'c-syntactic-context)
102 c-syntactic-context))))
103 (c-save-buffer-state (indent)
104 (unless c-syntactic-context
105 (setq c-syntactic-context (c-guess-basic-syntax)))
106 (setq indent (c-get-syntactic-indentation
107 c-syntactic-context))
108 (and (not (c-echo-parsing-error quiet))
109 c-echo-syntactic-information-p
110 (message "syntax: %s, indent: %d"
111 c-syntactic-context indent))
112 (setq shift-amt (- indent (current-indentation))))
113 (c-shift-line-indentation shift-amt)
114 (run-hooks 'c-special-indent-hook)
115 c-parsing-error)
116 c-parsing-error))
117 (let ((indent 0))
118 (save-excursion
119 (while (and (= (forward-line -1) 0)
120 (if (looking-at "\\s *\\\\?$")
121 t
122 (setq indent (current-indentation))
123 nil))))
124 (setq shift-amt (- indent (current-indentation)))
125 (c-shift-line-indentation shift-amt)))
126 (when (and c-fix-backslashes line-cont-backslash)
127 (if bs-col
128 (save-excursion
129 (indent-to bs-col)
130 (insert ?\\))
131 (when c-auto-align-backslashes
132 ;; Realign the line continuation backslash.
133 (c-backslash-region (point) (point) nil t))))
134 shift-amt))
135
136 (defun c-newline-and-indent (&optional newline-arg)
137 "Inserts a newline and indents the new line.
138 This function fixes line continuation backslashes if inside a macro,
139 and takes care to set the indentation before calling
140 `indent-according-to-mode', so that lineup functions like
141 `c-lineup-dont-change' works better."
142 ;;
143 ;; This function does not do any hidden buffer changes.
144
145 ;; TODO: Backslashes before eol in comments and literals aren't
146 ;; kept intact.
147 (let ((c-macro-start (c-query-macro-start))
148 ;; Avoid calling c-backslash-region from c-indent-line if it's
149 ;; called during the newline call, which can happen due to
150 ;; c-electric-continued-statement, for example. We also don't
151 ;; want any backslash alignment from indent-according-to-mode.
152 (c-fix-backslashes nil)
153 has-backslash insert-backslash
154 start col)
155 (save-excursion
156 (beginning-of-line)
157 (setq start (point))
158 (while (and (looking-at "[ \t]*\\\\?$")
159 (= (forward-line -1) 0)))
160 (setq col (current-indentation)))
161 (when c-macro-start
162 (if (and (eolp) (eq (char-before) ?\\))
163 (setq insert-backslash t
164 has-backslash t)
165 (setq has-backslash (eq (char-before (c-point 'eol)) ?\\))))
166 (newline newline-arg)
167 (indent-to col)
168 (when c-macro-start
169 (if insert-backslash
170 (progn
171 ;; The backslash stayed on the previous line. Insert one
172 ;; before calling c-backslash-region, so that
173 ;; bs-col-after-end in it works better. Fixup the
174 ;; backslashes on the newly inserted line.
175 (insert ?\\)
176 (backward-char)
177 (c-backslash-region (point) (point) nil t))
178 ;; The backslash moved to the new line, if there was any. Let
179 ;; c-backslash-region fix a backslash on the previous line,
180 ;; and the one that might be on the new line.
181 ;; c-auto-align-backslashes is intentionally ignored here;
182 ;; maybe the moved backslash should be left alone if it's set,
183 ;; but we fix both lines on the grounds that the old backslash
184 ;; has been moved anyway and is now in a different context.
185 (c-backslash-region start (if has-backslash (point) start) nil t)))
186 (when c-syntactic-indentation
187 ;; Reindent syntactically. The indentation done above is not
188 ;; wasted, since c-indent-line might look at the current
189 ;; indentation.
190 (let ((c-syntactic-context (c-save-buffer-state nil
191 (c-guess-basic-syntax))))
192 ;; We temporarily insert another line break, so that the
193 ;; lineup functions will see the line as empty. That makes
194 ;; e.g. c-lineup-cpp-define more intuitive since it then
195 ;; proceeds to the preceding line in this case.
196 (insert ?\n)
197 (delete-horizontal-space)
198 (setq start (- (point-max) (point)))
199 (unwind-protect
200 (progn
201 (backward-char)
202 (indent-according-to-mode))
203 (goto-char (- (point-max) start))
204 (delete-char -1)))
205 (when has-backslash
206 ;; Must align the backslash again after reindentation. The
207 ;; c-backslash-region call above can't be optimized to ignore
208 ;; this line, since it then won't align correctly with the
209 ;; lines below if the first line in the macro is broken.
210 (c-backslash-region (point) (point) nil t)))))
211
212 (defun c-show-syntactic-information (arg)
213 "Show syntactic information for current line.
214 With universal argument, inserts the analysis as a comment on that line."
215 (interactive "P")
216 (let* ((c-parsing-error nil)
217 (syntax (if (boundp 'c-syntactic-context)
218 ;; Use `c-syntactic-context' in the same way as
219 ;; `c-indent-line', to be consistent.
220 c-syntactic-context
221 (c-save-buffer-state nil
222 (c-guess-basic-syntax)))))
223 (if (not (consp arg))
224 (message "syntactic analysis: %s" syntax)
225 (indent-for-comment)
226 (insert-and-inherit (format "%s" syntax))
227 ))
228 (c-keep-region-active))
229
230 (defun c-syntactic-information-on-region (from to)
231 "Inserts a comment with the syntactic analysis on every line in the region."
232 (interactive "*r")
233 (save-excursion
234 (save-restriction
235 (narrow-to-region from to)
236 (goto-char (point-min))
237 (while (not (eobp))
238 (c-show-syntactic-information '(0))
239 (forward-line)))))
240
241 \f
242 (defun c-toggle-syntactic-indentation (&optional arg)
243 "Toggle syntactic indentation.
244 Optional numeric ARG, if supplied, turns on syntactic indentation when
245 positive, turns it off when negative, and just toggles it when zero or
246 left out.
247
248 When syntactic indentation is turned on (the default), the indentation
249 functions and the electric keys indent according to the syntactic
250 context keys, when applicable.
251
252 When it's turned off, the electric keys does no reindentation, the
253 indentation functions indents every new line to the same level as the
254 previous nonempty line, and \\[c-indent-command] adjusts the
255 indentation in seps specified `c-basic-offset'. The indentation style
256 has no effect in this mode, nor any of the indentation associated
257 variables, e.g. `c-special-indent-hook'.
258
259 This command sets the variable `c-syntactic-indentation'."
260 (interactive "P")
261 (setq c-syntactic-indentation
262 (c-calculate-state arg c-syntactic-indentation))
263 (c-keep-region-active))
264
265 (defun c-toggle-auto-state (&optional arg)
266 "Toggle auto-newline feature.
267 Optional numeric ARG, if supplied, turns on auto-newline when
268 positive, turns it off when negative, and just toggles it when zero or
269 left out.
270
271 When the auto-newline feature is enabled (as evidenced by the `/a' or
272 `/ah' on the modeline after the mode name) newlines are automatically
273 inserted after special characters such as brace, comma, semi-colon,
274 and colon."
275 (interactive "P")
276 (setq c-auto-newline (c-calculate-state arg c-auto-newline))
277 (c-update-modeline)
278 (c-keep-region-active))
279
280 (defun c-toggle-hungry-state (&optional arg)
281 "Toggle hungry-delete-key feature.
282 Optional numeric ARG, if supplied, turns on hungry-delete when
283 positive, turns it off when negative, and just toggles it when zero or
284 left out.
285
286 When the hungry-delete-key feature is enabled (as evidenced by the
287 `/h' or `/ah' on the modeline after the mode name) the delete key
288 gobbles all preceding whitespace in one fell swoop."
289 (interactive "P")
290 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
291 (c-update-modeline)
292 (c-keep-region-active))
293
294 (defun c-toggle-auto-hungry-state (&optional arg)
295 "Toggle auto-newline and hungry-delete-key features.
296 Optional numeric ARG, if supplied, turns on auto-newline and
297 hungry-delete when positive, turns them off when negative, and just
298 toggles them when zero or left out.
299
300 See `c-toggle-auto-state' and `c-toggle-hungry-state' for details."
301 (interactive "P")
302 (setq c-auto-newline (c-calculate-state arg c-auto-newline))
303 (setq c-hungry-delete-key (c-calculate-state arg c-hungry-delete-key))
304 (c-update-modeline)
305 (c-keep-region-active))
306
307 \f
308 ;; Electric keys
309
310 (defun c-electric-backspace (arg)
311 "Delete the preceding character or whitespace.
312 If `c-hungry-delete-key' is non-nil, as evidenced by the \"/h\" or
313 \"/ah\" string on the mode line, then all preceding whitespace is
314 consumed. If however a prefix argument is supplied, or
315 `c-hungry-delete-key' is nil, or point is inside a literal then the
316 function in the variable `c-backspace-function' is called."
317 (interactive "*P")
318 (if (or (not c-hungry-delete-key)
319 arg
320 (c-in-literal))
321 (funcall c-backspace-function (prefix-numeric-value arg))
322 (c-hungry-backspace)))
323
324 (defun c-hungry-backspace ()
325 "Delete the preceding character or all preceding whitespace
326 back to the previous non-whitespace character.
327 See also \\[c-hungry-delete-forward]."
328 (interactive)
329 (let ((here (point)))
330 (c-skip-ws-backward)
331 (if (/= (point) here)
332 (delete-region (point) here)
333 (funcall c-backspace-function 1))))
334
335 (defun c-electric-delete-forward (arg)
336 "Delete the following character or whitespace.
337 If `c-hungry-delete-key' is non-nil, as evidenced by the \"/h\" or
338 \"/ah\" string on the mode line, then all following whitespace is
339 consumed. If however a prefix argument is supplied, or
340 `c-hungry-delete-key' is nil, or point is inside a literal then the
341 function in the variable `c-delete-function' is called."
342 (interactive "*P")
343 (if (or (not c-hungry-delete-key)
344 arg
345 (c-in-literal))
346 (funcall c-delete-function (prefix-numeric-value arg))
347 (c-hungry-delete-forward)))
348
349 (defun c-hungry-delete-forward ()
350 "Delete the following character or all following whitespace
351 up to the next non-whitespace character.
352 See also \\[c-hungry-backspace]."
353 (interactive)
354 (let ((here (point)))
355 (c-skip-ws-forward)
356 (if (/= (point) here)
357 (delete-region (point) here)
358 (funcall c-delete-function 1))))
359
360 ;; This function is only used in XEmacs.
361 (defun c-electric-delete (arg)
362 "Deletes preceding or following character or whitespace.
363 This function either deletes forward as `c-electric-delete-forward' or
364 backward as `c-electric-backspace', depending on the configuration:
365
366 If the function `delete-forward-p' is defined (XEmacs 21) and returns
367 non-nil, it deletes forward. Else, if the variable
368 `delete-key-deletes-forward' is defined (XEmacs 20) and is set to
369 non-nil, it deletes forward. Otherwise it deletes backward.
370
371 Note: This is the way in XEmacs 20 and later to choose the correct
372 action for the [delete] key, whichever key that means. In other
373 flavors this function isn't used, instead it's left to the user to
374 bind [delete] to either \\[c-electric-delete-forward] or \\[c-electric-backspace] as appropriate
375 \(the keymap `function-key-map' is useful for that). Emacs 21 handles
376 that automatically, though."
377 (interactive "*P")
378 (if (or (and (fboundp 'delete-forward-p) ;XEmacs 21
379 (delete-forward-p))
380 (and (boundp 'delete-key-deletes-forward) ;XEmacs 20
381 delete-key-deletes-forward))
382 (c-electric-delete-forward arg)
383 (c-electric-backspace arg)))
384
385 (defun c-electric-pound (arg)
386 "Electric pound (`#') insertion.
387 Inserts a `#' character specially depending on the variable
388 `c-electric-pound-behavior'. If a numeric ARG is supplied, or if
389 point is inside a literal or a macro, nothing special happens."
390 (interactive "*P")
391 (if (or arg
392 (not (memq 'alignleft c-electric-pound-behavior))
393 (save-excursion
394 (skip-chars-backward " \t")
395 (not (bolp)))
396 (save-excursion
397 (and (= (forward-line -1) 0)
398 (progn (end-of-line)
399 (eq (char-before) ?\\))))
400 (c-in-literal))
401 ;; do nothing special
402 (self-insert-command (prefix-numeric-value arg))
403 ;; place the pound character at the left edge
404 (let ((pos (- (point-max) (point)))
405 (bolp (bolp)))
406 (beginning-of-line)
407 (delete-horizontal-space)
408 (insert last-command-char)
409 (and (not bolp)
410 (goto-char (- (point-max) pos)))
411 )))
412
413 (defun c-electric-brace (arg)
414 "Insert a brace.
415
416 If the auto-newline feature is turned on, as evidenced by the \"/a\"
417 or \"/ah\" string on the mode line, newlines are inserted before and
418 after braces based on the value of `c-hanging-braces-alist'.
419
420 Also, the line is re-indented unless a numeric ARG is supplied, the
421 brace is inserted inside a literal, or `c-syntactic-indentation' is
422 nil.
423
424 This function does various newline cleanups based on the value of
425 `c-cleanup-list'."
426 (interactive "*P")
427 (let* ((safepos (c-safe-position (point) (c-parse-state)))
428 (literal (c-in-literal safepos))
429 ;; We want to inhibit blinking the paren since this will be
430 ;; most disruptive. We'll blink it ourselves later on.
431 (old-blink-paren blink-paren-function)
432 blink-paren-function)
433 (cond
434 ((or literal arg)
435 (self-insert-command (prefix-numeric-value arg)))
436 ((not (looking-at "[ \t]*\\\\?$"))
437 (self-insert-command (prefix-numeric-value arg))
438 (if c-syntactic-indentation
439 (indent-according-to-mode)))
440 (t
441 (let* ((syms
442 ;; This is the list of brace syntactic symbols that can
443 ;; hang. If any new ones are added to c-offsets-alist,
444 ;; they should be added here as well.
445 '(class-open class-close defun-open defun-close
446 inline-open inline-close
447 brace-list-open brace-list-close
448 brace-list-intro brace-entry-open
449 block-open block-close
450 substatement-open statement-case-open
451 extern-lang-open extern-lang-close
452 namespace-open namespace-close
453 module-open module-close
454 composition-open composition-close
455 inexpr-class-open inexpr-class-close
456 ;; `statement-cont' is here for the case with a brace
457 ;; list opener inside a statement. C.f. CASE B.2 in
458 ;; `c-guess-continued-construct'.
459 statement-cont))
460 (insertion-point (point))
461 (preserve-p (and (not (bobp))
462 (eq ?\ (char-syntax (char-before)))))
463 ;; shut this up too
464 (c-echo-syntactic-information-p nil)
465 delete-temp-newline syntax newlines)
466 ;; only insert a newline if there is non-whitespace behind us
467 (when (save-excursion
468 (skip-chars-backward " \t")
469 (not (bolp)))
470 (c-newline-and-indent)
471 ;; Set markers around the newline and indention inserted
472 ;; above. We insert the start marker here and not before
473 ;; the call to kludge around a misfeature in expand-abbrev:
474 ;; If the line contains e.g. "else" then expand-abbrev will
475 ;; be called when c-newline-and-indent inserts the newline.
476 ;; That function first removes the abbrev "else" and then
477 ;; inserts the expansion, which is an identical "else" in
478 ;; this case. So the marker that we put after "else" would
479 ;; end up before it.
480 (setq delete-temp-newline
481 (cons (save-excursion
482 (end-of-line 0)
483 (if (eq (char-before) ?\\)
484 ;; Ignore a line continuation.
485 (backward-char))
486 (skip-chars-backward " \t")
487 (copy-marker (point) t))
488 (point-marker))))
489 (unwind-protect
490 (progn
491 (if (eq last-command-char ?{)
492 (setq c-state-cache (cons (point) c-state-cache)))
493 (self-insert-command (prefix-numeric-value arg))
494 (c-save-buffer-state ((c-syntactic-indentation-in-macros t)
495 (c-auto-newline-analysis t))
496 ;; Turn on syntactic macro analysis to help with auto
497 ;; newlines only.
498 (setq syntax (c-guess-basic-syntax)))
499 (setq newlines
500 (and
501 c-auto-newline
502 (or (c-lookup-lists
503 syms
504 ;; Substitute inexpr-class and class-open or
505 ;; class-close with inexpr-class-open or
506 ;; inexpr-class-close.
507 (if (assq 'inexpr-class syntax)
508 (cond ((assq 'class-open syntax)
509 '((inexpr-class-open)))
510 ((assq 'class-close syntax)
511 '((inexpr-class-close)))
512 (t syntax))
513 syntax)
514 c-hanging-braces-alist)
515 '(ignore before after))))
516 ;; Do not try to insert newlines around a special
517 ;; (Pike-style) brace list.
518 (if (and c-special-brace-lists
519 (save-excursion
520 (c-save-buffer-state nil
521 (c-safe (if (= (char-before) ?{)
522 (forward-char -1)
523 (c-forward-sexp -1))
524 (c-looking-at-special-brace-list)))))
525 (setq newlines nil))
526 ;; If syntax is a function symbol, then call it using the
527 ;; defined semantics.
528 (if (and (not (consp (cdr newlines)))
529 (functionp (cdr newlines)))
530 (let ((c-syntactic-context syntax))
531 (setq newlines
532 (funcall (cdr newlines)
533 (car newlines)
534 insertion-point))))
535 ;; does a newline go before the open brace?
536 (when (memq 'before newlines)
537 ;; we leave the newline we've put in there before,
538 ;; but we need to re-indent the line above
539 (when delete-temp-newline
540 (set-marker (car delete-temp-newline) nil)
541 (set-marker (cdr delete-temp-newline) nil)
542 (setq delete-temp-newline nil))
543 (when c-syntactic-indentation
544 (let ((pos (- (point-max) (point)))
545 (here (point)))
546 (forward-line -1)
547 (indent-according-to-mode)
548 (goto-char (- (point-max) pos))
549 ;; if the buffer has changed due to the
550 ;; indentation, we need to recalculate syntax for
551 ;; the current line.
552 (if (/= (point) here)
553 (c-save-buffer-state
554 ((c-syntactic-indentation-in-macros t)
555 (c-auto-newline-analysis t))
556 ;; Turn on syntactic macro analysis to help
557 ;; with auto newlines only.
558 (setq syntax (c-guess-basic-syntax))))))))
559 ;; must remove the newline we just stuck in (if we really did it)
560 (when delete-temp-newline
561 (save-excursion
562 (delete-region (car delete-temp-newline)
563 (cdr delete-temp-newline))
564 (goto-char (car delete-temp-newline))
565 (set-marker (car delete-temp-newline) nil)
566 (set-marker (cdr delete-temp-newline) nil)
567 ;; if there is whitespace before point, then preserve
568 ;; at least one space.
569 (just-one-space)
570 (if (not preserve-p)
571 (delete-char -1)))))
572 (if (not (memq 'before newlines))
573 ;; since we're hanging the brace, we need to recalculate
574 ;; syntax.
575 (c-save-buffer-state ((c-syntactic-indentation-in-macros t)
576 (c-auto-newline-analysis t))
577 ;; Turn on syntactic macro analysis to help with auto
578 ;; newlines only.
579 (setq syntax (c-guess-basic-syntax))))
580 (when c-syntactic-indentation
581 ;; Now adjust the line's indentation. Don't update the state
582 ;; cache since c-guess-basic-syntax isn't called when
583 ;; c-syntactic-context is set.
584 (let* ((c-syntactic-context syntax))
585 (indent-according-to-mode)))
586 ;; Do all appropriate clean ups
587 (let ((here (point))
588 (pos (- (point-max) (point)))
589 mbeg mend tmp)
590 ;; clean up empty defun braces
591 (if (and c-auto-newline
592 (memq 'empty-defun-braces c-cleanup-list)
593 (eq last-command-char ?\})
594 (c-intersect-lists '(defun-close class-close inline-close)
595 syntax)
596 (progn
597 (forward-char -1)
598 (c-skip-ws-backward)
599 (eq (char-before) ?\{))
600 ;; make sure matching open brace isn't in a comment
601 (not (c-in-literal)))
602 (delete-region (point) (1- here)))
603 ;; clean up brace-else-brace and brace-elseif-brace
604 (when (and c-auto-newline
605 (eq last-command-char ?\{))
606 (cond
607 ((and (memq 'brace-else-brace c-cleanup-list)
608 (re-search-backward
609 (concat "}"
610 "\\([ \t\n]\\|\\\\\n\\)*"
611 "else"
612 "\\([ \t\n]\\|\\\\\n\\)*"
613 "{")
614 nil t)
615 (progn
616 (setq mbeg (match-beginning 0)
617 mend (match-end 0))
618 (eq (match-end 0) here)))
619 (delete-region mbeg mend)
620 (insert-and-inherit "} else {"))
621 ((and (memq 'brace-elseif-brace c-cleanup-list)
622 (progn
623 (goto-char (1- here))
624 (setq mend (point))
625 (c-skip-ws-backward)
626 (setq mbeg (point))
627 (eq (char-before) ?\)))
628 (zerop (c-save-buffer-state nil (c-backward-token-2 1 t)))
629 (eq (char-after) ?\()
630 (progn
631 (setq tmp (point))
632 (re-search-backward
633 (concat "}"
634 "\\([ \t\n]\\|\\\\\n\\)*"
635 "else"
636 "\\([ \t\n]\\|\\\\\n\\)+"
637 "if"
638 "\\([ \t\n]\\|\\\\\n\\)*")
639 nil t))
640 (eq (match-end 0) tmp))
641 (delete-region mbeg mend)
642 (goto-char mbeg)
643 (insert ?\ ))))
644 (goto-char (- (point-max) pos))
645 )
646 ;; does a newline go after the brace?
647 (if (memq 'after newlines)
648 (c-newline-and-indent))
649 )))
650 ;; blink the paren
651 (and (eq last-command-char ?\})
652 (not executing-kbd-macro)
653 old-blink-paren
654 (save-excursion
655 (c-save-buffer-state nil
656 (c-backward-syntactic-ws safepos))
657 (funcall old-blink-paren)))))
658
659 (defun c-electric-slash (arg)
660 "Insert a slash character.
661
662 Indent the line as a comment, if:
663
664 1. The slash is second of a `//' line oriented comment introducing
665 token and we are on a comment-only-line, or
666
667 2. The slash is part of a `*/' token that closes a block oriented
668 comment.
669
670 If a numeric ARG is supplied, point is inside a literal, or
671 `c-syntactic-indentation' is nil, indentation is inhibited."
672 (interactive "*P")
673 (let* ((ch (char-before))
674 (literal (c-in-literal))
675 (indentp (and c-syntactic-indentation
676 (not arg)
677 (eq last-command-char ?/)
678 (or (and (eq ch ?/)
679 (not literal))
680 (and (eq ch ?*)
681 literal))
682 ))
683 ;; shut this up
684 (c-echo-syntactic-information-p nil))
685 (self-insert-command (prefix-numeric-value arg))
686 (if indentp
687 (indent-according-to-mode))))
688
689 (defun c-electric-star (arg)
690 "Insert a star character.
691 If the star is the second character of a C style comment introducing
692 construct, and we are on a comment-only-line, indent line as comment.
693 If a numeric ARG is supplied, point is inside a literal, or
694 `c-syntactic-indentation' is nil, indentation is inhibited."
695 (interactive "*P")
696 (self-insert-command (prefix-numeric-value arg))
697 ;; if we are in a literal, or if arg is given do not re-indent the
698 ;; current line, unless this star introduces a comment-only line.
699 (if (and c-syntactic-indentation
700 (not arg)
701 (eq (c-in-literal) 'c)
702 (eq (char-before) ?*)
703 (save-excursion
704 (forward-char -1)
705 (skip-chars-backward "*")
706 (if (eq (char-before) ?/)
707 (forward-char -1))
708 (skip-chars-backward " \t")
709 (bolp)))
710 (let (c-echo-syntactic-information-p) ; shut this up
711 (indent-according-to-mode))
712 ))
713
714 (defun c-electric-semi&comma (arg)
715 "Insert a comma or semicolon.
716 When the auto-newline feature is turned on, as evidenced by the \"/a\"
717 or \"/ah\" string on the mode line, a newline might be inserted. See
718 the variable `c-hanging-semi&comma-criteria' for how newline insertion
719 is determined.
720
721 When a semicolon is inserted, the line is re-indented unless a numeric
722 arg is supplied, point is inside a literal, or
723 `c-syntactic-indentation' is nil.
724
725 Based on the value of `c-cleanup-list', this function cleans up commas
726 following brace lists and semicolons following defuns."
727 (interactive "*P")
728 (let* ((lim (c-most-enclosing-brace (c-parse-state)))
729 (literal (c-in-literal lim))
730 (here (point))
731 ;; shut this up
732 (c-echo-syntactic-information-p nil))
733 (if (or literal arg)
734 (self-insert-command (prefix-numeric-value arg))
735 ;; do some special stuff with the character
736 (self-insert-command (prefix-numeric-value arg))
737 ;; do all cleanups and newline insertions if c-auto-newline is
738 ;; turned on
739 (if (or (not c-auto-newline)
740 (not (looking-at "[ \t]*\\\\?$")))
741 (if c-syntactic-indentation
742 (indent-according-to-mode))
743 ;; clean ups
744 (let ((pos (- (point-max) (point))))
745 (if (and (or (and
746 (eq last-command-char ?,)
747 (memq 'list-close-comma c-cleanup-list))
748 (and
749 (eq last-command-char ?\;)
750 (memq 'defun-close-semi c-cleanup-list)))
751 (progn
752 (forward-char -1)
753 (c-skip-ws-backward)
754 (eq (char-before) ?}))
755 ;; make sure matching open brace isn't in a comment
756 (not (c-in-literal lim)))
757 (delete-region (point) here))
758 (goto-char (- (point-max) pos)))
759 ;; re-indent line
760 (if c-syntactic-indentation
761 (indent-according-to-mode))
762 ;; check to see if a newline should be added
763 (let ((criteria c-hanging-semi&comma-criteria)
764 answer add-newline-p)
765 (while criteria
766 (setq answer (funcall (car criteria)))
767 ;; only nil value means continue checking
768 (if (not answer)
769 (setq criteria (cdr criteria))
770 (setq criteria nil)
771 ;; only 'stop specifically says do not add a newline
772 (setq add-newline-p (not (eq answer 'stop)))
773 ))
774 (if add-newline-p
775 (c-newline-and-indent))
776 )))))
777
778 (defun c-electric-colon (arg)
779 "Insert a colon.
780
781 If the auto-newline feature is turned on, as evidenced by the \"/a\"
782 or \"/ah\" string on the mode line, newlines are inserted before and
783 after colons based on the value of `c-hanging-colons-alist'.
784
785 Also, the line is re-indented unless a numeric ARG is supplied, the
786 colon is inserted inside a literal, or `c-syntactic-indentation' is
787 nil.
788
789 This function cleans up double colon scope operators based on the
790 value of `c-cleanup-list'."
791 (interactive "*P")
792 (let* ((bod (c-point 'bod))
793 (literal (c-in-literal bod))
794 newlines is-scope-op
795 ;; shut this up
796 (c-echo-syntactic-information-p nil))
797 (cond
798 ((or literal arg)
799 (self-insert-command (prefix-numeric-value arg)))
800 ((not (looking-at "[ \t]*\\\\?$"))
801 (self-insert-command (prefix-numeric-value arg))
802 (if c-syntactic-indentation
803 (indent-according-to-mode)))
804 (t
805 ;; insert the colon, then do any specified cleanups
806 (self-insert-command (prefix-numeric-value arg))
807 (let ((pos (- (point-max) (point)))
808 (here (point)))
809 (if (and c-auto-newline
810 (memq 'scope-operator c-cleanup-list)
811 (eq (char-before) ?:)
812 (progn
813 (forward-char -1)
814 (c-skip-ws-backward)
815 (eq (char-before) ?:))
816 (not (c-in-literal))
817 (not (eq (char-after (- (point) 2)) ?:)))
818 (progn
819 (delete-region (point) (1- here))
820 (setq is-scope-op t)))
821 (goto-char (- (point-max) pos)))
822 ;; indent the current line if it's done syntactically.
823 (if c-syntactic-indentation
824 ;; Cannot use the same syntax analysis as we find below,
825 ;; since that's made with c-syntactic-indentation-in-macros
826 ;; always set to t.
827 (indent-according-to-mode))
828 (c-save-buffer-state
829 ((c-syntactic-indentation-in-macros t)
830 (c-auto-newline-analysis t)
831 ;; Turn on syntactic macro analysis to help with auto newlines
832 ;; only.
833 (syntax (c-guess-basic-syntax))
834 (elem syntax))
835 ;; Translate substatement-label to label for this operation.
836 (while elem
837 (if (eq (car (car elem)) 'substatement-label)
838 (setcar (car elem) 'label))
839 (setq elem (cdr elem)))
840 ;; some language elements can only be determined by checking
841 ;; the following line. Lets first look for ones that can be
842 ;; found when looking on the line with the colon
843 (setq newlines
844 (and c-auto-newline
845 (or (c-lookup-lists '(case-label label access-label)
846 syntax c-hanging-colons-alist)
847 (c-lookup-lists '(member-init-intro inher-intro)
848 (progn
849 (insert ?\n)
850 (unwind-protect
851 (c-guess-basic-syntax)
852 (delete-char -1)))
853 c-hanging-colons-alist)))))
854 ;; does a newline go before the colon? Watch out for already
855 ;; non-hung colons. However, we don't unhang them because that
856 ;; would be a cleanup (and anti-social).
857 (if (and (memq 'before newlines)
858 (not is-scope-op)
859 (save-excursion
860 (skip-chars-backward ": \t")
861 (not (bolp))))
862 (let ((pos (- (point-max) (point))))
863 (forward-char -1)
864 (c-newline-and-indent)
865 (goto-char (- (point-max) pos))))
866 ;; does a newline go after the colon?
867 (if (and (memq 'after (cdr-safe newlines))
868 (not is-scope-op))
869 (c-newline-and-indent))
870 ))))
871
872 (defun c-electric-lt-gt (arg)
873 "Insert a less-than, or greater-than character.
874 The line will be re-indented if the character inserted is the second
875 of a C++ style stream operator and the buffer is in C++ mode.
876 Exceptions are when a numeric argument is supplied, point is inside a
877 literal, or `c-syntactic-indentation' is nil, in which case the line
878 will not be re-indented."
879 (interactive "*P")
880 (let ((indentp (and c-syntactic-indentation
881 (not arg)
882 (eq (char-before) last-command-char)
883 (not (c-in-literal))))
884 ;; shut this up
885 (c-echo-syntactic-information-p nil))
886 (self-insert-command (prefix-numeric-value arg))
887 (if indentp
888 (indent-according-to-mode))))
889
890 (defun c-electric-paren (arg)
891 "Insert a parenthesis.
892
893 Some newline cleanups are done if appropriate; see the variable
894 `c-cleanup-list'.
895
896 Also, the line is re-indented unless a numeric ARG is supplied, the
897 parenthesis is inserted inside a literal, or `c-syntactic-indentation'
898 is nil."
899 (interactive "*P")
900 (let ((literal (c-in-literal (c-point 'bod)))
901 ;; shut this up
902 (c-echo-syntactic-information-p nil))
903 (if (or arg literal)
904 (self-insert-command (prefix-numeric-value arg))
905 ;; do some special stuff with the character
906 (let* (;; We want to inhibit blinking the paren since this will
907 ;; be most disruptive. We'll blink it ourselves
908 ;; afterwards.
909 (old-blink-paren blink-paren-function)
910 blink-paren-function
911 (noblink (eq last-input-event ?\()))
912 (self-insert-command (prefix-numeric-value arg))
913 (if c-syntactic-indentation
914 (indent-according-to-mode))
915 (when (looking-at "[ \t]*\\\\?$")
916 (when c-auto-newline
917 ;; Do all appropriate clean ups
918 (let ((here (point))
919 (pos (- (point-max) (point)))
920 mbeg mend)
921 ;; clean up brace-elseif-brace
922 (if (and (memq 'brace-elseif-brace c-cleanup-list)
923 (eq last-command-char ?\()
924 (re-search-backward
925 (concat "}"
926 "\\([ \t\n]\\|\\\\\n\\)*"
927 "else"
928 "\\([ \t\n]\\|\\\\\n\\)+"
929 "if"
930 "\\([ \t\n]\\|\\\\\n\\)*"
931 "(")
932 nil t)
933 (save-excursion
934 (setq mbeg (match-beginning 0)
935 mend (match-end 0))
936 (= mend here))
937 (not (c-in-literal)))
938 (progn
939 (delete-region mbeg mend)
940 (insert-and-inherit "} else if ("))
941 ;; clean up brace-catch-brace
942 (goto-char here)
943 (if (and (memq 'brace-catch-brace c-cleanup-list)
944 (eq last-command-char ?\()
945 (re-search-backward
946 (concat "}"
947 "\\([ \t\n]\\|\\\\\n\\)*"
948 "catch"
949 "\\([ \t\n]\\|\\\\\n\\)*"
950 "(")
951 nil t)
952 (save-excursion
953 (setq mbeg (match-beginning 0)
954 mend (match-end 0))
955 (= mend here))
956 (not (c-in-literal)))
957 (progn
958 (delete-region mbeg mend)
959 (insert-and-inherit "} catch ("))))
960 (goto-char (- (point-max) pos))
961 )))
962 (let (beg (end (1- (point))))
963 (cond ((and (memq 'space-before-funcall c-cleanup-list)
964 (eq last-command-char ?\()
965 (save-excursion
966 (backward-char)
967 (skip-chars-backward " \t")
968 (setq beg (point))
969 (c-on-identifier)))
970 (save-excursion
971 (delete-region beg end)
972 (goto-char beg)
973 (insert ?\ )))
974 ((and (memq 'compact-empty-funcall c-cleanup-list)
975 (eq last-command-char ?\))
976 (save-excursion
977 (c-safe (backward-char 2))
978 (when (looking-at "()")
979 (setq end (point))
980 (skip-chars-backward " \t")
981 (setq beg (point))
982 (c-on-identifier))))
983 (delete-region beg end))))
984 (and (not executing-kbd-macro)
985 old-blink-paren
986 (not noblink)
987 (funcall old-blink-paren))))))
988
989 (defun c-electric-continued-statement ()
990 "Reindent the current line if appropriate.
991
992 This function is used to reindent the line after a keyword which
993 continues an earlier statement is typed, e.g. an \"else\" or the
994 \"while\" in a do-while block.
995
996 The line is reindented if there is nothing but whitespace before the
997 keyword on the line, the keyword is not inserted inside a literal, and
998 `c-syntactic-indentation' is non-nil."
999 (let (;; shut this up
1000 (c-echo-syntactic-information-p nil))
1001 (when (and c-syntactic-indentation
1002 (not (eq last-command-char ?_))
1003 (= (save-excursion
1004 (skip-syntax-backward "w")
1005 (point))
1006 (c-point 'boi))
1007 (not (c-in-literal (c-point 'bod))))
1008 ;; Have to temporarily insert a space so that
1009 ;; c-guess-basic-syntax recognizes the keyword. Follow the
1010 ;; space with a nonspace to avoid messing up any whitespace
1011 ;; sensitive meddling that might be done, e.g. by
1012 ;; `c-backslash-region'.
1013 (insert-and-inherit " x")
1014 (unwind-protect
1015 (indent-according-to-mode)
1016 (delete-char -2)))))
1017
1018 \f
1019 ;; better movement routines for ThisStyleOfVariablesCommonInCPlusPlus
1020 ;; originally contributed by Terry_Glanfield.Southern@rxuk.xerox.com
1021 (defun c-forward-into-nomenclature (&optional arg)
1022 "Move forward to end of a nomenclature section or word.
1023 With arg, do it arg times."
1024 (interactive "p")
1025 (let ((case-fold-search nil))
1026 (if (> arg 0)
1027 (re-search-forward
1028 (cc-eval-when-compile
1029 (concat "\\W*\\([" c-upper "]*[" c-lower c-digit "]*\\)"))
1030 (point-max) t arg)
1031 (while (and (< arg 0)
1032 (re-search-backward
1033 (cc-eval-when-compile
1034 (concat
1035 "\\(\\(\\W\\|[" c-lower c-digit "]\\)[" c-upper "]+"
1036 "\\|\\W\\w+\\)"))
1037 (point-min) 0))
1038 (forward-char 1)
1039 (setq arg (1+ arg)))))
1040 (c-keep-region-active))
1041
1042 (defun c-backward-into-nomenclature (&optional arg)
1043 "Move backward to beginning of a nomenclature section or word.
1044 With optional ARG, move that many times. If ARG is negative, move
1045 forward."
1046 (interactive "p")
1047 (c-forward-into-nomenclature (- arg))
1048 (c-keep-region-active))
1049
1050 (defun c-scope-operator ()
1051 "Insert a double colon scope operator at point.
1052 No indentation or other \"electric\" behavior is performed."
1053 (interactive "*")
1054 (insert-and-inherit "::"))
1055
1056 (defun c-beginning-of-defun (&optional arg)
1057 "Move backward to the beginning of a defun.
1058 Every top level declaration that contains a brace paren block is
1059 considered to be a defun.
1060
1061 With a positive argument, move backward that many defuns. A negative
1062 argument -N means move forward to the Nth following beginning. Return
1063 t unless search stops due to beginning or end of buffer.
1064
1065 Unlike the built-in `beginning-of-defun' this tries to be smarter
1066 about finding the char with open-parenthesis syntax that starts the
1067 defun."
1068
1069 (interactive "p")
1070 (or arg (setq arg 1))
1071
1072 (if (< arg 0)
1073 (when (c-end-of-defun (- arg))
1074 (c-save-buffer-state nil (c-forward-syntactic-ws))
1075 t)
1076
1077 (c-save-buffer-state (paren-state lim pos)
1078 (catch 'exit
1079 (while (> arg 0)
1080 ;; Note: Partial code duplication in `c-end-of-defun' and
1081 ;; `c-declaration-limits'.
1082
1083 (setq paren-state (c-parse-state))
1084 (unless (c-safe
1085 (goto-char (c-least-enclosing-brace paren-state))
1086 ;; If we moved to the outermost enclosing paren
1087 ;; then we can use c-safe-position to set the
1088 ;; limit. Can't do that otherwise since the
1089 ;; earlier paren pair on paren-state might very
1090 ;; well be part of the declaration we should go
1091 ;; to.
1092 (setq lim (c-safe-position (point) paren-state))
1093 t)
1094 ;; At top level. Make sure we aren't inside a literal.
1095 (setq pos (c-literal-limits
1096 (c-safe-position (point) paren-state)))
1097 (if pos (goto-char (car pos))))
1098
1099 (while (let ((start (point)))
1100 (c-beginning-of-decl-1 lim)
1101 (if (= (point) start)
1102 ;; Didn't move. Might be due to bob or unbalanced
1103 ;; parens. Try to continue if it's the latter.
1104 (unless (c-safe (goto-char
1105 (c-down-list-backward (point))))
1106 ;; Didn't work, so it's bob then.
1107 (goto-char (point-min))
1108 (throw 'exit nil)))
1109
1110 (save-excursion
1111 ;; Check if the declaration contains a brace
1112 ;; block. If not, we try another one.
1113 (setq pos (point))
1114 (not (and (c-syntactic-re-search-forward "[;{]" nil t t)
1115 (or (eq (char-before) ?{)
1116 (and c-recognize-knr-p
1117 ;; Might have stopped on the
1118 ;; ';' in a K&R argdecl. In
1119 ;; that case the declaration
1120 ;; should contain a block.
1121 (c-in-knr-argdecl pos)))))))
1122 (setq lim nil))
1123
1124 ;; Check if `c-beginning-of-decl-1' put us after the block
1125 ;; in a declaration that doesn't end there. We're searching
1126 ;; back and forth over the block here, which can be
1127 ;; expensive.
1128 (setq pos (point))
1129 (if (and c-opt-block-decls-with-vars-key
1130 (progn
1131 (c-backward-syntactic-ws)
1132 (eq (char-before) ?}))
1133 (eq (car (c-beginning-of-decl-1))
1134 'previous)
1135 (save-excursion
1136 (c-end-of-decl-1)
1137 (> (point) pos)))
1138 nil
1139 (goto-char pos))
1140
1141 (setq pos (point))
1142 ;; Try to be line oriented; position point at the closest
1143 ;; preceding boi that isn't inside a comment, but if we hit
1144 ;; the previous declaration then we use the current point
1145 ;; instead.
1146 (while (and (/= (point) (c-point 'boi))
1147 (c-backward-single-comment)))
1148 (if (/= (point) (c-point 'boi))
1149 (goto-char pos))
1150
1151 (setq arg (1- arg)))))
1152 (c-keep-region-active)
1153 (= arg 0)))
1154
1155 (defun c-end-of-defun (&optional arg)
1156 "Move forward to the end of a top level declaration.
1157 With argument, do it that many times. Negative argument -N means move
1158 back to Nth preceding end. Returns t unless search stops due to
1159 beginning or end of buffer.
1160
1161 An end of a defun occurs right after the close-parenthesis that matches
1162 the open-parenthesis that starts a defun; see `beginning-of-defun'."
1163
1164 (interactive "p")
1165 (or arg (setq arg 1))
1166
1167 (if (< arg 0)
1168 (when (c-beginning-of-defun (- arg))
1169 (c-save-buffer-state nil (c-backward-syntactic-ws))
1170 t)
1171
1172 (c-save-buffer-state (paren-state lim pos)
1173 (catch 'exit
1174 (while (> arg 0)
1175 ;; Note: Partial code duplication in `c-beginning-of-defun'
1176 ;; and `c-declaration-limits'.
1177
1178 (setq paren-state (c-parse-state))
1179 (unless (c-safe
1180 (goto-char (c-least-enclosing-brace paren-state))
1181 ;; If we moved to the outermost enclosing paren
1182 ;; then we can use c-safe-position to set the
1183 ;; limit. Can't do that otherwise since the
1184 ;; earlier paren pair on paren-state might very
1185 ;; well be part of the declaration we should go
1186 ;; to.
1187 (setq lim (c-safe-position (point) paren-state))
1188 t)
1189 ;; At top level. Make sure we aren't inside a literal.
1190 (setq pos (car-safe (c-literal-limits
1191 (c-safe-position (point) paren-state))))
1192 (if pos (goto-char pos)))
1193
1194 ;; Have to move to the start first so that `c-end-of-decl-1'
1195 ;; has the correct start position.
1196 (setq pos (point))
1197 (when (memq (car (c-beginning-of-decl-1 lim))
1198 '(previous macro))
1199 ;; We moved back over the previous defun or a macro. Move
1200 ;; to the next token; it's the start of the next
1201 ;; declaration. We can also be directly after the block
1202 ;; in a `c-opt-block-decls-with-vars-key' declaration, but
1203 ;; then we won't move significantly far here.
1204 (goto-char pos)
1205 (c-forward-token-2 0))
1206
1207 (while (let ((start (point)))
1208 (c-end-of-decl-1)
1209 (if (= (point) start)
1210 ;; Didn't move. Might be due to eob or unbalanced
1211 ;; parens. Try to continue if it's the latter.
1212 (if (c-safe (goto-char (c-up-list-forward (point))))
1213 t
1214 ;; Didn't work, so it's eob then.
1215 (goto-char (point-max))
1216 (throw 'exit nil))
1217
1218 (save-excursion
1219 ;; Check if the declaration contains a brace
1220 ;; block. If not, we try another one.
1221 (setq pos (point))
1222 (goto-char start)
1223 (not (c-syntactic-re-search-forward "{" pos t t))))))
1224
1225 (setq pos (point))
1226 ;; Try to be line oriented; position point after the next
1227 ;; newline that isn't inside a comment, but if we hit the
1228 ;; next declaration then we use the current point instead.
1229 (while (and (not (bolp))
1230 (not (looking-at "\\s *$"))
1231 (c-forward-single-comment)))
1232 (cond ((bolp))
1233 ((looking-at "\\s *$")
1234 (forward-line 1))
1235 (t
1236 (goto-char pos)))
1237
1238 (setq arg (1- arg)))))
1239 (c-keep-region-active)
1240 (= arg 0)))
1241
1242 (defun c-declaration-limits (near)
1243 ;; Return a cons of the beginning and end positions of the current
1244 ;; top level declaration or macro. If point is not inside any then
1245 ;; nil is returned, unless NEAR is non-nil in which case the closest
1246 ;; following one is chosen instead (if there is any). The end
1247 ;; position is at the next line, providing there is one before the
1248 ;; declaration.
1249 (save-excursion
1250
1251 ;; Note: Some code duplication in `c-beginning-of-defun' and
1252 ;; `c-end-of-defun'.
1253 (catch 'exit
1254 (let ((start (point))
1255 (paren-state (c-parse-state))
1256 lim pos end-pos)
1257 (unless (c-safe
1258 (goto-char (c-least-enclosing-brace paren-state))
1259 ;; If we moved to the outermost enclosing paren then we
1260 ;; can use c-safe-position to set the limit. Can't do
1261 ;; that otherwise since the earlier paren pair on
1262 ;; paren-state might very well be part of the
1263 ;; declaration we should go to.
1264 (setq lim (c-safe-position (point) paren-state))
1265 t)
1266 ;; At top level. Make sure we aren't inside a literal.
1267 (setq pos (c-literal-limits
1268 (c-safe-position (point) paren-state)))
1269 (if pos (goto-char (car pos))))
1270
1271 (when (c-beginning-of-macro)
1272 (throw 'exit
1273 (cons (point)
1274 (save-excursion
1275 (c-end-of-macro)
1276 (forward-line 1)
1277 (point)))))
1278
1279 (setq pos (point))
1280 (when (or (eq (car (c-beginning-of-decl-1 lim)) 'previous)
1281 (= pos (point)))
1282 ;; We moved back over the previous defun. Skip to the next
1283 ;; one. Not using c-forward-syntactic-ws here since we
1284 ;; should not skip a macro. We can also be directly after
1285 ;; the block in a `c-opt-block-decls-with-vars-key'
1286 ;; declaration, but then we won't move significantly far
1287 ;; here.
1288 (goto-char pos)
1289 (c-forward-comments)
1290
1291 (when (and near (c-beginning-of-macro))
1292 (throw 'exit
1293 (cons (point)
1294 (save-excursion
1295 (c-end-of-macro)
1296 (forward-line 1)
1297 (point))))))
1298
1299 (if (eobp) (throw 'exit nil))
1300
1301 ;; Check if `c-beginning-of-decl-1' put us after the block in a
1302 ;; declaration that doesn't end there. We're searching back and
1303 ;; forth over the block here, which can be expensive.
1304 (setq pos (point))
1305 (if (and c-opt-block-decls-with-vars-key
1306 (progn
1307 (c-backward-syntactic-ws)
1308 (eq (char-before) ?}))
1309 (eq (car (c-beginning-of-decl-1))
1310 'previous)
1311 (save-excursion
1312 (c-end-of-decl-1)
1313 (and (> (point) pos)
1314 (setq end-pos (point)))))
1315 nil
1316 (goto-char pos))
1317
1318 (if (and (not near) (> (point) start))
1319 nil
1320
1321 ;; Try to be line oriented; position the limits at the
1322 ;; closest preceding boi, and after the next newline, that
1323 ;; isn't inside a comment, but if we hit a neighboring
1324 ;; declaration then we instead use the exact declaration
1325 ;; limit in that direction.
1326 (cons (progn
1327 (setq pos (point))
1328 (while (and (/= (point) (c-point 'boi))
1329 (c-backward-single-comment)))
1330 (if (/= (point) (c-point 'boi))
1331 pos
1332 (point)))
1333 (progn
1334 (if end-pos
1335 (goto-char end-pos)
1336 (c-end-of-decl-1))
1337 (setq pos (point))
1338 (while (and (not (bolp))
1339 (not (looking-at "\\s *$"))
1340 (c-forward-single-comment)))
1341 (cond ((bolp)
1342 (point))
1343 ((looking-at "\\s *$")
1344 (forward-line 1)
1345 (point))
1346 (t
1347 pos)))))
1348 ))))
1349
1350 (defun c-mark-function ()
1351 "Put mark at end of the current top-level declaration or macro, point at beginning.
1352 If point is not inside any then the closest following one is chosen.
1353
1354 As opposed to \\[c-beginning-of-defun] and \\[c-end-of-defun], this
1355 function does not require the declaration to contain a brace block."
1356 (interactive)
1357
1358 (let (decl-limits)
1359 (c-save-buffer-state nil
1360 ;; We try to be line oriented, unless there are several
1361 ;; declarations on the same line.
1362 (if (looking-at c-syntactic-eol)
1363 (c-backward-token-2 1 nil (c-point 'bol)))
1364 (setq decl-limits (c-declaration-limits t)))
1365
1366 (if (not decl-limits)
1367 (error "Cannot find any declaration")
1368 (goto-char (car decl-limits))
1369 (push-mark (cdr decl-limits) nil t))))
1370
1371 \f
1372 (defun c-beginning-of-statement (&optional count lim sentence-flag)
1373 "Go to the beginning of the innermost C statement.
1374 With prefix arg, go back N - 1 statements. If already at the
1375 beginning of a statement then go to the beginning of the closest
1376 preceding one, moving into nested blocks if necessary (use
1377 \\[backward-sexp] to skip over a block). If within or next to a
1378 comment or multiline string, move by sentences instead of statements.
1379
1380 When called from a program, this function takes 3 optional args: the
1381 repetition count, a buffer position limit which is the farthest back
1382 to search for the syntactic context, and a flag saying whether to do
1383 sentence motion in or near comments and multiline strings.
1384
1385 Note that `c-beginning-of-statement-1' is usually better to use from
1386 programs. It has much more well defined semantics than this one,
1387 which is intended for interactive use and might therefore change to be
1388 more \"DWIM:ey\"."
1389 (interactive (list (prefix-numeric-value current-prefix-arg)
1390 nil t))
1391 (c-save-buffer-state
1392 ((count (or count 1))
1393 here
1394 (range (c-collect-line-comments (c-literal-limits lim))))
1395 (while (and (/= count 0)
1396 (or (not lim) (> (point) lim)))
1397 (setq here (point))
1398 (if (and (not range) sentence-flag)
1399 (save-excursion
1400 ;; Find the comment next to point if we're not in one.
1401 (if (> count 0)
1402 (if (c-backward-single-comment)
1403 (setq range (cons (point)
1404 (progn (c-forward-single-comment)
1405 (point))))
1406 (c-skip-ws-backward)
1407 (setq range (point))
1408 (setq range
1409 (if (eq (char-before) ?\")
1410 (c-safe (c-backward-sexp 1)
1411 (cons (point) range)))))
1412 (c-skip-ws-forward)
1413 (if (eq (char-after) ?\")
1414 (setq range (cons (point)
1415 (progn
1416 (c-forward-sexp 1)
1417 (point))))
1418 (setq range (point))
1419 (setq range (if (c-forward-single-comment)
1420 (cons range (point))
1421 nil))))
1422 (setq range (c-collect-line-comments range))))
1423 (if (and (< count 0) (= here (point-max)))
1424 ;; Special case because eob might be in a literal.
1425 (setq range nil))
1426 (if range
1427 (if (and sentence-flag
1428 (or (/= (char-syntax (char-after (car range))) ?\")
1429 ;; Only visit a string if it spans more than one line.
1430 (save-excursion
1431 (goto-char (car range))
1432 (skip-chars-forward "^\n" (cdr range))
1433 (< (point) (cdr range)))))
1434 (let* ((lit-type (c-literal-type range))
1435 (line-prefix (concat "[ \t]*\\("
1436 c-current-comment-prefix
1437 "\\)[ \t]*"))
1438 (beg (if (eq lit-type 'string)
1439 (1+ (car range))
1440 (save-excursion
1441 (goto-char (car range))
1442 (max (progn
1443 (looking-at comment-start-skip)
1444 (match-end 0))
1445 (progn
1446 (looking-at line-prefix)
1447 (match-end 0))))))
1448 (end (- (cdr range) (if (eq lit-type 'c) 2 1)))
1449 (beg-of-para (if (eq lit-type 'string)
1450 (lambda ())
1451 (lambda ()
1452 (beginning-of-line)
1453 (if (looking-at line-prefix)
1454 (goto-char (match-end 0)))))))
1455 (save-restriction
1456 ;; Move by sentence, but not past the limit of the
1457 ;; literal, narrowed to the appropriate
1458 ;; paragraph(s).
1459 (narrow-to-region (save-excursion
1460 (let ((pos (min here end)))
1461 (goto-char pos)
1462 (forward-paragraph -1)
1463 (if (looking-at paragraph-separate)
1464 (forward-line))
1465 (when (> (point) beg)
1466 (funcall beg-of-para)
1467 (when (>= (point) pos)
1468 (forward-paragraph -2)
1469 (funcall beg-of-para)))
1470 (max (point) beg)))
1471 end)
1472 (c-safe (forward-sentence (if (< count 0) 1 -1)))
1473 (if (and (memq lit-type '(c c++))
1474 ;; Check if we stopped due to a comment
1475 ;; prefix and not a sentence end.
1476 (/= (point) (point-min))
1477 (/= (point) (point-max))
1478 (save-excursion
1479 (beginning-of-line)
1480 (looking-at line-prefix))
1481 (>= (point) (match-beginning 0))
1482 (/= (match-beginning 1) (match-end 1))
1483 (or (< (point) (match-end 0))
1484 (and
1485 (= (point) (match-end 0))
1486 ;; The comment prefix may contain
1487 ;; characters that is regarded as end
1488 ;; of sentence.
1489 (or (eolp)
1490 (and
1491 (save-excursion
1492 (forward-paragraph -1)
1493 (< (point) (match-beginning 0)))
1494 (save-excursion
1495 (beginning-of-line)
1496 (or (not (re-search-backward
1497 (sentence-end)
1498 (c-point 'bopl)
1499 t))
1500 (< (match-end 0)
1501 (c-point 'eol)))))))))
1502 (setq count (+ count (if (< count 0) -1 1)))
1503 (if (< count 0)
1504 (progn
1505 ;; In block comments, if there's only
1506 ;; horizontal ws between the text and the
1507 ;; comment ender, stop before it. Stop after
1508 ;; the ender if there's either nothing or
1509 ;; newlines between.
1510 (when (and (eq lit-type 'c)
1511 (eq (point) (point-max)))
1512 (widen)
1513 (when (or (= (skip-chars-backward " \t") 0)
1514 (eq (point) (point-max))
1515 (bolp))
1516 (goto-char (cdr range)))))
1517 (when (and (eq (point) (point-min))
1518 (looking-at "[ \t]*\\\\?$"))
1519 ;; Stop before instead of after the comment
1520 ;; starter if nothing follows it.
1521 (widen)
1522 (goto-char (car range))
1523 (if (and (eq lit-type 'string) (/= (point) here))
1524 (setq count (1+ count)
1525 range nil))))))
1526 ;; See if we should escape the literal.
1527 (if (> count 0)
1528 (if (< (point) here)
1529 (setq count (1- count))
1530 (goto-char (car range))
1531 (setq range nil))
1532 (if (> (point) here)
1533 (setq count (1+ count))
1534 (goto-char (cdr range))
1535 (setq range nil))))
1536 (goto-char (if (> count 0) (car range) (cdr range)))
1537 (setq range nil))
1538 (goto-char here)
1539 (if (> count 0)
1540 (condition-case nil
1541 ;; Stop before `{' and after `;', `{', `}' and `};'
1542 ;; when not followed by `}' or `)', but on the other
1543 ;; side of the syntactic ws. Move by sexps and move
1544 ;; into parens. Also stop before `#' when it's at boi
1545 ;; on a line.
1546 (let ((literal-pos (not sentence-flag))
1547 last last-below-line)
1548 (catch 'done
1549 (while t
1550 (setq last (point))
1551 (when (and (or (eq (char-after) ?\{)
1552 (and (eq (char-after) ?#)
1553 (eq (point) (c-point 'boi)))
1554 )
1555 (/= here last))
1556 (unless (and c-special-brace-lists
1557 (eq (char-after) ?{)
1558 (c-looking-at-special-brace-list))
1559 (if (and (eq (char-after) ?#)
1560 (numberp last-below-line)
1561 (not (eq last-below-line here)))
1562 (goto-char last-below-line))
1563 (throw 'done t)))
1564 ;; Don't know why I added the following, but it
1565 ;; doesn't work when point is preceded by a line
1566 ;; style comment. /mast
1567 ;;(c-skip-ws-backward)
1568 (if literal-pos
1569 (c-backward-comments)
1570 (when (c-backward-single-comment)
1571 ;; Record position of first comment.
1572 (save-excursion
1573 (c-forward-single-comment)
1574 (setq literal-pos (point)))
1575 (c-backward-comments)))
1576 (unless last-below-line
1577 (if (save-excursion
1578 (re-search-forward "\\(^\\|[^\\]\\)$" last t))
1579 (setq last-below-line last)))
1580 (cond ((bobp) ; Must handle bob specially.
1581 (if (= here last)
1582 (throw 'done t)
1583 (goto-char last)
1584 (throw 'done t)))
1585 ((progn (backward-char)
1586 (looking-at "[;{}]"))
1587 (if (and c-special-brace-lists
1588 (eq (char-after) ?{)
1589 (c-looking-at-special-brace-list))
1590 (skip-syntax-backward "w_") ; Speedup only.
1591 (if (or (= here last)
1592 (memq (char-after last) '(?\) ?})))
1593 (if (and (eq (char-before) ?})
1594 (eq (char-after) ?\;))
1595 (backward-char))
1596 (goto-char last)
1597 (throw 'done t))))
1598 ((= (char-syntax (char-after)) ?\")
1599 (let ((end (point)))
1600 (forward-char)
1601 (c-backward-sexp)
1602 (save-excursion
1603 (skip-chars-forward "^\n" end)
1604 (when (< (point) end)
1605 ;; Break at multiline string.
1606 (setq literal-pos (1+ end))
1607 (throw 'done t)))))
1608 (t (skip-syntax-backward "w_")) ; Speedup only.
1609 )))
1610 (if (and (numberp literal-pos)
1611 (< (point) literal-pos))
1612 ;; We jumped over a comment or string that
1613 ;; should be investigated.
1614 (goto-char literal-pos)
1615 (setq count (1- count))))
1616 (error
1617 (goto-char (point-min))
1618 (setq count 0)))
1619 (condition-case nil
1620 ;; Stop before `{', `}', and `#' when it's at boi on a
1621 ;; line, but on the other side of the syntactic ws, and
1622 ;; after `;', `}' and `};'. Only stop before `{' if at
1623 ;; top level or inside braces, though. Move by sexps
1624 ;; and move into parens. Also stop at eol of lines
1625 ;; with `#' at the boi.
1626 (let ((literal-pos (not sentence-flag))
1627 last)
1628 (catch 'done
1629 (while t
1630 (setq last (point))
1631 (if literal-pos
1632 (c-forward-comments)
1633 (if (progn
1634 (c-skip-ws-forward)
1635 ;; Record position of first comment.
1636 (setq literal-pos (point))
1637 (c-forward-single-comment))
1638 (c-forward-comments)
1639 (setq literal-pos nil)))
1640 (cond ((and (eq (char-after) ?{)
1641 (not (and c-special-brace-lists
1642 (c-looking-at-special-brace-list)))
1643 (/= here last)
1644 (save-excursion
1645 (or (not (c-safe (up-list -1) t))
1646 (= (char-after) ?{))))
1647 (goto-char last)
1648 (throw 'done t))
1649 ((and c-special-brace-lists
1650 (eq (char-after) ?})
1651 (save-excursion
1652 (and (c-safe (up-list -1) t)
1653 (c-looking-at-special-brace-list))))
1654 (forward-char 1)
1655 (skip-syntax-forward "w_")) ; Speedup only.
1656 ((and (eq (char-after) ?})
1657 (/= here last))
1658 (goto-char last)
1659 (throw 'done t))
1660 ; ((and (eq (char-after) ?#)
1661 ; (= (point) (c-point 'boi)))
1662 ; (if (= here last)
1663 ; (or (re-search-forward "\\(^\\|[^\\]\\)$" nil t)
1664 ; (goto-char (point-max)))
1665 ; (goto-char last))
1666 ; (throw 'done t))
1667 ((looking-at ";\\|};?")
1668 (goto-char (match-end 0))
1669 (throw 'done t))
1670 ((= (char-syntax (char-after)) ?\")
1671 (let ((beg (point)))
1672 (c-forward-sexp)
1673 (save-excursion
1674 (skip-chars-backward "^\n" beg)
1675 (when (> (point) beg)
1676 ;; Break at multiline string.
1677 (setq literal-pos beg)
1678 (throw 'done t)))))
1679 (t
1680 (forward-char 1)
1681 (skip-syntax-forward "w_")) ; Speedup only.
1682 )))
1683 (if (and (numberp literal-pos)
1684 (> (point) literal-pos))
1685 ;; We jumped over a comment that should be investigated.
1686 (goto-char literal-pos)
1687 (setq count (1+ count))))
1688 (error
1689 (goto-char (point-max))
1690 (setq count 0)))
1691 ))
1692 ;; If we haven't moved we're near a buffer limit.
1693 (when (and (not (zerop count)) (= (point) here))
1694 (goto-char (if (> count 0) (point-min) (point-max)))
1695 (setq count 0))))
1696 (c-keep-region-active))
1697
1698 (defun c-end-of-statement (&optional count lim sentence-flag)
1699 "Go to the end of the innermost C statement.
1700 With prefix arg, go forward N - 1 statements. Move forward to the end
1701 of the next statement if already at end, and move into nested blocks
1702 \(use \\[forward-sexp] to skip over a block). If within or next to a
1703 comment or multiline string, move by sentences instead of statements.
1704
1705 When called from a program, this function takes 3 optional args: the
1706 repetition count, a buffer position limit which is the farthest back
1707 to search for the syntactic context, and a flag saying whether to do
1708 sentence motion in or near comments and multiline strings."
1709 (interactive (list (prefix-numeric-value current-prefix-arg)
1710 nil t))
1711 (c-beginning-of-statement (- (or count 1)) lim sentence-flag)
1712 (c-keep-region-active))
1713
1714 \f
1715 ;; set up electric character functions to work with pending-del,
1716 ;; (a.k.a. delsel) mode. All symbols get the t value except
1717 ;; the functions which delete, which gets 'supersede.
1718 (mapcar
1719 (function
1720 (lambda (sym)
1721 (put sym 'delete-selection t) ; for delsel (Emacs)
1722 (put sym 'pending-delete t))) ; for pending-del (XEmacs)
1723 '(c-electric-pound
1724 c-electric-brace
1725 c-electric-slash
1726 c-electric-star
1727 c-electric-semi&comma
1728 c-electric-lt-gt
1729 c-electric-colon
1730 c-electric-paren))
1731 (put 'c-electric-delete 'delete-selection 'supersede) ; delsel
1732 (put 'c-electric-delete 'pending-delete 'supersede) ; pending-del
1733 (put 'c-electric-backspace 'delete-selection 'supersede) ; delsel
1734 (put 'c-electric-backspace 'pending-delete 'supersede) ; pending-del
1735 (put 'c-electric-delete-forward 'delete-selection 'supersede) ; delsel
1736 (put 'c-electric-delete-forward 'pending-delete 'supersede) ; pending-del
1737
1738 \f
1739 (defun c-calc-comment-indent (entry)
1740 (if (symbolp entry)
1741 (setq entry (or (assq entry c-indent-comment-alist)
1742 (assq 'other c-indent-comment-alist)
1743 '(default . (column . nil)))))
1744 (let ((action (car (cdr entry)))
1745 (value (cdr (cdr entry)))
1746 (col (current-column)))
1747 (cond ((eq action 'space)
1748 (+ col value))
1749 ((eq action 'column)
1750 (unless value (setq value comment-column))
1751 (if (bolp)
1752 ;; Do not pad with one space if we're at bol.
1753 value
1754 (max (1+ col) value)))
1755 ((eq action 'align)
1756 (or (save-excursion
1757 (beginning-of-line)
1758 (unless (bobp)
1759 (backward-char)
1760 (let ((lim (c-literal-limits (c-point 'bol) t)))
1761 (when (consp lim)
1762 (goto-char (car lim))
1763 (when (looking-at "/[/*]")
1764 ;; Found comment to align with.
1765 (if (bolp)
1766 ;; Do not pad with one space if we're at bol.
1767 0
1768 (max (1+ col) (current-column))))))))
1769 ;; Recurse to handle value as a new spec.
1770 (c-calc-comment-indent (cdr entry)))))))
1771
1772 (defun c-comment-indent ()
1773 "Used by `indent-for-comment' to create and indent comments.
1774 See `c-indent-comment-alist' for a description."
1775 (save-excursion
1776 (end-of-line)
1777 (c-save-buffer-state
1778 ((eot (let ((lim (c-literal-limits (c-point 'bol) t)))
1779 (or (when (consp lim)
1780 (goto-char (car lim))
1781 (when (looking-at "/[/*]")
1782 (skip-chars-backward " \t")
1783 (point)))
1784 (progn
1785 (skip-chars-backward " \t")
1786 (point)))))
1787 (line-type
1788 (cond ((looking-at "^/[/*]")
1789 'anchored-comment)
1790 ((progn (beginning-of-line)
1791 (eq (point) eot))
1792 'empty-line)
1793 ((progn (back-to-indentation)
1794 (and (eq (char-after) ?})
1795 (eq (point) (1- eot))))
1796 'end-block)
1797 ((and (looking-at "#[ \t]*\\(endif\\|else\\)")
1798 (eq (match-end 0) eot))
1799 'cpp-end-block)
1800 (t
1801 'other))))
1802 (if (and (memq line-type '(anchored-comment empty-line))
1803 c-indent-comments-syntactically-p)
1804 (let ((c-syntactic-context (c-guess-basic-syntax)))
1805 ;; BOGOSITY ALERT: if we're looking at the eol, its
1806 ;; because indent-for-comment hasn't put the comment-start
1807 ;; in the buffer yet. this will screw up the syntactic
1808 ;; analysis so we kludge in the necessary info. Another
1809 ;; kludge is that if we're at the bol, then we really want
1810 ;; to ignore any anchoring as specified by
1811 ;; c-comment-only-line-offset since it doesn't apply here.
1812 (if (eolp)
1813 (c-add-syntax 'comment-intro))
1814 (let ((c-comment-only-line-offset
1815 (if (consp c-comment-only-line-offset)
1816 c-comment-only-line-offset
1817 (cons c-comment-only-line-offset
1818 c-comment-only-line-offset))))
1819 (c-get-syntactic-indentation c-syntactic-context)))
1820 (goto-char eot)
1821 (c-calc-comment-indent line-type)))))
1822
1823 \f
1824 ;; used by outline-minor-mode
1825 (defun c-outline-level ()
1826 (let (buffer-invisibility-spec);; This so that `current-column' DTRT
1827 ;; in otherwise-hidden text.
1828 (save-excursion
1829 (skip-chars-forward "\t ")
1830 (current-column))))
1831
1832 \f
1833 (defun c-up-conditional (count)
1834 "Move back to the containing preprocessor conditional, leaving mark behind.
1835 A prefix argument acts as a repeat count. With a negative argument,
1836 move forward to the end of the containing preprocessor conditional.
1837
1838 `#elif' is treated like `#else' followed by `#if', so the function
1839 stops at them when going backward, but not when going forward."
1840 (interactive "p")
1841 (c-forward-conditional (- count) -1)
1842 (c-keep-region-active))
1843
1844 (defun c-up-conditional-with-else (count)
1845 "Move back to the containing preprocessor conditional, including `#else'.
1846 Just like `c-up-conditional', except it also stops at `#else'
1847 directives."
1848 (interactive "p")
1849 (c-forward-conditional (- count) -1 t)
1850 (c-keep-region-active))
1851
1852 (defun c-down-conditional (count)
1853 "Move forward into the next preprocessor conditional, leaving mark behind.
1854 A prefix argument acts as a repeat count. With a negative argument,
1855 move backward into the previous preprocessor conditional.
1856
1857 `#elif' is treated like `#else' followed by `#if', so the function
1858 stops at them when going forward, but not when going backward."
1859 (interactive "p")
1860 (c-forward-conditional count 1)
1861 (c-keep-region-active))
1862
1863 (defun c-down-conditional-with-else (count)
1864 "Move forward into the next preprocessor conditional, including `#else'.
1865 Just like `c-down-conditional', except it also stops at `#else'
1866 directives."
1867 (interactive "p")
1868 (c-forward-conditional count 1 t)
1869 (c-keep-region-active))
1870
1871 (defun c-backward-conditional (count &optional target-depth with-else)
1872 "Move back across a preprocessor conditional, leaving mark behind.
1873 A prefix argument acts as a repeat count. With a negative argument,
1874 move forward across a preprocessor conditional."
1875 (interactive "p")
1876 (c-forward-conditional (- count) target-depth with-else)
1877 (c-keep-region-active))
1878
1879 (defun c-forward-conditional (count &optional target-depth with-else)
1880 "Move forward across a preprocessor conditional, leaving mark behind.
1881 A prefix argument acts as a repeat count. With a negative argument,
1882 move backward across a preprocessor conditional.
1883
1884 `#elif' is treated like `#else' followed by `#if', except that the
1885 nesting level isn't changed when tracking subconditionals.
1886
1887 The optional argument TARGET-DEPTH specifies the wanted nesting depth
1888 after each scan. I.e. if TARGET-DEPTH is -1, the function will move
1889 out of the enclosing conditional. A non-integer non-nil TARGET-DEPTH
1890 counts as -1.
1891
1892 If the optional argument WITH-ELSE is non-nil, `#else' directives are
1893 treated as conditional clause limits. Normally they are ignored."
1894 (interactive "p")
1895 (let* ((forward (> count 0))
1896 (increment (if forward -1 1))
1897 (search-function (if forward 're-search-forward 're-search-backward))
1898 (new))
1899 (unless (integerp target-depth)
1900 (setq target-depth (if target-depth -1 0)))
1901 (save-excursion
1902 (while (/= count 0)
1903 (let ((depth 0)
1904 ;; subdepth is the depth in "uninteresting" subtrees,
1905 ;; i.e. those that takes us farther from the target
1906 ;; depth instead of closer.
1907 (subdepth 0)
1908 found)
1909 (save-excursion
1910 ;; Find the "next" significant line in the proper direction.
1911 (while (and (not found)
1912 ;; Rather than searching for a # sign that
1913 ;; comes at the beginning of a line aside from
1914 ;; whitespace, search first for a string
1915 ;; starting with # sign. Then verify what
1916 ;; precedes it. This is faster on account of
1917 ;; the fastmap feature of the regexp matcher.
1918 (funcall search-function
1919 "#[ \t]*\\(if\\|elif\\|endif\\|else\\)"
1920 nil t))
1921 (beginning-of-line)
1922 ;; Now verify it is really a preproc line.
1923 (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\|else\\)")
1924 (let (dchange (directive (match-string 1)))
1925 (cond ((string= directive "if")
1926 (setq dchange (- increment)))
1927 ((string= directive "endif")
1928 (setq dchange increment))
1929 ((= subdepth 0)
1930 ;; When we're not in an "uninteresting"
1931 ;; subtree, we might want to act on "elif"
1932 ;; and "else" too.
1933 (if (cond (with-else
1934 ;; Always move toward the target depth.
1935 (setq dchange
1936 (if (> target-depth 0) 1 -1)))
1937 ((string= directive "elif")
1938 (setq dchange (- increment))))
1939 ;; Ignore the change if it'd take us
1940 ;; into an "uninteresting" subtree.
1941 (if (eq (> dchange 0) (<= target-depth 0))
1942 (setq dchange nil)))))
1943 (when dchange
1944 (when (or (/= subdepth 0)
1945 (eq (> dchange 0) (<= target-depth 0)))
1946 (setq subdepth (+ subdepth dchange)))
1947 (setq depth (+ depth dchange))
1948 ;; If we are trying to move across, and we find an
1949 ;; end before we find a beginning, get an error.
1950 (if (and (< depth target-depth) (< dchange 0))
1951 (error (if forward
1952 "No following conditional at this level"
1953 "No previous conditional at this level"))))
1954 ;; When searching forward, start from next line so
1955 ;; that we don't find the same line again.
1956 (if forward (forward-line 1))
1957 ;; We found something if we've arrived at the
1958 ;; target depth.
1959 (if (and dchange (= depth target-depth))
1960 (setq found (point))))
1961 ;; else
1962 (if forward (forward-line 1)))))
1963 (or found
1964 (error "No containing preprocessor conditional"))
1965 (goto-char (setq new found)))
1966 (setq count (+ count increment))))
1967 (push-mark)
1968 (goto-char new))
1969 (c-keep-region-active))
1970
1971 \f
1972 ;; commands to indent lines, regions, defuns, and expressions
1973 (defun c-indent-command (&optional arg)
1974 "Indent current line as C code, and/or insert some whitespace.
1975
1976 If `c-tab-always-indent' is t, always just indent the current line.
1977 If nil, indent the current line only if point is at the left margin or
1978 in the line's indentation; otherwise insert some whitespace[*]. If
1979 other than nil or t, then some whitespace[*] is inserted only within
1980 literals (comments and strings), but the line is always reindented.
1981
1982 If `c-syntactic-indentation' is t, indentation is done according to
1983 the syntactic context. A numeric argument, regardless of its value,
1984 means indent rigidly all the lines of the expression starting after
1985 point so that this line becomes properly indented. The relative
1986 indentation among the lines of the expression is preserved.
1987
1988 If `c-syntactic-indentation' is nil, the line is just indented one
1989 step according to `c-basic-offset'. In this mode, a numeric argument
1990 indents a number of such steps, positive or negative, and an empty
1991 prefix argument is equivalent to -1.
1992
1993 [*] The amount and kind of whitespace inserted is controlled by the
1994 variable `c-insert-tab-function', which is called to do the actual
1995 insertion of whitespace. Normally the function in this variable
1996 just inserts a tab character, or the equivalent number of spaces,
1997 depending on the variable `indent-tabs-mode'."
1998
1999 (interactive "p")
2000 (let ((indent-function
2001 (if c-syntactic-indentation
2002 (symbol-function 'indent-according-to-mode)
2003 (lambda ()
2004 (let ((c-macro-start c-macro-start)
2005 (steps (cond ((not current-prefix-arg) 1)
2006 ((equal current-prefix-arg '(4)) -1)
2007 (t arg))))
2008 (c-shift-line-indentation (* steps c-basic-offset))
2009 (when (and c-auto-align-backslashes
2010 (save-excursion
2011 (end-of-line)
2012 (eq (char-before) ?\\))
2013 (c-query-and-set-macro-start))
2014 ;; Realign the line continuation backslash if inside a macro.
2015 (c-backslash-region (point) (point) nil t)))
2016 ))))
2017 (if (and c-syntactic-indentation current-prefix-arg)
2018 ;; If c-syntactic-indentation and got arg, always indent this
2019 ;; line as C and shift remaining lines of expression the same
2020 ;; amount.
2021 (let ((shift-amt (save-excursion
2022 (back-to-indentation)
2023 (current-column)))
2024 beg end)
2025 (c-indent-line)
2026 (setq shift-amt (- (save-excursion
2027 (back-to-indentation)
2028 (current-column))
2029 shift-amt))
2030 (save-excursion
2031 (if (eq c-tab-always-indent t)
2032 (beginning-of-line))
2033 (setq beg (point))
2034 (c-forward-sexp 1)
2035 (setq end (point))
2036 (goto-char beg)
2037 (forward-line 1)
2038 (setq beg (point)))
2039 (if (> end beg)
2040 (indent-code-rigidly beg end shift-amt "#")))
2041 ;; Else use c-tab-always-indent to determine behavior.
2042 (cond
2043 ;; CASE 1: indent when at column zero or in lines indentation,
2044 ;; otherwise insert a tab
2045 ((not c-tab-always-indent)
2046 (if (save-excursion
2047 (skip-chars-backward " \t")
2048 (not (bolp)))
2049 (funcall c-insert-tab-function)
2050 (funcall indent-function)))
2051 ;; CASE 2: just indent the line
2052 ((eq c-tab-always-indent t)
2053 (funcall indent-function))
2054 ;; CASE 3: if in a literal, insert a tab, but always indent the
2055 ;; line
2056 (t
2057 (if (c-in-literal)
2058 (funcall c-insert-tab-function))
2059 (funcall indent-function)
2060 )))))
2061
2062 (defun c-indent-exp (&optional shutup-p)
2063 "Indent each line in the balanced expression following point syntactically.
2064 If optional SHUTUP-P is non-nil, no errors are signalled if no
2065 balanced expression is found."
2066 (interactive "*P")
2067 (let ((here (point-marker))
2068 end)
2069 (set-marker-insertion-type here t)
2070 (unwind-protect
2071 (let ((start (save-restriction
2072 ;; Find the closest following open paren that
2073 ;; ends on another line.
2074 (narrow-to-region (point-min) (c-point 'eol))
2075 (let (beg (end (point)))
2076 (while (and (setq beg (c-down-list-forward end))
2077 (setq end (c-up-list-forward beg))))
2078 (and beg
2079 (eq (char-syntax (char-before beg)) ?\()
2080 (1- beg))))))
2081 ;; sanity check
2082 (if (not start)
2083 (unless shutup-p
2084 (error "Cannot find start of balanced expression to indent"))
2085 (goto-char start)
2086 (setq end (c-safe (scan-sexps (point) 1)))
2087 (if (not end)
2088 (unless shutup-p
2089 (error "Cannot find end of balanced expression to indent"))
2090 (forward-line)
2091 (if (< (point) end)
2092 (c-indent-region (point) end)))))
2093 (goto-char here)
2094 (set-marker here nil))))
2095
2096 (defun c-indent-defun ()
2097 "Indent the current top-level declaration or macro syntactically.
2098 In the macro case this also has the effect of realigning any line
2099 continuation backslashes, unless `c-auto-align-backslashes' is nil."
2100 (interactive "*")
2101 (let ((here (point-marker)) decl-limits)
2102 (unwind-protect
2103 (progn
2104 (c-save-buffer-state nil
2105 ;; We try to be line oriented, unless there are several
2106 ;; declarations on the same line.
2107 (if (looking-at c-syntactic-eol)
2108 (c-backward-token-2 1 nil (c-point 'bol))
2109 (c-forward-token-2 0 nil (c-point 'eol)))
2110 (setq decl-limits (c-declaration-limits nil)))
2111 (if decl-limits
2112 (c-indent-region (car decl-limits)
2113 (cdr decl-limits))))
2114 (goto-char here)
2115 (set-marker here nil))))
2116
2117 (defun c-indent-region (start end &optional quiet)
2118 "Indent syntactically every line whose first char is between START
2119 and END inclusive. If the optional argument QUIET is non-nil then no
2120 syntactic errors are reported, even if `c-report-syntactic-errors' is
2121 non-nil."
2122 (save-excursion
2123 (goto-char end)
2124 (skip-chars-backward " \t\n\r\f\v")
2125 (setq end (point))
2126 (goto-char start)
2127 ;; Advance to first nonblank line.
2128 (beginning-of-line)
2129 (skip-chars-forward " \t\n\r\f\v")
2130 (setq start (point))
2131 (beginning-of-line)
2132 (setq c-parsing-error
2133 (or (let ((endmark (copy-marker end))
2134 (c-parsing-error nil)
2135 ;; shut up any echo msgs on indiv lines
2136 (c-echo-syntactic-information-p nil)
2137 (in-macro (and c-auto-align-backslashes
2138 (save-excursion (c-beginning-of-macro))
2139 start))
2140 (c-fix-backslashes nil)
2141 syntax)
2142 (unwind-protect
2143 (progn
2144 (c-progress-init start end 'c-indent-region)
2145 (while (and (bolp)
2146 (not (eobp))
2147 (< (point) endmark))
2148 ;; update progress
2149 (c-progress-update)
2150 ;; skip empty lines
2151 (skip-chars-forward " \t\n")
2152 (beginning-of-line)
2153 ;; Get syntax and indent.
2154 (c-save-buffer-state nil
2155 (setq syntax (c-guess-basic-syntax)))
2156 (if (and c-auto-align-backslashes
2157 (assq 'cpp-macro syntax))
2158 ;; Record macro start.
2159 (setq in-macro (point)))
2160 (if in-macro
2161 (if (looking-at "\\s *\\\\$")
2162 (forward-line)
2163 (c-indent-line syntax t t)
2164 (if (progn (end-of-line)
2165 (not (eq (char-before) ?\\)))
2166 (progn
2167 ;; Fixup macro backslashes.
2168 (forward-line)
2169 (c-backslash-region in-macro (point) nil)
2170 (setq in-macro nil))
2171 (forward-line)))
2172 (c-indent-line syntax t t)
2173 (forward-line)))
2174 (if in-macro
2175 (c-backslash-region in-macro (c-point 'bopl) nil t)))
2176 (set-marker endmark nil)
2177 (c-progress-fini 'c-indent-region))
2178 (c-echo-parsing-error quiet))
2179 c-parsing-error))))
2180
2181 (defun c-fn-region-is-active-p ()
2182 ;; Function version of the macro for use in places that aren't
2183 ;; compiled, e.g. in the menus.
2184 ;;
2185 ;; This function does not do any hidden buffer changes.
2186 (c-region-is-active-p))
2187
2188 (defun c-indent-line-or-region ()
2189 "When the region is active, indent it syntactically. Otherwise
2190 indent the current line syntactically."
2191 ;; Emacs has a variable called mark-active, XEmacs uses region-active-p
2192 (interactive)
2193 (if (c-region-is-active-p)
2194 (c-indent-region (region-beginning) (region-end))
2195 (c-indent-line)))
2196
2197 \f
2198 ;; for progress reporting
2199 (defvar c-progress-info nil)
2200
2201 (defun c-progress-init (start end context)
2202 ;; This function does not do any hidden buffer changes.
2203 (cond
2204 ;; Be silent
2205 ((not c-progress-interval))
2206 ;; Start the progress update messages. If this Emacs doesn't have
2207 ;; a built-in timer, just be dumb about it.
2208 ((not (fboundp 'current-time))
2209 (message "Indenting region... (this may take a while)"))
2210 ;; If progress has already been initialized, do nothing. otherwise
2211 ;; initialize the counter with a vector of:
2212 ;; [start end lastsec context]
2213 (c-progress-info)
2214 (t (setq c-progress-info (vector start
2215 (save-excursion
2216 (goto-char end)
2217 (point-marker))
2218 (nth 1 (current-time))
2219 context))
2220 (message "Indenting region..."))
2221 ))
2222
2223 (defun c-progress-update ()
2224 ;; This function does not do any hidden buffer changes.
2225 (if (not (and c-progress-info c-progress-interval))
2226 nil
2227 (let ((now (nth 1 (current-time)))
2228 (start (aref c-progress-info 0))
2229 (end (aref c-progress-info 1))
2230 (lastsecs (aref c-progress-info 2)))
2231 ;; should we update? currently, update happens every 2 seconds,
2232 ;; what's the right value?
2233 (if (< c-progress-interval (- now lastsecs))
2234 (progn
2235 (message "Indenting region... (%d%% complete)"
2236 (/ (* 100 (- (point) start)) (- end start)))
2237 (aset c-progress-info 2 now)))
2238 )))
2239
2240 (defun c-progress-fini (context)
2241 ;; This function does not do any hidden buffer changes.
2242 (if (not c-progress-interval)
2243 nil
2244 (if (or (eq context (aref c-progress-info 3))
2245 (eq context t))
2246 (progn
2247 (set-marker (aref c-progress-info 1) nil)
2248 (setq c-progress-info nil)
2249 (message "Indenting region... done")))))
2250
2251
2252 \f
2253 ;;; This page handles insertion and removal of backslashes for C macros.
2254
2255 (defun c-backslash-region (from to delete-flag &optional line-mode)
2256 "Insert, align, or delete end-of-line backslashes on the lines in the region.
2257 With no argument, inserts backslashes and aligns existing backslashes.
2258 With an argument, deletes the backslashes. The backslash alignment is
2259 done according to the settings in `c-backslash-column',
2260 `c-backslash-max-column' and `c-auto-align-backslashes'.
2261
2262 This function does not modify blank lines at the start of the region.
2263 If the region ends at the start of a line and the macro doesn't
2264 continue below it, the backslash (if any) at the end of the previous
2265 line is deleted.
2266
2267 You can put the region around an entire macro definition and use this
2268 command to conveniently insert and align the necessary backslashes."
2269 (interactive "*r\nP")
2270 (let ((endmark (make-marker))
2271 ;; Keep the backslash trimming functions from changing the
2272 ;; whitespace around point, since in this case it's only the
2273 ;; position of point that tells the indentation of the line.
2274 (point-pos (if (save-excursion
2275 (skip-chars-backward " \t")
2276 (and (bolp) (looking-at "[ \t]*\\\\?$")))
2277 (point-marker)
2278 (point-min)))
2279 column longest-line-col bs-col-after-end)
2280 (save-excursion
2281 (goto-char to)
2282 (if (and (not line-mode) (bobp))
2283 ;; Nothing to do if to is at bob, since we should back up
2284 ;; and there's no line to back up to.
2285 nil
2286 (when (and (not line-mode) (bolp))
2287 ;; Do not back up the to line if line-mode is set, to make
2288 ;; e.g. c-newline-and-indent consistent regardless whether
2289 ;; the (newline) call leaves point at bol or not.
2290 (backward-char)
2291 (setq to (point)))
2292 (if delete-flag
2293 (progn
2294 (set-marker endmark (point))
2295 (goto-char from)
2296 (c-delete-backslashes-forward endmark point-pos))
2297 ;; Set bs-col-after-end to the column of any backslash
2298 ;; following the region, or nil if there is none.
2299 (setq bs-col-after-end
2300 (and (progn (end-of-line)
2301 (eq (char-before) ?\\))
2302 (= (forward-line 1) 0)
2303 (progn (end-of-line)
2304 (eq (char-before) ?\\))
2305 (1- (current-column))))
2306 (when line-mode
2307 ;; Back up the to line if line-mode is set, since the line
2308 ;; after the newly inserted line break should not be
2309 ;; touched in c-newline-and-indent.
2310 (setq to (max from (or (c-safe (c-point 'eopl)) from)))
2311 (unless bs-col-after-end
2312 ;; Set bs-col-after-end to non-nil in any case, since we
2313 ;; do not want to delete the backslash at the last line.
2314 (setq bs-col-after-end t)))
2315 (if (and line-mode
2316 (not c-auto-align-backslashes))
2317 (goto-char from)
2318 ;; Compute the smallest column number past the ends of all
2319 ;; the lines.
2320 (setq longest-line-col 0)
2321 (goto-char to)
2322 (if bs-col-after-end
2323 ;; Include one more line in the max column
2324 ;; calculation, since the to line will be backslashed
2325 ;; too.
2326 (forward-line 1))
2327 (end-of-line)
2328 (while (and (>= (point) from)
2329 (progn
2330 (if (eq (char-before) ?\\)
2331 (forward-char -1))
2332 (skip-chars-backward " \t")
2333 (setq longest-line-col (max longest-line-col
2334 (1+ (current-column))))
2335 (beginning-of-line)
2336 (not (bobp))))
2337 (backward-char))
2338 ;; Try to align with surrounding backslashes.
2339 (goto-char from)
2340 (beginning-of-line)
2341 (if (and (not (bobp))
2342 (progn (backward-char)
2343 (eq (char-before) ?\\)))
2344 (progn
2345 (setq column (1- (current-column)))
2346 (if (numberp bs-col-after-end)
2347 ;; Both a preceding and a following backslash.
2348 ;; Choose the greatest of them.
2349 (setq column (max column bs-col-after-end)))
2350 (goto-char from))
2351 ;; No preceding backslash. Try to align with one
2352 ;; following the region. Disregard the backslash at the
2353 ;; to line since it's likely to be bogus (e.g. when
2354 ;; called from c-newline-and-indent).
2355 (if (numberp bs-col-after-end)
2356 (setq column bs-col-after-end))
2357 ;; Don't modify blank lines at start of region.
2358 (goto-char from)
2359 (while (and (< (point) to) (bolp) (eolp))
2360 (forward-line 1)))
2361 (if (and column (< column longest-line-col))
2362 ;; Don't try to align with surrounding backslashes if
2363 ;; any line is too long.
2364 (setq column nil))
2365 (unless column
2366 ;; Impose minimum limit and tab width alignment only if
2367 ;; we can't align with surrounding backslashes.
2368 (if (> (% longest-line-col tab-width) 0)
2369 (setq longest-line-col
2370 (* (/ (+ longest-line-col tab-width -1)
2371 tab-width)
2372 tab-width)))
2373 (setq column (max c-backslash-column
2374 longest-line-col)))
2375 ;; Always impose maximum limit.
2376 (setq column (min column c-backslash-max-column)))
2377 (if bs-col-after-end
2378 ;; Add backslashes on all lines if the macro continues
2379 ;; after the to line.
2380 (progn
2381 (set-marker endmark to)
2382 (c-append-backslashes-forward endmark column point-pos))
2383 ;; Add backslashes on all lines except the last, and
2384 ;; remove any on the last line.
2385 (if (save-excursion
2386 (goto-char to)
2387 (beginning-of-line)
2388 (if (not (bobp))
2389 (set-marker endmark (1- (point)))))
2390 (progn
2391 (c-append-backslashes-forward endmark column point-pos)
2392 ;; The function above leaves point on the line
2393 ;; following endmark.
2394 (set-marker endmark (point)))
2395 (set-marker endmark to))
2396 (c-delete-backslashes-forward endmark point-pos)))))
2397 (set-marker endmark nil)
2398 (if (markerp point-pos)
2399 (set-marker point-pos nil))))
2400
2401 (defun c-append-backslashes-forward (to-mark column point-pos)
2402 ;; This function does not do any hidden buffer changes.
2403 (let ((state (parse-partial-sexp (c-point 'bol) (point))))
2404 (if column
2405 (while
2406 (and
2407 (<= (point) to-mark)
2408
2409 (let ((start (point)) (inserted nil) end col)
2410 (end-of-line)
2411 (unless (eq (char-before) ?\\)
2412 (insert ?\\)
2413 (setq inserted t))
2414 (setq state (parse-partial-sexp
2415 start (point) nil nil state))
2416 (backward-char)
2417 (setq col (current-column))
2418
2419 ;; Avoid unnecessary changes of the buffer.
2420 (cond ((and (not inserted) (nth 3 state))
2421 ;; Don't realign backslashes in string literals
2422 ;; since that would change them.
2423 )
2424
2425 ((< col column)
2426 (delete-region
2427 (point)
2428 (progn
2429 (skip-chars-backward
2430 " \t" (if (>= (point) point-pos) point-pos))
2431 (point)))
2432 (indent-to column))
2433
2434 ((and (= col column)
2435 (memq (char-before) '(?\ ?\t))))
2436
2437 ((progn
2438 (setq end (point))
2439 (or (/= (skip-chars-backward
2440 " \t" (if (>= (point) point-pos) point-pos))
2441 -1)
2442 (/= (char-after) ?\ )))
2443 (delete-region (point) end)
2444 (indent-to column 1)))
2445
2446 (zerop (forward-line 1)))
2447 (bolp))) ; forward-line has funny behavior at eob.
2448
2449 ;; Make sure there are backslashes with at least one space in
2450 ;; front of them.
2451 (while
2452 (and
2453 (<= (point) to-mark)
2454
2455 (let ((start (point)))
2456 (end-of-line)
2457 (setq state (parse-partial-sexp
2458 start (point) nil nil state))
2459
2460 (if (eq (char-before) ?\\)
2461 (unless (nth 3 state)
2462 (backward-char)
2463 (unless (and (memq (char-before) '(?\ ?\t))
2464 (/= (point) point-pos))
2465 (insert ?\ )))
2466
2467 (if (and (memq (char-before) '(?\ ?\t))
2468 (/= (point) point-pos))
2469 (insert ?\\)
2470 (insert ?\ ?\\)))
2471
2472 (zerop (forward-line 1)))
2473 (bolp)))))) ; forward-line has funny behavior at eob.
2474
2475 (defun c-delete-backslashes-forward (to-mark point-pos)
2476 ;; This function does not do any hidden buffer changes.
2477 (while
2478 (and (<= (point) to-mark)
2479 (progn
2480 (end-of-line)
2481 (if (eq (char-before) ?\\)
2482 (delete-region
2483 (point)
2484 (progn (backward-char)
2485 (skip-chars-backward " \t" (if (>= (point) point-pos)
2486 point-pos))
2487 (point))))
2488 (zerop (forward-line 1)))
2489 (bolp)))) ; forward-line has funny behavior at eob.
2490
2491
2492 \f
2493 ;;; Line breaking and paragraph filling.
2494
2495 (defvar c-auto-fill-prefix t)
2496 (defvar c-lit-limits nil)
2497 (defvar c-lit-type nil)
2498
2499 ;; The filling code is based on a simple theory; leave the intricacies
2500 ;; of the text handling to the currently active mode for that
2501 ;; (e.g. adaptive-fill-mode or filladapt-mode) and do as little as
2502 ;; possible to make them work correctly wrt the comment and string
2503 ;; separators, one-line paragraphs etc. Unfortunately, when it comes
2504 ;; to it, there's quite a lot of special cases to handle which makes
2505 ;; the code anything but simple. The intention is that it will work
2506 ;; with any well-written text filling package that preserves a fill
2507 ;; prefix.
2508 ;;
2509 ;; We temporarily mask comment starters and enders as necessary for
2510 ;; the filling code to do its job on a seemingly normal text block.
2511 ;; We do _not_ mask the fill prefix, so it's up to the filling code to
2512 ;; preserve it correctly (especially important when filling C++ style
2513 ;; line comments). By default, we set up and use adaptive-fill-mode,
2514 ;; which is standard in all supported Emacs flavors.
2515
2516 (defun c-guess-fill-prefix (lit-limits lit-type)
2517 ;; Determine the appropriate comment fill prefix for a block or line
2518 ;; comment. Return a cons of the prefix string and the column where
2519 ;; it ends. If fill-prefix is set, it'll override. Note that this
2520 ;; function also uses the value of point in some heuristics.
2521
2522 (let* ((here (point))
2523 (prefix-regexp (concat "[ \t]*\\("
2524 c-current-comment-prefix
2525 "\\)[ \t]*"))
2526 (comment-start-regexp (if (eq lit-type 'c++)
2527 prefix-regexp
2528 comment-start-skip))
2529 prefix-line comment-prefix res comment-text-end)
2530
2531 (cond
2532 (fill-prefix
2533 (setq res (cons fill-prefix
2534 ;; Ugly way of getting the column after the fill
2535 ;; prefix; it'd be nice with a current-column
2536 ;; that works on strings..
2537 (let ((start (point)))
2538 (unwind-protect
2539 (progn
2540 (insert-and-inherit "\n" fill-prefix)
2541 (current-column))
2542 (delete-region start (point)))))))
2543
2544 ((eq lit-type 'c++)
2545 (save-excursion
2546 ;; Set fallback for comment-prefix if none is found.
2547 (setq comment-prefix "// "
2548 comment-text-end (cdr lit-limits))
2549
2550 (beginning-of-line)
2551 (if (> (point) (car lit-limits))
2552 ;; The current line is not the comment starter, so the
2553 ;; comment has more than one line, and it can therefore be
2554 ;; used to find the comment fill prefix.
2555 (setq prefix-line (point))
2556
2557 (goto-char (car lit-limits))
2558 (if (and (= (forward-line 1) 0)
2559 (< (point) (cdr lit-limits)))
2560 ;; The line after the comment starter is inside the
2561 ;; comment, so we can use it.
2562 (setq prefix-line (point))
2563
2564 ;; The comment is only one line. Take the comment prefix
2565 ;; from it and keep the indentation.
2566 (goto-char (car lit-limits))
2567 (if (looking-at prefix-regexp)
2568 (goto-char (match-end 0))
2569 (forward-char 2)
2570 (skip-chars-forward " \t"))
2571
2572 (let (str col)
2573 (if (eq (c-point 'boi) (car lit-limits))
2574 ;; There is only whitespace before the comment
2575 ;; starter; take the prefix straight from this line.
2576 (setq str (buffer-substring-no-properties
2577 (c-point 'bol) (point))
2578 col (current-column))
2579
2580 ;; There is code before the comment starter, so we
2581 ;; have to temporarily insert and indent a new line to
2582 ;; get the right space/tab mix in the indentation.
2583 (let ((prefix-len (- (point) (car lit-limits)))
2584 tmp)
2585 (unwind-protect
2586 (progn
2587 (goto-char (car lit-limits))
2588 (indent-to (prog1 (current-column)
2589 (insert ?\n)))
2590 (setq tmp (point))
2591 (forward-char prefix-len)
2592 (setq str (buffer-substring-no-properties
2593 (c-point 'bol) (point))
2594 col (current-column)))
2595 (delete-region (car lit-limits) tmp))))
2596
2597 (setq res
2598 (if (or (string-match "\\s \\'" str) (not (eolp)))
2599 (cons str col)
2600 ;; The prefix ends the line with no whitespace
2601 ;; after it. Default to a single space.
2602 (cons (concat str " ") (1+ col))))
2603 )))))
2604
2605 (t
2606 (setq comment-text-end
2607 (save-excursion
2608 (goto-char (- (cdr lit-limits) 2))
2609 (if (looking-at "\\*/") (point) (cdr lit-limits))))
2610
2611 (save-excursion
2612 (beginning-of-line)
2613 (if (and (> (point) (car lit-limits))
2614 (not (and (looking-at "[ \t]*\\*/")
2615 (eq (cdr lit-limits) (match-end 0)))))
2616 ;; The current line is not the comment starter and
2617 ;; contains more than just the ender, so it's good enough
2618 ;; to be used for the comment fill prefix.
2619 (setq prefix-line (point))
2620 (goto-char (car lit-limits))
2621
2622 (cond ((or (/= (forward-line 1) 0)
2623 (>= (point) (cdr lit-limits))
2624 (and (looking-at "[ \t]*\\*/")
2625 (eq (cdr lit-limits) (match-end 0)))
2626 (and (looking-at prefix-regexp)
2627 (<= (1- (cdr lit-limits)) (match-end 0))))
2628 ;; The comment is either one line or the next line contains
2629 ;; just the comment ender. In this case we have no
2630 ;; information about a suitable comment prefix, so we resort
2631 ;; to c-block-comment-prefix.
2632 (setq comment-prefix (or c-block-comment-prefix "")))
2633
2634 ((< here (point))
2635 ;; The point was on the comment opener line, so we might want
2636 ;; to treat this as a not yet closed comment.
2637
2638 (if (and (match-beginning 1)
2639 (/= (match-beginning 1) (match-end 1)))
2640 ;; Above `prefix-regexp' matched a nonempty prefix on the
2641 ;; second line, so let's use it. Normally it should do
2642 ;; to set `prefix-line' and let the code below pick up
2643 ;; the whole prefix, but if there's no text after the
2644 ;; match then it will probably fall back to no prefix at
2645 ;; all if the comment isn't closed yet, so in that case
2646 ;; it's better to force use of the prefix matched now.
2647 (if (= (match-end 0) (c-point 'eol))
2648 (setq comment-prefix (match-string 1))
2649 (setq prefix-line (point)))
2650
2651 ;; There's no nonempty prefix on the line after the
2652 ;; comment opener. If the line is empty, or if the
2653 ;; text on it has less or equal indentation than the
2654 ;; comment starter we assume it's an unclosed
2655 ;; comment starter, i.e. that
2656 ;; `c-block-comment-prefix' should be used.
2657 ;; Otherwise we assume it's a closed comment where
2658 ;; the prefix really is the empty string.
2659 ;; E.g. this is an unclosed comment:
2660 ;;
2661 ;; /*
2662 ;; foo
2663 ;;
2664 ;; But this is not:
2665 ;;
2666 ;; /*
2667 ;; foo
2668 ;; */
2669 ;;
2670 ;; (Looking for the presence of the comment closer
2671 ;; rarely works since it's probably the closer of
2672 ;; some comment further down when the comment
2673 ;; really is unclosed.)
2674 (if (<= (save-excursion (back-to-indentation)
2675 (current-column))
2676 (save-excursion (goto-char (car lit-limits))
2677 (current-column)))
2678 (setq comment-prefix (or c-block-comment-prefix ""))
2679 (setq prefix-line (point)))))
2680
2681 (t
2682 ;; Otherwise the line after the comment starter is good
2683 ;; enough to find the prefix in.
2684 (setq prefix-line (point))))
2685
2686 (when comment-prefix
2687 ;; Haven't got the comment prefix on any real line that we
2688 ;; can take it from, so we have to temporarily insert
2689 ;; `comment-prefix' on a line and indent it to find the
2690 ;; correct column and the correct mix of tabs and spaces.
2691 (setq res
2692 (let (tmp-pre tmp-post)
2693 (unwind-protect
2694 (progn
2695
2696 (goto-char (car lit-limits))
2697 (if (looking-at comment-start-regexp)
2698 (goto-char (min (match-end 0)
2699 comment-text-end))
2700 (forward-char 2)
2701 (skip-chars-forward " \t"))
2702
2703 (when (eq (char-syntax (char-before)) ?\ )
2704 ;; If there's ws on the current line, we'll use it
2705 ;; instead of what's ending comment-prefix.
2706 (setq comment-prefix
2707 (concat (substring comment-prefix
2708 0 (string-match
2709 "\\s *\\'"
2710 comment-prefix))
2711 (buffer-substring-no-properties
2712 (save-excursion
2713 (skip-chars-backward " \t")
2714 (point))
2715 (point)))))
2716
2717 (setq tmp-pre (point-marker))
2718
2719 ;; We insert an extra non-whitespace character
2720 ;; before the line break and after comment-prefix in
2721 ;; case it's "" or ends with whitespace.
2722 (insert-and-inherit "x\n" comment-prefix "x")
2723 (setq tmp-post (point-marker))
2724
2725 (indent-according-to-mode)
2726
2727 (goto-char (1- tmp-post))
2728 (cons (buffer-substring-no-properties
2729 (c-point 'bol) (point))
2730 (current-column)))
2731
2732 (when tmp-post
2733 (delete-region tmp-pre tmp-post)
2734 (set-marker tmp-pre nil)
2735 (set-marker tmp-post nil))))))))))
2736
2737 (or res ; Found a good prefix above.
2738
2739 (save-excursion
2740 ;; prefix-line is the bol of a line on which we should try
2741 ;; to find the prefix.
2742 (let* (fb-string fb-endpos ; Contains any fallback prefix found.
2743 (test-line
2744 (lambda ()
2745 (when (and (looking-at prefix-regexp)
2746 (<= (match-end 0) comment-text-end))
2747 (unless (eq (match-end 0) (c-point 'eol))
2748 ;; The match is fine if there's text after it.
2749 (throw 'found (cons (buffer-substring-no-properties
2750 (match-beginning 0) (match-end 0))
2751 (progn (goto-char (match-end 0))
2752 (current-column)))))
2753 (unless fb-string
2754 ;; This match is better than nothing, so let's
2755 ;; remember it in case nothing better is found
2756 ;; on another line.
2757 (setq fb-string (buffer-substring-no-properties
2758 (match-beginning 0) (match-end 0))
2759 fb-endpos (match-end 0)))
2760 t))))
2761
2762 (or (catch 'found
2763 ;; Search for a line which has text after the prefix
2764 ;; so that we get the proper amount of whitespace
2765 ;; after it. We start with the current line, then
2766 ;; search backwards, then forwards.
2767
2768 (goto-char prefix-line)
2769 (when (and (funcall test-line)
2770 (or (/= (match-end 1) (match-end 0))
2771 ;; The whitespace is sucked up by the
2772 ;; first [ \t]* glob if the prefix is empty.
2773 (and (= (match-beginning 1) (match-end 1))
2774 (/= (match-beginning 0) (match-end 0)))))
2775 ;; If the current line doesn't have text but do
2776 ;; have whitespace after the prefix, we'll use it.
2777 (throw 'found (cons fb-string
2778 (progn (goto-char fb-endpos)
2779 (current-column)))))
2780
2781 (if (eq lit-type 'c++)
2782 ;; For line comments we can search up to and
2783 ;; including the first line.
2784 (while (and (zerop (forward-line -1))
2785 (>= (point) (car lit-limits)))
2786 (funcall test-line))
2787 ;; For block comments we must stop before the
2788 ;; block starter.
2789 (while (and (zerop (forward-line -1))
2790 (> (point) (car lit-limits)))
2791 (funcall test-line)))
2792
2793 (goto-char prefix-line)
2794 (while (and (zerop (forward-line 1))
2795 (< (point) (cdr lit-limits)))
2796 (funcall test-line))
2797
2798 (goto-char prefix-line)
2799 nil)
2800
2801 (when fb-string
2802 ;; A good line wasn't found, but at least we have a
2803 ;; fallback that matches the comment prefix regexp.
2804 (cond ((or (string-match "\\s \\'" fb-string)
2805 (progn
2806 (goto-char fb-endpos)
2807 (not (eolp))))
2808 ;; There are ws or text after the prefix, so
2809 ;; let's use it.
2810 (cons fb-string (current-column)))
2811
2812 ((progn
2813 ;; Check if there's any whitespace padding
2814 ;; on the comment start line that we can
2815 ;; use after the prefix.
2816 (goto-char (car lit-limits))
2817 (if (looking-at comment-start-regexp)
2818 (goto-char (match-end 0))
2819 (forward-char 2)
2820 (skip-chars-forward " \t"))
2821 (or (not (eolp))
2822 (eq (char-syntax (char-before)) ?\ )))
2823
2824 (setq fb-string (buffer-substring-no-properties
2825 (save-excursion
2826 (skip-chars-backward " \t")
2827 (point))
2828 (point)))
2829 (goto-char fb-endpos)
2830 (skip-chars-backward " \t")
2831
2832 (let ((tmp (point)))
2833 ;; Got to mess in the buffer once again to
2834 ;; ensure the column gets correct. :P
2835 (unwind-protect
2836 (progn
2837 (insert-and-inherit fb-string)
2838 (cons (buffer-substring-no-properties
2839 (c-point 'bol)
2840 (point))
2841 (current-column)))
2842 (delete-region tmp (point)))))
2843
2844 (t
2845 ;; Last resort: Just add a single space after
2846 ;; the prefix.
2847 (cons (concat fb-string " ")
2848 (progn (goto-char fb-endpos)
2849 (1+ (current-column)))))))
2850
2851 ;; The line doesn't match the comment prefix regexp.
2852 (if comment-prefix
2853 ;; We have a fallback for line comments that we must use.
2854 (cons (concat (buffer-substring-no-properties
2855 prefix-line (c-point 'boi))
2856 comment-prefix)
2857 (progn (back-to-indentation)
2858 (+ (current-column) (length comment-prefix))))
2859
2860 ;; Assume we are dealing with a "free text" block
2861 ;; comment where the lines doesn't have any comment
2862 ;; prefix at all and we should just fill it as
2863 ;; normal text.
2864 '("" . 0))))))
2865 ))
2866
2867 (defun c-mask-paragraph (fill-paragraph apply-outside-literal fun &rest args)
2868 ;; Calls FUN with ARGS ar arguments while the current paragraph is
2869 ;; masked to allow adaptive filling to work correctly. That
2870 ;; includes narrowing the buffer and, if point is inside a comment,
2871 ;; masking the comment starter and ender appropriately.
2872 ;;
2873 ;; FILL-PARAGRAPH is non-nil if called for whole paragraph filling.
2874 ;; The position of point is then less significant when doing masking
2875 ;; and narrowing.
2876 ;;
2877 ;; If APPLY-OUTSIDE-LITERAL is nil then the function will be called
2878 ;; only if the point turns out to be inside a comment or a string.
2879 ;;
2880 ;; This function does not do any hidden buffer changes.
2881
2882 (let (fill
2883 ;; beg and end limits the region to narrow. end is a marker.
2884 beg end
2885 ;; tmp-pre and tmp-post mark strings that are temporarily
2886 ;; inserted at the start and end of the region. tmp-pre is a
2887 ;; cons of the positions of the prepended string. tmp-post is
2888 ;; a marker pointing to the single character of the appended
2889 ;; string.
2890 tmp-pre tmp-post
2891 ;; If hang-ender-stuck isn't nil, the comment ender is
2892 ;; hanging. In that case it's set to the number of spaces
2893 ;; that should be between the text and the ender.
2894 hang-ender-stuck
2895 (here (point))
2896 (c-lit-limits c-lit-limits)
2897 (c-lit-type c-lit-type))
2898
2899 ;; Restore point on undo. It's necessary since we do a lot of
2900 ;; hidden inserts and deletes below that should be as transparent
2901 ;; as possible.
2902 (if (and buffer-undo-list (not (eq buffer-undo-list t)))
2903 (setq buffer-undo-list (cons (point) buffer-undo-list)))
2904
2905 (save-restriction
2906 ;; Widen to catch comment limits correctly.
2907 (widen)
2908 (unless c-lit-limits
2909 (setq c-lit-limits (c-literal-limits nil fill-paragraph)))
2910 (setq c-lit-limits (c-collect-line-comments c-lit-limits))
2911 (unless c-lit-type
2912 (setq c-lit-type (c-literal-type c-lit-limits))))
2913
2914 (save-excursion
2915 (unless (c-safe (backward-char)
2916 (forward-paragraph)
2917 (>= (point) here))
2918 (goto-char here)
2919 (forward-paragraph))
2920 (setq end (point-marker)))
2921 (save-excursion
2922 (unless (c-safe (forward-char)
2923 (backward-paragraph)
2924 (<= (point) here))
2925 (goto-char here)
2926 (backward-paragraph))
2927 (setq beg (point)))
2928
2929 (unwind-protect
2930 (progn
2931 (cond
2932
2933 ((eq c-lit-type 'c++) ; Line comment.
2934 (save-excursion
2935 ;; Limit to the comment or paragraph end, whichever
2936 ;; comes first.
2937 (set-marker end (min end (cdr c-lit-limits)))
2938
2939 (when (<= beg (car c-lit-limits))
2940 ;; The region includes the comment starter, so we must
2941 ;; check it.
2942 (goto-char (car c-lit-limits))
2943 (back-to-indentation)
2944 (if (eq (point) (car c-lit-limits))
2945 ;; Include the first line in the region.
2946 (setq beg (c-point 'bol))
2947 ;; The first line contains code before the
2948 ;; comment. We must fake a line that doesn't.
2949 (setq tmp-pre t))))
2950
2951 (setq apply-outside-literal t))
2952
2953 ((eq c-lit-type 'c) ; Block comment.
2954 (when (>= end (cdr c-lit-limits))
2955 ;; The region includes the comment ender which we might
2956 ;; want to keep together with the last word.
2957 (unless (save-excursion
2958 (goto-char (cdr c-lit-limits))
2959 (beginning-of-line)
2960 (and (looking-at (concat "[ \t]*\\("
2961 c-current-comment-prefix
2962 "\\)\\*/"))
2963 (eq (cdr c-lit-limits) (match-end 0))
2964 ;; The comment ender is on a line of its
2965 ;; own. Keep it that way.
2966 (set-marker end (point))))
2967
2968 (if fill-paragraph
2969 ;; The comment ender should hang. Replace all
2970 ;; cruft between it and the last word with one or
2971 ;; two 'x' and include it in the region. We'll
2972 ;; change them back to spaces afterwards. This
2973 ;; isn't done when auto filling, since that'd
2974 ;; effectively make it impossible to insert extra
2975 ;; spaces before the comment ender.
2976 (let* ((ender-start (save-excursion
2977 (goto-char (cdr c-lit-limits))
2978 (skip-syntax-backward "^w ")
2979 (point)))
2980 (point-rel (- ender-start here))
2981 spaces)
2982
2983 (save-excursion
2984 (goto-char (cdr c-lit-limits))
2985 (setq tmp-post (point-marker))
2986 (insert ?\n)
2987 (set-marker end (point))
2988 (forward-line -1)
2989 (if (and (looking-at (concat "[ \t]*\\(\\("
2990 c-current-comment-prefix
2991 "\\)[ \t]*\\)"))
2992 (eq ender-start (match-end 0)))
2993 ;; The comment ender is prefixed by nothing
2994 ;; but a comment line prefix. Remove it
2995 ;; along with surrounding ws.
2996 (setq spaces (- (match-end 1) (match-end 2)))
2997 (goto-char ender-start))
2998 (skip-chars-backward " \t\r\n")
2999
3000 (if (/= (point) ender-start)
3001 (progn
3002 (if (<= here (point))
3003 ;; Don't adjust point below if it's
3004 ;; before the string we replace.
3005 (setq point-rel -1))
3006 ;; Keep one or two spaces between the
3007 ;; text and the ender, depending on how
3008 ;; many there are now.
3009 (unless spaces
3010 (setq spaces (- ender-start (point))))
3011 (setq spaces
3012 (max
3013 (min spaces
3014 (if sentence-end-double-space 2 1))
3015 1))
3016 ;; Insert the filler first to keep marks right.
3017 (insert-char ?x spaces t)
3018 (delete-region (point) (+ ender-start spaces))
3019 (setq hang-ender-stuck spaces)
3020 (setq point-rel
3021 (and (>= point-rel 0)
3022 (- (point) (min point-rel spaces)))))
3023 (setq point-rel nil)))
3024
3025 (if point-rel
3026 ;; Point was in the middle of the string we
3027 ;; replaced above, so put it back in the same
3028 ;; relative position, counting from the end.
3029 (goto-char point-rel)))
3030
3031 ;; We're doing auto filling. Just move the marker
3032 ;; to the comment end to ignore any code after the
3033 ;; comment.
3034 (move-marker end (cdr c-lit-limits)))))
3035
3036 (when (<= beg (car c-lit-limits))
3037 ;; The region includes the comment starter.
3038 (save-excursion
3039 (goto-char (car c-lit-limits))
3040 (if (looking-at (concat "\\(" comment-start-skip "\\)$"))
3041 ;; Begin with the next line.
3042 (setq beg (c-point 'bonl))
3043 ;; Fake the fill prefix in the first line.
3044 (setq tmp-pre t))))
3045
3046 (setq apply-outside-literal t))
3047
3048 ((eq c-lit-type 'string) ; String.
3049 (save-excursion
3050 (when (>= end (cdr c-lit-limits))
3051 (goto-char (1- (cdr c-lit-limits)))
3052 (setq tmp-post (point-marker))
3053 (insert ?\n)
3054 (set-marker end (point)))
3055 (when (<= beg (car c-lit-limits))
3056 (goto-char (1+ (car c-lit-limits)))
3057 (setq beg (if (looking-at "\\\\$")
3058 ;; Leave the start line if it's
3059 ;; nothing but an escaped newline.
3060 (1+ (match-end 0))
3061 (point)))))
3062 (setq apply-outside-literal t))
3063
3064 ((eq c-lit-type 'pound) ; Macro
3065 ;; Narrow to the macro limits if they are nearer than the
3066 ;; paragraph limits. Don't know if this is necessary but
3067 ;; do it for completeness sake (doing auto filling at all
3068 ;; inside macros is bogus to begin with since the line
3069 ;; continuation backslashes aren't handled).
3070 (save-excursion
3071 (c-beginning-of-macro)
3072 (beginning-of-line)
3073 (if (> (point) beg)
3074 (setq beg (point)))
3075 (c-end-of-macro)
3076 (forward-line)
3077 (if (< (point) end)
3078 (set-marker end (point)))))
3079
3080 (t ; Other code.
3081 ;; Try to avoid comments and macros in the paragraph to
3082 ;; avoid that the adaptive fill mode gets the prefix from
3083 ;; them.
3084 (c-save-buffer-state nil
3085 (save-excursion
3086 (goto-char beg)
3087 (c-forward-syntactic-ws end)
3088 (beginning-of-line)
3089 (setq beg (point))
3090 (goto-char end)
3091 (c-backward-syntactic-ws beg)
3092 (forward-line)
3093 (set-marker end (point))))))
3094
3095 (when tmp-pre
3096 ;; Temporarily insert the fill prefix after the comment
3097 ;; starter so that the first line looks like any other
3098 ;; comment line in the narrowed region.
3099 (setq fill (c-save-buffer-state nil
3100 (c-guess-fill-prefix c-lit-limits c-lit-type)))
3101 (unless (string-match (concat "\\`[ \t]*\\("
3102 c-current-comment-prefix
3103 "\\)[ \t]*\\'")
3104 (car fill))
3105 ;; Oops, the prefix doesn't match the comment prefix
3106 ;; regexp. This could produce very confusing
3107 ;; results with adaptive fill packages together with
3108 ;; the insert prefix magic below, since the prefix
3109 ;; often doesn't appear at all. So let's warn about
3110 ;; it.
3111 (message "\
3112 Warning: Regexp from `c-comment-prefix-regexp' doesn't match the comment prefix %S"
3113 (car fill)))
3114 ;; Find the right spot on the line, break it, insert
3115 ;; the fill prefix and make sure we're back in the
3116 ;; same column by temporarily prefixing the first word
3117 ;; with a number of 'x'.
3118 (save-excursion
3119 (goto-char (car c-lit-limits))
3120 (if (looking-at (if (eq c-lit-type 'c++)
3121 c-current-comment-prefix
3122 comment-start-skip))
3123 (goto-char (match-end 0))
3124 (forward-char 2)
3125 (skip-chars-forward " \t"))
3126 (while (and (< (current-column) (cdr fill))
3127 (not (eolp)))
3128 (forward-char 1))
3129 (let ((col (current-column)))
3130 (setq beg (1+ (point))
3131 tmp-pre (list (point)))
3132 (unwind-protect
3133 (progn
3134 (insert-and-inherit "\n" (car fill))
3135 (insert-char ?x (- col (current-column)) t))
3136 (setcdr tmp-pre (point))))))
3137
3138 (when apply-outside-literal
3139 ;; `apply-outside-literal' is always set to t here if
3140 ;; we're inside a literal.
3141
3142 (let ((fill-prefix
3143 (or fill-prefix
3144 ;; Kludge: If the function that adapts the fill prefix
3145 ;; doesn't produce the required comment starter for
3146 ;; line comments, then force it by setting fill-prefix.
3147 (when (and (eq c-lit-type 'c++)
3148 ;; Kludge the kludge: filladapt-mode doesn't
3149 ;; have this problem, but it currently
3150 ;; doesn't override fill-context-prefix
3151 ;; (version 2.12).
3152 (not (and (boundp 'filladapt-mode)
3153 filladapt-mode))
3154 (not (string-match
3155 "\\`[ \t]*//"
3156 (or (fill-context-prefix beg end)
3157 ""))))
3158 (c-save-buffer-state nil
3159 (car (or fill (c-guess-fill-prefix
3160 c-lit-limits c-lit-type)))))))
3161
3162 ;; Save the relative position of point if it's outside the
3163 ;; region we're going to narrow. Want to restore it in that
3164 ;; case, but otherwise it should be moved according to the
3165 ;; called function.
3166 (point-rel (cond ((< (point) beg) (- (point) beg))
3167 ((> (point) end) (- (point) end)))))
3168
3169 ;; Preparations finally done! Now we can call the
3170 ;; actual function.
3171 (prog1
3172 (save-restriction
3173 (narrow-to-region beg end)
3174 (apply fun args))
3175 (if point-rel
3176 ;; Restore point if it was outside the region.
3177 (if (< point-rel 0)
3178 (goto-char (+ beg point-rel))
3179 (goto-char (+ end point-rel))))))))
3180
3181 (when (consp tmp-pre)
3182 (delete-region (car tmp-pre) (cdr tmp-pre)))
3183
3184 (when tmp-post
3185 (save-excursion
3186 (goto-char tmp-post)
3187 (delete-char 1))
3188 (when hang-ender-stuck
3189 ;; Preserve point even if it's in the middle of the string
3190 ;; we replace; save-excursion doesn't work in that case.
3191 (setq here (point))
3192 (goto-char tmp-post)
3193 (skip-syntax-backward "^w ")
3194 (forward-char (- hang-ender-stuck))
3195 (insert-char ?\ hang-ender-stuck t)
3196 (delete-char hang-ender-stuck)
3197 (goto-char here))
3198 (set-marker tmp-post nil))
3199
3200 (set-marker end nil))))
3201
3202 (defun c-fill-paragraph (&optional arg)
3203 "Like \\[fill-paragraph] but handles C and C++ style comments.
3204 If any of the current line is a comment or within a comment, fill the
3205 comment or the paragraph of it that point is in, preserving the
3206 comment indentation or line-starting decorations (see the
3207 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
3208 details).
3209
3210 If point is inside multiline string literal, fill it. This currently
3211 does not respect escaped newlines, except for the special case when it
3212 is the very first thing in the string. The intended use for this rule
3213 is in situations like the following:
3214
3215 char description[] = \"\\
3216 A very long description of something that you want to fill to make
3217 nicely formatted output.\"\;
3218
3219 If point is in any other situation, i.e. in normal code, do nothing.
3220
3221 Optional prefix ARG means justify paragraph as well."
3222 (interactive "*P")
3223 (let ((fill-paragraph-function
3224 ;; Avoid infinite recursion.
3225 (if (not (eq fill-paragraph-function 'c-fill-paragraph))
3226 fill-paragraph-function)))
3227 (c-mask-paragraph t nil 'fill-paragraph arg))
3228 ;; Always return t. This has the effect that if filling isn't done
3229 ;; above, it isn't done at all, and it's therefore effectively
3230 ;; disabled in normal code.
3231 t)
3232
3233 (defun c-do-auto-fill ()
3234 ;; Do automatic filling if not inside a context where it should be
3235 ;; ignored.
3236 ;;
3237 ;; This function does not do any hidden buffer changes.
3238 (let ((c-auto-fill-prefix
3239 ;; The decision whether the line should be broken is actually
3240 ;; done in c-indent-new-comment-line, which do-auto-fill
3241 ;; calls to break lines. We just set this special variable
3242 ;; so that we'll know when we're called from there. It's
3243 ;; also used to detect whether fill-prefix is user set or
3244 ;; generated automatically by do-auto-fill.
3245 fill-prefix))
3246 (c-mask-paragraph nil t 'do-auto-fill)))
3247
3248 (defun c-indent-new-comment-line (&optional soft allow-auto-fill)
3249 "Break line at point and indent, continuing comment or macro if within one.
3250 If inside a comment and `comment-multi-line' is non-nil, the
3251 indentation and line prefix are preserved (see the
3252 `c-comment-prefix-regexp' and `c-block-comment-prefix' variables for
3253 details). If inside a single line comment and `comment-multi-line' is
3254 nil, a new comment of the same type is started on the next line and
3255 indented as appropriate for comments. If inside a macro, a line
3256 continuation backslash is inserted and aligned as appropriate, and the
3257 new line is indented according to `c-syntactic-indentation'.
3258
3259 If a fill prefix is specified, it overrides all the above."
3260 ;; allow-auto-fill is used from c-context-line-break to allow auto
3261 ;; filling to break the line more than once. Since this function is
3262 ;; used from auto-fill itself, that's normally disabled to avoid
3263 ;; unnecessary recursion.
3264 (interactive)
3265 (let ((fill-prefix fill-prefix)
3266 (do-line-break
3267 (lambda ()
3268 (delete-horizontal-space)
3269 (if soft
3270 (insert-and-inherit ?\n)
3271 (newline (if allow-auto-fill nil 1)))))
3272 ;; Already know the literal type and limits when called from
3273 ;; c-context-line-break.
3274 (c-lit-limits c-lit-limits)
3275 (c-lit-type c-lit-type)
3276 (c-macro-start c-macro-start))
3277 (when (not (eq c-auto-fill-prefix t))
3278 ;; Called from do-auto-fill.
3279 (unless c-lit-limits
3280 (setq c-lit-limits (c-literal-limits nil nil t)))
3281 (unless c-lit-type
3282 (setq c-lit-type (c-literal-type c-lit-limits)))
3283 (if (memq (cond ((c-query-and-set-macro-start) 'cpp)
3284 ((null c-lit-type) 'code)
3285 (t c-lit-type))
3286 c-ignore-auto-fill)
3287 (setq fill-prefix t) ; Used as flag in the cond.
3288 (if (and (null c-auto-fill-prefix)
3289 (eq c-lit-type 'c)
3290 (<= (c-point 'bol) (car c-lit-limits)))
3291 ;; The adaptive fill function has generated a prefix, but
3292 ;; we're on the first line in a block comment so it'll be
3293 ;; wrong. Ignore it to guess a better one below.
3294 (setq fill-prefix nil)
3295 (when (and (eq c-lit-type 'c++)
3296 (not (string-match "\\`[ \t]*//" (or fill-prefix ""))))
3297 ;; Kludge: If the function that adapted the fill prefix
3298 ;; doesn't produce the required comment starter for line
3299 ;; comments, then we ignore it.
3300 (setq fill-prefix nil)))
3301 ))
3302 (cond ((eq fill-prefix t)
3303 ;; A call from do-auto-fill which should be ignored.
3304 )
3305 (fill-prefix
3306 ;; A fill-prefix overrides anything.
3307 (funcall do-line-break)
3308 (insert-and-inherit fill-prefix))
3309 ((progn
3310 (unless c-lit-limits
3311 (setq c-lit-limits (c-literal-limits)))
3312 (unless c-lit-type
3313 (setq c-lit-type (c-literal-type c-lit-limits)))
3314 (memq c-lit-type '(c c++)))
3315 ;; Some sort of comment.
3316 (if (or comment-multi-line
3317 (save-excursion
3318 (goto-char (car c-lit-limits))
3319 (end-of-line)
3320 (< (point) (cdr c-lit-limits))))
3321 ;; Inside a comment that should be continued.
3322 (let ((fill (c-save-buffer-state nil
3323 (c-guess-fill-prefix
3324 (setq c-lit-limits
3325 (c-collect-line-comments c-lit-limits))
3326 c-lit-type)))
3327 (pos (point))
3328 (comment-text-end
3329 (or (and (eq c-lit-type 'c)
3330 (save-excursion
3331 (goto-char (- (cdr c-lit-limits) 2))
3332 (if (looking-at "\\*/") (point))))
3333 (cdr c-lit-limits))))
3334 ;; Skip forward past the fill prefix in case
3335 ;; we're standing in it.
3336 ;;
3337 ;; FIXME: This doesn't work well in cases like
3338 ;;
3339 ;; /* Bla bla bla bla bla
3340 ;; bla bla
3341 ;;
3342 ;; If point is on the 'B' then the line will be
3343 ;; broken after "Bla b".
3344 (while (and (< (current-column) (cdr fill))
3345 (not (eolp)))
3346 (forward-char 1))
3347 (if (and (> (point) comment-text-end)
3348 (> (c-point 'bol) (car c-lit-limits)))
3349 (progn
3350 ;; The skip takes us out of the (block)
3351 ;; comment; insert the fill prefix at bol
3352 ;; instead and keep the position.
3353 (setq pos (copy-marker pos t))
3354 (beginning-of-line)
3355 (insert-and-inherit (car fill))
3356 (if soft (insert-and-inherit ?\n) (newline 1))
3357 (goto-char pos)
3358 (set-marker pos nil))
3359 ;; Don't break in the middle of a comment starter
3360 ;; or ender.
3361 (cond ((> (point) comment-text-end)
3362 (goto-char comment-text-end))
3363 ((< (point) (+ (car c-lit-limits) 2))
3364 (goto-char (+ (car c-lit-limits) 2))))
3365 (funcall do-line-break)
3366 (insert-and-inherit (car fill))))
3367 ;; Inside a comment that should be broken.
3368 (let ((comment-start comment-start)
3369 (comment-end comment-end)
3370 col)
3371 (if (eq c-lit-type 'c)
3372 (unless (string-match "[ \t]*/\\*" comment-start)
3373 (setq comment-start "/* " comment-end " */"))
3374 (unless (string-match "[ \t]*//" comment-start)
3375 (setq comment-start "// " comment-end "")))
3376 (setq col (save-excursion
3377 (back-to-indentation)
3378 (current-column)))
3379 (funcall do-line-break)
3380 (when (and comment-end (not (equal comment-end "")))
3381 (forward-char -1)
3382 (insert-and-inherit comment-end)
3383 (forward-char 1))
3384 ;; c-comment-indent may look at the current
3385 ;; indentation, so let's start out with the same
3386 ;; indentation as the previous one.
3387 (indent-to col)
3388 (insert-and-inherit comment-start)
3389 (indent-for-comment))))
3390 ((c-query-and-set-macro-start)
3391 ;; In a macro.
3392 (unless (looking-at "[ \t]*\\\\$")
3393 ;; Do not clobber the alignment of the line continuation
3394 ;; slash; c-backslash-region might look at it.
3395 (delete-horizontal-space))
3396 ;; Got an asymmetry here: In normal code this command
3397 ;; doesn't indent the next line syntactically, and otoh a
3398 ;; normal syntactically indenting newline doesn't continue
3399 ;; the macro.
3400 (c-newline-and-indent (if allow-auto-fill nil 1)))
3401 (t
3402 ;; Somewhere else in the code.
3403 (let ((col (save-excursion
3404 (beginning-of-line)
3405 (while (and (looking-at "[ \t]*\\\\?$")
3406 (= (forward-line -1) 0)))
3407 (current-indentation))))
3408 (funcall do-line-break)
3409 (indent-to col))))))
3410
3411 (defalias 'c-comment-line-break-function 'c-indent-new-comment-line)
3412 (make-obsolete 'c-comment-line-break-function 'c-indent-new-comment-line)
3413
3414 ;; advice for indent-new-comment-line for older Emacsen
3415 (unless (boundp 'comment-line-break-function)
3416 (defvar c-inside-line-break-advice nil)
3417 (defadvice indent-new-comment-line (around c-line-break-advice
3418 activate preactivate)
3419 "Call `c-indent-new-comment-line' if in CC Mode."
3420 (if (or c-inside-line-break-advice
3421 (not c-buffer-is-cc-mode))
3422 ad-do-it
3423 (let ((c-inside-line-break-advice t))
3424 (c-indent-new-comment-line (ad-get-arg 0))))))
3425
3426 (defun c-context-line-break ()
3427 "Do a line break suitable to the context.
3428
3429 When point is outside a comment or macro, insert a newline and indent
3430 according to the syntactic context, unless `c-syntactic-indentation'
3431 is nil, in which case the new line is indented as the previous
3432 non-empty line instead.
3433
3434 When point is inside the content of a preprocessor directive, a line
3435 continuation backslash is inserted before the line break and aligned
3436 appropriately. The end of the cpp directive doesn't count as inside
3437 it.
3438
3439 When point is inside a comment, continue it with the appropriate
3440 comment prefix (see the `c-comment-prefix-regexp' and
3441 `c-block-comment-prefix' variables for details). The end of a
3442 C++-style line comment doesn't count as inside it."
3443 (interactive "*")
3444 (let* ((c-lit-limits (c-literal-limits nil nil t))
3445 (c-lit-type (c-literal-type c-lit-limits))
3446 (c-macro-start c-macro-start))
3447 (if (or (eq c-lit-type 'c)
3448 (and (eq c-lit-type 'c++)
3449 (< (save-excursion
3450 (skip-chars-forward " \t")
3451 (point))
3452 (1- (cdr (setq c-lit-limits
3453 (c-collect-line-comments c-lit-limits))))))
3454 (and (or (not (looking-at "\\s *$"))
3455 (eq (char-before) ?\\))
3456 (c-query-and-set-macro-start)
3457 (<= (save-excursion
3458 (goto-char c-macro-start)
3459 (if (looking-at c-opt-cpp-start)
3460 (goto-char (match-end 0)))
3461 (point))
3462 (point))))
3463 (let ((comment-multi-line t)
3464 (fill-prefix nil))
3465 (c-indent-new-comment-line nil t))
3466 (delete-horizontal-space)
3467 (newline)
3468 ;; c-indent-line may look at the current indentation, so let's
3469 ;; start out with the same indentation as the previous line.
3470 (let ((col (save-excursion
3471 (forward-line -1)
3472 (while (and (looking-at "[ \t]*\\\\?$")
3473 (= (forward-line -1) 0)))
3474 (current-indentation))))
3475 (indent-to col))
3476 (indent-according-to-mode))))
3477
3478 (defun c-context-open-line ()
3479 "Insert a line break suitable to the context and leave point before it.
3480 This is the `c-context-line-break' equivalent to `open-line', which is
3481 normally bound to C-o. See `c-context-line-break' for the details."
3482 (interactive "*")
3483 (let ((here (point)))
3484 (unwind-protect
3485 (progn
3486 ;; Temporarily insert a non-whitespace char to keep any
3487 ;; preceding whitespace intact.
3488 (insert ?x)
3489 (c-context-line-break))
3490 (goto-char here)
3491 (delete-char 1))))
3492
3493 \f
3494 (cc-provide 'cc-cmds)
3495
3496 ;;; arch-tag: bf0611dc-d1f4-449e-9e45-4ec7c6936677
3497 ;;; cc-cmds.el ends here