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