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