Initial Commit
[packages] / xemacs-packages / prog-modes / old-c-mode.el
1 ;;; old-c-mode.el --- Old and fast mode for C code in XEmacs
2
3 ;; Copyright (C) 1985, 86, 87, 92, 94, 95 Free Software Foundation, Inc.
4
5 ;; Maintainer: Ben Wing <ben@xemacs.org>
6 ;; Keywords: c
7
8 ;; This file is part of GNU Emacs.
9
10 ;; GNU Emacs is free software; you can redistribute it and/or modify
11 ;; it under the terms of the GNU General Public License as published by
12 ;; the Free Software Foundation; either version 2, or (at your option)
13 ;; any later version.
14
15 ;; GNU Emacs is distributed in the hope that it will be useful,
16 ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
17 ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
18 ;; GNU General Public License for more details.
19
20 ;; You should have received a copy of the GNU General Public License
21 ;; along with GNU Emacs; see the file COPYING.  If not, write to the
22 ;; Free Software Foundation, Inc., 59 Temple Place - Suite 330,
23 ;; Boston, MA 02111-1307, USA.
24
25 ;;; Commentary:
26
27 ;; Ported from GNU Emacs 20.7.
28
29 ;; cc-mode is dog-slow on large files, even on my 700 MHz Pentium III.
30 ;; This version works with no problems on the XEmacs source code and is
31 ;; very very fast.
32
33 ;;; Original commentary:
34
35 ;; [[A smart editing mode for C code.  It knows a lot about C syntax and tries
36 ;; to position the cursor according to C layout conventions.  You can
37 ;; change the details of the layout style with option variables.  Load it
38 ;; and do M-x describe-mode for details.]]
39
40 ;;; Code:
41 (defgroup old-c nil
42   "Old C code editing commands for Emacs."
43   ;; This group should have no parent.
44   ;; We don't want it to be loaded except on explicit request.
45   :prefix "c-")
46
47
48 (defvar c-mode-abbrev-table nil
49   "Abbrev table in use in C mode.")
50 (define-abbrev-table 'c-mode-abbrev-table ())
51
52 (defvar c-mode-map (make-sparse-keymap)
53   "Keymap used in C mode.")
54
55 (define-key c-mode-map "{" 'electric-c-brace)
56 (define-key c-mode-map "}" 'electric-c-brace)
57 (define-key c-mode-map ";" 'electric-c-semi)
58 (define-key c-mode-map "#" 'electric-c-sharp-sign)
59 (define-key c-mode-map ":" 'electric-c-terminator)
60 (define-key c-mode-map "\e\C-h" 'mark-c-function)
61 (define-key c-mode-map "\e\C-q" 'indent-c-exp)
62 (define-key c-mode-map "\ea" 'c-beginning-of-statement)
63 (define-key c-mode-map "\ee" 'c-end-of-statement)
64 (define-key c-mode-map "\C-c\C-n" 'c-forward-conditional)
65 (define-key c-mode-map "\C-c\C-p" 'c-backward-conditional)
66 (define-key c-mode-map "\C-c\C-u" 'c-up-conditional)
67 (define-key c-mode-map "\t" 'c-indent-command)
68 (define-key c-mode-map "\C-c\C-q"  'c-indent-defun)
69 (define-key c-mode-map "\C-c\C-\\" 'c-backslash-region)
70 (define-key c-mode-map "\C-c\C-c"  'comment-region)
71
72 (autoload 'c-macro-expand "cmacexp"
73   "Display the result of expanding all C macros occurring in the region.
74 The expansion is entirely correct because it uses the C preprocessor."
75   t)
76
77 ;;; begin stuff from cc-mode
78
79 (defun c-mode-menu (modestr)
80   (let ((m
81          '(["%_Comment Out Region"     comment-region
82             (c-fn-region-is-active-p)]
83            ["%_Uncomment Region"
84             (comment-region (region-beginning) (region-end) '(4))
85             (c-fn-region-is-active-p)]
86            ["%_Fill Comment Paragraph" c-fill-paragraph t]
87            "---"
88            ["%_Indent Expression"      c-indent-exp
89             (memq (char-after) '(?\( ?\[ ?\{))]
90            ["Indent %_Line or Region"  c-indent-line-or-region t]
91            ["U%_p Conditional"         c-up-conditional t]
92            ["B%_ackward Conditional"   c-backward-conditional t]
93            ["F%_orward Conditional"    c-forward-conditional t]
94            ["Insert Matching %_Endif"  c-insert-matching-endif t]
95            ["Bac%_kward Statement"     c-beginning-of-statement t]
96            ["Fo%_rward Statement"      c-end-of-statement t]
97            "---"
98            ["%_Macro Expand Region"    c-macro-expand (c-fn-region-is-active-p)]
99            ["%_Backslashify"           c-backslash-region
100             (c-fn-region-is-active-p)]
101            ["U%_nbackslashify"
102             (c-backslash-region (region-beginning) (region-end) '(4))
103             (c-fn-region-is-active-p)]
104            )))
105     (or (featurep 'menu-accelerator-support)
106         (setq m (mapcar #'(lambda (def)
107                             (if (vectorp def)
108                                 (aset def 0 (replace-in-string (aref def 0)
109                                                                "%_" "")))
110                             def)
111                         m)))
112     (cons modestr m)))
113
114 (defun c-populate-syntax-table (table)
115   ;; Populate the syntax TABLE
116   ;; DO NOT TRY TO SET _ (UNDERSCORE) TO WORD CLASS!
117   (modify-syntax-entry ?_  "_"     table)
118   (modify-syntax-entry ?\\ "\\"    table)
119   (modify-syntax-entry ?+  "."     table)
120   (modify-syntax-entry ?-  "."     table)
121   (modify-syntax-entry ?=  "."     table)
122   (modify-syntax-entry ?%  "."     table)
123   (modify-syntax-entry ?<  "."     table)
124   (modify-syntax-entry ?>  "."     table)
125   (modify-syntax-entry ?&  "."     table)
126   (modify-syntax-entry ?|  "."     table)
127   (modify-syntax-entry ?\' "\""    table)
128   ;; Set up block and line oriented comments.  The new C standard
129   ;; mandates both comment styles even in C, so since all languages
130   ;; now require dual comments, we make this the default.
131   (cond
132    ;; XEmacs 19 & 20
133    ((memq '8-bit c-emacs-features)
134     (modify-syntax-entry ?/  ". 1456" table)
135     (modify-syntax-entry ?*  ". 23"   table))
136    ;; Emacs 19 & 20
137    ((memq '1-bit c-emacs-features)
138     (modify-syntax-entry ?/  ". 124b" table)
139     (modify-syntax-entry ?*  ". 23"   table))
140    ;; incompatible
141    (t (error "CC Mode is incompatible with this version of Emacs"))
142    )
143   (modify-syntax-entry ?\n "> b"  table)
144   ;; Give CR the same syntax as newline, for selective-display
145   (modify-syntax-entry ?\^m "> b" table))
146
147 (defvar c-mode-syntax-table nil
148   "Syntax table used in c-mode buffers.")
149 (if c-mode-syntax-table
150     ()
151   (setq c-mode-syntax-table (make-syntax-table))
152   (c-populate-syntax-table c-mode-syntax-table))
153
154 (defvar c-current-comment-prefix nil
155   "The current comment prefix regexp.
156 Set from `c-comment-prefix-regexp' at mode initialization.")
157 (make-variable-buffer-local 'c-current-comment-prefix)
158
159 ;(defcustom-c-stylevar c-comment-prefix-regexp
160 (defcustom c-comment-prefix-regexp
161   '((pike-mode . "//+!?\\|\\**")
162     (other . "//+\\|\\**"))
163   "*Regexp to match the line prefix inside comments.
164 This regexp is used to recognize the fill prefix inside comments for
165 correct paragraph filling and other things.
166
167 If this variable is a string, it will be used in all CC Mode major
168 modes.  It can also be an association list, to associate specific
169 regexps to specific major modes.  The symbol for the major mode is
170 looked up in the association list, and its value is used as the line
171 prefix regexp.  If it's not found, then the symbol `other' is looked
172 up and its value is used instead.
173
174 The regexp should match the prefix used in both C++ style line
175 comments and C style block comments, but it does not need to match a
176 block comment starter.  In other words, it should at least match
177 \"//\" for line comments and the string in `c-block-comment-prefix',
178 which is sometimes inserted by CC Mode inside block comments.  It
179 should not match any surrounding whitespace.
180
181 Note that CC Mode modifies other variables from this one at mode
182 initialization, so you will need to do \\[c-mode] (or whatever mode
183 you're currently using) if you change it in a CC Mode buffer."
184   :type '(radio
185           (regexp :tag "Regexp for all modes")
186           (list
187            :tag "Mode-specific regexps"
188            (set
189             :inline t :format "%v"
190             (cons :format "%v"
191                   (const :format "C     " c-mode) (regexp :format "%v"))
192             (cons :format "%v"
193                   (const :format "C++   " c++-mode) (regexp :format "%v"))
194             (cons :format "%v"
195                   (const :format "ObjC  " objc-mode) (regexp :format "%v"))
196             (cons :format "%v"
197                   (const :format "Java  " java-mode) (regexp :format "%v"))
198             (cons :format "%v"
199                   (const :format "IDL   " idl-mode) (regexp :format "%v"))
200             (cons :format "%v"
201                   (const :format "Pike  " pike-mode) (regexp :format "%v")))
202            (cons :format "    %v"
203                  (const :format "Other " other) (regexp :format "%v"))))
204   :group 'old-c)
205
206 (defvar c-append-paragraph-start "$")
207 (make-variable-buffer-local 'c-append-paragraph-start)
208 (defconst c-Java-javadoc-paragraph-start
209   "\\(@[a-zA-Z]+\\>\\|$\\)")
210 (defconst c-Pike-pikedoc-paragraph-start
211   "\\(@[a-zA-Z]+\\>\\([^{]\\|$\\)\\|$\\)")
212
213 ;; Regexp to append to paragraph-separate.
214 (defvar c-append-paragraph-separate "$")
215 (make-variable-buffer-local 'c-append-paragraph-separate)
216 (defconst c-Pike-pikedoc-paragraph-separate c-Pike-pikedoc-paragraph-start)
217
218 ;;; end stuff from cc-mode
219
220 (defcustom c-indent-level 2
221   "*Indentation of C statements with respect to containing block."
222   :type 'integer
223   :group 'old-c)
224 (defcustom c-brace-imaginary-offset 0
225   "*Imagined indentation of a C open brace that actually follows a statement."
226   :type 'integer
227   :group 'old-c)
228 (defcustom c-brace-offset 0
229   "*Extra indentation for braces, compared with other text in same context."
230   :type 'integer
231   :group 'old-c)
232 (defcustom c-argdecl-indent 5
233   "*Indentation level of declarations of C function arguments."
234   :type 'integer
235   :group 'old-c)
236 (defcustom c-label-offset -2
237   "*Offset of C label lines and case statements relative to usual indentation."
238   :type 'integer
239   :group 'old-c)
240 (defcustom c-continued-statement-offset 2
241   "*Extra indent for lines not starting new statements."
242   :type 'integer
243   :group 'old-c)
244 (defcustom c-continued-brace-offset 0
245   "*Extra indent for substatements that start with open-braces.
246 This is in addition to `c-continued-statement-offset'."
247   :type 'integer
248   :group 'old-c)
249 (defconst c-style-alist
250   '(("GNU"
251      (c-indent-level               .  2)
252      (c-argdecl-indent             .  5)
253      (c-brace-offset               .  0)
254      (c-continued-brace-offset     .  0)
255      (c-label-offset               . -2)
256      (c-continued-statement-offset .  2))
257     ("K&R"
258      (c-indent-level               .  5)
259      (c-argdecl-indent             .  0)
260      (c-brace-offset               .  0)
261      (c-continued-brace-offset     . -5)
262      (c-label-offset               . -5)
263      (c-continued-statement-offset .  5))
264     ("BSD"
265      (c-indent-level               .  4)
266      (c-argdecl-indent             .  4)
267      (c-brace-offset               .  0)
268      (c-continued-brace-offset     . -4)
269      (c-label-offset               . -4)
270      (c-continued-statement-offset .  4))
271     ("C++"
272      (c-indent-level               .  4)
273      (c-argdecl-indent             .  0)
274      (c-brace-offset               .  0)
275      (c-continued-brace-offset     . -4)
276      (c-label-offset               . -4)
277      (c-continued-statement-offset .  4)
278      (c-auto-newline               .  t))
279     ("Whitesmith"
280      (c-indent-level               .  4)
281      (c-argdecl-indent             .  4)
282      (c-brace-offset               .  0)
283      (c-continued-brace-offset     .  0)
284      (c-label-offset               . -4)
285      (c-continued-statement-offset .  4))))
286
287 (defcustom c-auto-newline nil
288   "*Non-nil means automatically newline before and after braces,
289 and after colons and semicolons, inserted in C code.
290 If you do not want a leading newline before braces then use:
291   (define-key c-mode-map \"{\" 'electric-c-semi)"
292   :type 'boolean
293   :group 'old-c)
294
295 (defcustom c-tab-always-indent t
296   "*Non-nil means TAB in C mode should always reindent the current line,
297 regardless of where in the line point is when the TAB command is used."
298   :type 'boolean
299   :group 'old-c)
300
301 ;;; Regular expression used internally to recognize labels in switch
302 ;;; statements.
303 (defconst c-switch-label-regexp "case[ \t'/(]\\|default[ \t]*:")
304
305 ;; This is actually the expression for C++ mode, but it's used for C too.
306 (defvar c-imenu-generic-expression
307   (`
308    ((nil
309      (,
310       (concat
311        "^"                                ; beginning of line is required
312        "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
313        "\\([a-zA-Z0-9_:]+[ \t]+\\)?"      ; type specs; there can be no
314        "\\([a-zA-Z0-9_:]+[ \t]+\\)?"      ; more than 3 tokens, right?
315
316        "\\("                              ; last type spec including */&
317        "[a-zA-Z0-9_:]+"
318        "\\([ \t]*[*&]+[ \t]*\\|[ \t]+\\)"         ; either pointer/ref sign or whitespace
319        "\\)?"                             ; if there is a last type spec
320        "\\("                          ; name; take that into the imenu entry
321        "[a-zA-Z0-9_:~]+"                      ; member function, ctor or dtor...
322                                         ; (may not contain * because then
323                                         ; "a::operator char*" would become "char*"!)
324        "\\|"
325        "\\([a-zA-Z0-9_:~]*::\\)?operator"
326        "[^a-zA-Z1-9_][^(]*"           ; ...or operator
327        " \\)"
328        "[ \t]*([^)]*)[ \t\n]*[^       ;]" ; require something other than a ; after
329                                         ; the (...) to avoid prototypes.  Can't
330                                         ; catch cases with () inside the parentheses
331                                         ; surrounding the parameters
332                                         ; (like "int foo(int a=bar()) {...}"
333
334        )) 6)
335     ("Class"
336      (, (concat
337          "^"                               ; beginning of line is required
338          "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
339          "class[ \t]+"
340          "\\([a-zA-Z0-9_]+\\)"                ; this is the string we want to get
341          "[ \t]*[:{]"
342          )) 2)
343 ;; Example of generic expression for finding prototypes, structs, unions, enums.
344 ;; Uncomment if you want to find these too.  It will be a bit slower gathering
345 ;; the indexes.
346 ;    ("Prototypes"
347 ;     (,
348 ;      (concat
349 ;       "^"                               ; beginning of line is required
350 ;       "\\(template[ \t]*<[^>]+>[ \t]*\\)?" ; there may be a "template <...>"
351 ;       "\\([a-zA-Z0-9_:]+[ \t]+\\)?"     ; type specs; there can be no
352 ;       "\\([a-zA-Z0-9_:]+[ \t]+\\)?"     ; more than 3 tokens, right?
353
354 ;       "\\("                             ; last type spec including */&
355 ;       "[a-zA-Z0-9_:]+"
356 ;       "\\([ \t]*[*&]+[ \t]*\\|[ \t]+\\)"        ; either pointer/ref sign or whitespace
357 ;       "\\)?"                            ; if there is a last type spec
358 ;       "\\("                         ; name; take that into the imenu entry
359 ;       "[a-zA-Z0-9_:~]+"                     ; member function, ctor or dtor...
360 ;                                       ; (may not contain * because then
361 ;                                       ; "a::operator char*" would become "char*"!)
362 ;       "\\|"
363 ;       "\\([a-zA-Z0-9_:~]*::\\)?operator"
364 ;       "[^a-zA-Z1-9_][^(]*"          ; ...or operator
365 ;       " \\)"
366 ;       "[ \t]*([^)]*)[ \t\n]*;"        ; require ';' after
367 ;                                       ; the (...) Can't
368 ;                                       ; catch cases with () inside the parentheses
369 ;                                       ; surrounding the parameters
370 ;                                       ; (like "int foo(int a=bar());"
371 ;       )) 6)
372 ;    ("Struct"
373 ;     (, (concat
374 ;        "^"                            ; beginning of line is required
375 ;        "\\(static[ \t]+\\)?"          ; there may be static or const.
376 ;        "\\(const[ \t]+\\)?"
377 ;        "struct[ \t]+"
378 ;        "\\([a-zA-Z0-9_]+\\)"          ; this is the string we want to get
379 ;        "[ \t]*[{]"
380 ;        )) 3)
381 ;    ("Enum"
382 ;     (, (concat
383 ;        "^"                            ; beginning of line is required
384 ;        "\\(static[ \t]+\\)?"          ; there may be static or const.
385 ;        "\\(const[ \t]+\\)?"
386 ;        "enum[ \t]+"
387 ;        "\\([a-zA-Z0-9_]+\\)"          ; this is the string we want to get
388 ;        "[ \t]*[{]"
389 ;        )) 3)
390 ;    ("Union"
391 ;     (, (concat
392 ;        "^"                            ; beginning of line is required
393 ;        "\\(static[ \t]+\\)?"          ; there may be static or const.
394 ;        "\\(const[ \t]+\\)?"
395 ;        "union[ \t]+"
396 ;        "\\([a-zA-Z0-9_]+\\)"          ; this is the string we want to get
397 ;        "[ \t]*[{]"
398 ;        )) 3)
399     ))
400   "Imenu generic expression for C mode.  See `imenu-generic-expression'.")
401 \f
402 (defun c-mode ()
403   "Major mode for editing C code.
404 Expression and list commands understand all C brackets.
405 Tab indents for C code.
406 Comments are delimited with /* ... */.
407 Paragraphs are separated by blank lines only.
408 Delete converts tabs to spaces as it moves back.
409 \\{c-mode-map}
410 Variables controlling indentation style:
411  c-tab-always-indent
412     Non-nil means TAB in C mode should always reindent the current line,
413     regardless of where in the line point is when the TAB command is used.
414  c-auto-newline
415     Non-nil means automatically newline before and after braces,
416     and after colons and semicolons, inserted in C code.
417  c-indent-level
418     Indentation of C statements within surrounding block.
419     The surrounding block's indentation is the indentation
420     of the line on which the open-brace appears.
421  c-continued-statement-offset
422     Extra indentation given to a substatement, such as the
423     then-clause of an if or body of a while.
424  c-continued-brace-offset
425     Extra indentation given to a brace that starts a substatement.
426     This is in addition to c-continued-statement-offset.
427  c-brace-offset
428     Extra indentation for line if it starts with an open brace.
429  c-brace-imaginary-offset
430     An open brace following other text is treated as if it were
431     this far to the right of the start of its line.
432  c-argdecl-indent
433     Indentation level of declarations of C function arguments.
434  c-label-offset
435     Extra indentation for line that is a label, or case or default.
436
437 Settings for K&R and BSD indentation styles are
438   c-indent-level                5    8
439   c-continued-statement-offset  5    8
440   c-brace-offset               -5   -8
441   c-argdecl-indent              0    8
442   c-label-offset               -5   -8
443
444 Turning on C mode calls the value of the variable c-mode-hook with no args,
445 if that value is non-nil."
446   (interactive)
447   (kill-all-local-variables)
448   (use-local-map c-mode-map)
449   (setq major-mode 'c-mode)
450   (setq mode-name "C")
451
452 ;;; begin stuff from cc-mode
453
454   (make-local-variable 'require-final-newline)
455   (make-local-variable 'parse-sexp-ignore-comments)
456   (make-local-variable 'indent-line-function)
457   (make-local-variable 'indent-region-function)
458   (make-local-variable 'outline-regexp)
459   (make-local-variable 'outline-level)
460   (make-local-variable 'normal-auto-fill-function)
461   (make-local-variable 'comment-start)
462   (make-local-variable 'comment-end)
463   (make-local-variable 'comment-column)
464   (make-local-variable 'comment-start-skip)
465   (make-local-variable 'comment-multi-line)
466   (make-local-variable 'paragraph-start)
467   (make-local-variable 'paragraph-separate)
468   (make-local-variable 'paragraph-ignore-fill-prefix)
469   (make-local-variable 'adaptive-fill-mode)
470   (make-local-variable 'adaptive-fill-regexp)
471   (make-local-variable 'imenu-generic-expression) ;set in the mode functions
472 ;   ;; X/Emacs 20 only
473 ;   (and (boundp 'comment-line-break-function)
474 ;        (progn
475 ;        (make-local-variable 'comment-line-break-function)
476 ;        (setq comment-line-break-function
477 ;              'c-indent-new-comment-line)))
478   ;; now set their values
479   (setq require-final-newline t
480         parse-sexp-ignore-comments t
481         indent-line-function 'c-indent-line
482         indent-region-function 'c-indent-region
483         outline-regexp "[^#\n\^M]"
484         outline-level 'c-outline-level
485         normal-auto-fill-function 'c-do-auto-fill
486         comment-column 32
487         comment-start-skip "/\\*+ *\\|//+ *"
488         comment-multi-line t)
489 ;   ;; now set the mode style based on c-default-style
490 ;   (let ((style (if (stringp c-default-style)
491 ;                  c-default-style
492 ;                (or (cdr (assq major-mode c-default-style))
493 ;                    (cdr (assq 'other c-default-style))
494 ;                    "gnu"))))
495 ;     ;; Override style variables if `c-old-style-variable-behavior' is
496 ;     ;; set.  Also override if we are using global style variables,
497 ;     ;; have already initialized a style once, and are switching to a
498 ;     ;; different style.  (It's doubtful whether this is desirable, but
499 ;     ;; the whole situation with nonlocal style variables is a bit
500 ;     ;; awkward.  It's at least the most compatible way with the old
501 ;     ;; style init procedure.)
502 ;     (c-set-style style (not (or c-old-style-variable-behavior
503 ;                               (and (not c-style-variables-are-local-p)
504 ;                                    c-indentation-style
505 ;                                    (not (string-equal c-indentation-style
506 ;                                                       style)))))))
507   ;; Fix things up for paragraph recognition and filling inside
508   ;; comments by using c-current-comment-prefix in the relevant
509   ;; places.  We use adaptive filling for this to make it possible to
510   ;; use filladapt or some other fancy package.
511   (setq c-current-comment-prefix
512         (if (listp c-comment-prefix-regexp)
513             (cdr-safe (or (assoc major-mode c-comment-prefix-regexp)
514                           (assoc 'other c-comment-prefix-regexp)))
515           c-comment-prefix-regexp))
516   (let ((comment-line-prefix
517          (concat "[ \t]*\\(" c-current-comment-prefix "\\)[ \t]*")))
518     (setq paragraph-start (concat comment-line-prefix
519                                   c-append-paragraph-start
520                                   "\\|"
521                                   page-delimiter)
522           paragraph-separate (concat comment-line-prefix
523                                      c-append-paragraph-separate
524                                      "\\|"
525                                      page-delimiter)
526           paragraph-ignore-fill-prefix t
527           adaptive-fill-mode t
528           adaptive-fill-regexp
529           (concat comment-line-prefix
530                   (if adaptive-fill-regexp
531                       (concat "\\(" adaptive-fill-regexp "\\)")
532                     "")))
533     (when (boundp 'adaptive-fill-first-line-regexp)
534       ;; XEmacs (20.x) adaptive fill mode doesn't have this.
535       (make-local-variable 'adaptive-fill-first-line-regexp)
536       (setq adaptive-fill-first-line-regexp
537             (concat "\\`" comment-line-prefix
538                     ;; Maybe we should incorporate the old value here,
539                     ;; but then we have to do all sorts of kludges to
540                     ;; deal with the \` and \' it probably contains.
541                     "\\'"))))
542 ;   ;; we have to do something special for c-offsets-alist so that the
543 ;   ;; buffer local value has its own alist structure.
544 ;   (setq c-offsets-alist (copy-alist c-offsets-alist))
545   ;; setup the comment indent variable in a Emacs version portable way
546   ;; ignore any byte compiler warnings you might get here
547   (make-local-variable 'comment-indent-function)
548   (setq comment-indent-function 'c-comment-indent)
549   ;; add menus to menubar
550   (easy-menu-add (c-mode-menu mode-name))
551 ;   ;; put auto-hungry designators onto minor-mode-alist, but only once
552 ;   (or (assq 'c-auto-hungry-string minor-mode-alist)
553 ;       (setq minor-mode-alist
554 ;           (cons '(c-auto-hungry-string c-auto-hungry-string)
555 ;                 minor-mode-alist)))
556
557 ;;; end stuff from cc-mode
558
559   (setq local-abbrev-table c-mode-abbrev-table)
560   (set-syntax-table c-mode-syntax-table)
561   (make-local-variable 'fill-paragraph-function)
562   (setq fill-paragraph-function 'c-fill-paragraph)
563   (setq comment-start "/* ")
564   (setq comment-end " */")
565   (make-local-variable 'imenu-generic-expression)
566   (setq imenu-generic-expression c-imenu-generic-expression)
567   (run-hooks 'c-mode-hook))
568
569 (defun c-outline-level ()
570   ;; This so that `current-column' DTRT in otherwise-hidden text.
571   (let (buffer-invisibility-spec)
572     (save-excursion
573       (skip-chars-forward "\t ")
574       (current-column))))
575 \f
576 ;; This is used by indent-for-comment
577 ;; to decide how much to indent a comment in C code
578 ;; based on its context.
579 (defun c-comment-indent ()
580   (if (looking-at "^/\\*")
581       0                         ;Existing comment at bol stays there.
582     (let ((opoint (point)))
583       (save-excursion
584         (beginning-of-line)
585         (cond ((looking-at "[ \t]*}[ \t]*\\($\\|/\\*\\)")
586                ;; A comment following a solitary close-brace
587                ;; should have only one space.
588                (search-forward "}")
589                (1+ (current-column)))
590               ((or (looking-at "^#[ \t]*endif[ \t]*")
591                    (looking-at "^#[ \t]*else[ \t]*"))
592                7)                       ;2 spaces after #endif
593               ((progn
594                  (goto-char opoint)
595                  (skip-chars-backward " \t")
596                  (and (= comment-column 0) (bolp)))
597                ;; If comment-column is 0, and nothing but space
598                ;; before the comment, align it at 0 rather than 1.
599                0)
600               (t
601                (max (1+ (current-column))       ;Else indent at comment column
602                     comment-column)))))))       ; except leave at least one space.
603
604 (defun c-fill-paragraph (&optional arg)
605   "Like \\[fill-paragraph] but handle C comments.
606 If any of the current line is a comment or within a comment,
607 fill the comment or the paragraph of it that point is in,
608 preserving the comment indentation or line-starting decorations."
609   (interactive "P")
610   (let* (comment-start-place
611          (first-line
612           ;; Check for obvious entry to comment.
613           (save-excursion
614             (beginning-of-line)
615             (skip-chars-forward " \t\n")
616             (and (looking-at comment-start-skip)
617                  (setq comment-start-place (point))))))
618     (if (and (eq major-mode 'c++-mode)
619              (save-excursion
620                (beginning-of-line)
621                (looking-at ".*//")))
622         (let (fill-prefix
623               (paragraph-start
624                ;; Lines containing just a comment start or just an end
625                ;; should not be filled into paragraphs they are next to.
626                (concat
627                 paragraph-start
628                 "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$"))
629               (paragraph-separate
630                (concat
631                 paragraph-separate
632                 "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$")))
633           (save-excursion
634             (beginning-of-line)
635             ;; Move up to first line of this comment.
636             (while (and (not (bobp)) (looking-at "[ \t]*//"))
637               (forward-line -1))
638             (if (not (looking-at ".*//"))
639                 (forward-line 1))
640             ;; Find the comment start in this line.
641             (re-search-forward "[ \t]*//[ \t]*")
642             ;; Set the fill-prefix to be what all lines except the first
643             ;; should start with.
644             (let ((endcol (current-column)))
645               (skip-chars-backward " \t")
646               (setq fill-prefix
647                     (concat (make-string (- (current-column) 2) ?\ )
648                             "//"
649                             (make-string (- endcol (current-column)) ?\ ))))
650             (save-restriction
651               ;; Narrow down to just the lines of this comment.
652               (narrow-to-region (point)
653                                 (save-excursion
654                                   (forward-line 1)
655                                   (while (looking-at "[ \t]*//")
656                                     (forward-line 1))
657                                   (point)))
658               (insert fill-prefix)
659               (fill-paragraph arg)
660               (delete-region (point-min)
661                              (+ (point-min) (length fill-prefix))))))
662       (if (or first-line
663               ;; t if we enter a comment between start of function and this line.
664               (eq (calculate-c-indent) t)
665               ;; t if this line contains a comment starter.
666               (setq first-line
667                     (save-excursion
668                       (beginning-of-line)
669                       (prog1
670                           (re-search-forward comment-start-skip
671                                              (save-excursion (end-of-line)
672                                                              (point))
673                                              t)
674                         (setq comment-start-place (point))))))
675           ;; Inside a comment: fill one comment paragraph.
676           (let ((fill-prefix
677                  ;; The prefix for each line of this paragraph
678                  ;; is the appropriate part of the start of this line,
679                  ;; up to the column at which text should be indented.
680                  (save-excursion
681                    (beginning-of-line)
682                    (if (looking-at "[ \t]*/\\*.*\\*/")
683                        (progn (re-search-forward comment-start-skip)
684                               (make-string (current-column) ?\ ))
685                      (if first-line (forward-line 1))
686
687                      (let ((line-width (progn (end-of-line) (current-column))))
688                        (beginning-of-line)
689                        (prog1
690                            (buffer-substring
691                             (point)
692
693                             ;; How shall we decide where the end of the
694                             ;; fill-prefix is?
695                             ;; calculate-c-indent-within-comment bases its value
696                             ;; on the indentation of previous lines; if they're
697                             ;; indented specially, it could return a column
698                             ;; that's well into the current line's text.  So
699                             ;; we'll take at most that many space, tab, or *
700                             ;; characters, and use that as our fill prefix.
701                             (let ((max-prefix-end
702                                    (progn
703                                      (move-to-column
704                                       (calculate-c-indent-within-comment t)
705                                       t)
706                                      (point))))
707                               (beginning-of-line)
708                               (skip-chars-forward " \t*" max-prefix-end)
709                               ;; Don't include part of comment terminator
710                               ;; in the fill-prefix.
711                               (and (eq (following-char) ?/)
712                                    (eq (preceding-char) ?*)
713                                    (backward-char 1))
714                               (point)))
715
716                          ;; If the comment is only one line followed by a blank
717                          ;; line, calling move-to-column above may have added
718                          ;; some spaces and tabs to the end of the line; the
719                          ;; fill-paragraph function will then delete it and the
720                          ;; newline following it, so we'll lose a blank line
721                          ;; when we shouldn't.  So delete anything
722                          ;; move-to-column added to the end of the line.  We
723                          ;; record the line width instead of the position of the
724                          ;; old line end because move-to-column might break a
725                          ;; tab into spaces, and the new characters introduced
726                          ;; there shouldn't be deleted.
727
728                          ;; If you can see a better way to do this, please make
729                          ;; the change.  This seems very messy to me.
730                          (delete-region (progn (move-to-column line-width)
731                                                (point))
732                                         (progn (end-of-line) (point))))))))
733
734                 (paragraph-start
735                  ;; Lines containing just a comment start or just an end
736                  ;; should not be filled into paragraphs they are next to.
737                  (concat
738                   paragraph-start
739                   "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$"))
740                 (paragraph-separate
741                  (concat
742                   paragraph-separate
743                   "\\|[ \t]*/\\*[ \t]*$\\|[ \t]*\\*/[ \t]*$\\|[ \t/*]*$"))
744                 (chars-to-delete 0))
745             (save-restriction
746               ;; Don't fill the comment together with the code following it.
747               ;; So temporarily exclude everything before the comment start,
748               ;; and everything after the line where the comment ends.
749               ;; If comment-start-place is non-nil, the comment starter is there.
750               ;; Otherwise, point is inside the comment.
751               (narrow-to-region (save-excursion
752                                   (if comment-start-place
753                                       (goto-char comment-start-place)
754                                     (search-backward "/*"))
755                                   ;; Protect text before the comment start
756                                   ;; by excluding it.  Add spaces to bring back
757                                   ;; proper indentation of that point.
758                                   (let ((column (current-column)))
759                                     (prog1 (point)
760                                       (setq chars-to-delete column)
761                                       (insert-char ?\  column))))
762                                 (save-excursion
763                                   (if comment-start-place
764                                       (goto-char (+ comment-start-place 2)))
765                                   (search-forward "*/" nil 'move)
766                                   (forward-line 1)
767                                   (point)))
768               (save-excursion
769                 (goto-char (point-max))
770                 (forward-line -1)
771                 ;; And comment terminator was on a separate line before,
772                 ;; keep it that way.
773                 ;; This also avoids another problem:
774                 ;; if the fill-prefix ends in a *, it could eat up
775                 ;; the * of the comment terminator.
776                 (if (looking-at "[ \t]*\\*/")
777                     (narrow-to-region (point-min) (point))))
778               (fill-paragraph arg)
779               (save-excursion
780                 ;; Delete the chars we inserted to avoid clobbering
781                 ;; the stuff before the comment start.
782                 (goto-char (point-min))
783                 (if (> chars-to-delete 0)
784                     (delete-region (point) (+ (point) chars-to-delete)))
785                 ;; Find the comment ender (should be on last line of buffer,
786                 ;; given the narrowing) and don't leave it on its own line.
787                 ;; Do this with a fill command, so as to preserve sentence
788                 ;; boundaries.
789                 (goto-char (point-max))
790                 (forward-line -1)
791                 (search-forward "*/" nil 'move)
792                 (beginning-of-line)
793                 (if (looking-at "[ \t]*\\*/")
794                     (let ((fill-column (+ fill-column 9999)))
795                       (forward-line -1)
796                       (fill-region-as-paragraph (point) (point-max)))))))
797         ;; Outside of comments: do ordinary filling.
798         (fill-paragraph arg)))
799     t))
800
801 (defun electric-c-brace (arg)
802   "Insert character and correct line's indentation."
803   (interactive "P")
804   (let (insertpos)
805     (if (and (not arg)
806              (eolp)
807              (or (save-excursion
808                    (skip-chars-backward " \t")
809                    (bolp))
810                  (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
811         (progn
812           (insert last-command-char)
813           (c-indent-line)
814           (if c-auto-newline
815               (progn
816                 (newline)
817                 ;; (newline) may have done auto-fill
818                 (setq insertpos (- (point) 2))
819                 (c-indent-line)))
820           (save-excursion
821             (if insertpos (goto-char (1+ insertpos)))
822             (delete-char -1))))
823     (if insertpos
824         (save-excursion
825           (goto-char insertpos)
826           (self-insert-command (prefix-numeric-value arg)))
827       (self-insert-command (prefix-numeric-value arg)))))
828
829 (defun electric-c-sharp-sign (arg)
830   "Insert character and correct line's indentation."
831   (interactive "P")
832   (if (save-excursion
833         (skip-chars-backward " \t")
834         (bolp))
835       (let ((c-auto-newline nil))
836         (electric-c-terminator arg))
837     (self-insert-command (prefix-numeric-value arg))))
838
839 (defun electric-c-semi (arg)
840   "Insert character and correct line's indentation."
841   (interactive "P")
842   (if c-auto-newline
843       (electric-c-terminator arg)
844     (self-insert-command (prefix-numeric-value arg))))
845
846 (defun electric-c-terminator (arg)
847   "Insert character and correct line's indentation."
848   (interactive "P")
849   (let (insertpos (end (point)))
850     (if (and (not arg) (eolp)
851              (not (save-excursion
852                     (beginning-of-line)
853                     (skip-chars-forward " \t")
854                     (or (= (following-char) ?#)
855                         ;; Colon is special only after a label, or case ....
856                         ;; So quickly rule out most other uses of colon
857                         ;; and do no indentation for them.
858                         (and (eq last-command-char ?:)
859                              (not (looking-at c-switch-label-regexp))
860                              (save-excursion
861                                (skip-chars-forward "a-zA-Z0-9_$")
862                                (skip-chars-forward " \t")
863                                (< (point) end)))
864                         (progn
865                           (beginning-of-defun)
866                           (let ((pps (parse-partial-sexp (point) end)))
867                             (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
868         (progn
869           (insert last-command-char)
870           (c-indent-line)
871           (and c-auto-newline
872                (not (c-inside-parens-p))
873                (progn
874                  (newline)
875                  ;; (newline) may have done auto-fill
876                  (setq insertpos (- (point) 2))
877                  (c-indent-line)))
878           (save-excursion
879             (if insertpos (goto-char (1+ insertpos)))
880             (delete-char -1))))
881     (if insertpos
882         (save-excursion
883           (goto-char insertpos)
884           (self-insert-command (prefix-numeric-value arg)))
885       (self-insert-command (prefix-numeric-value arg)))))
886
887 (defun c-inside-parens-p ()
888   (condition-case ()
889       (save-excursion
890         (save-restriction
891           (narrow-to-region (point)
892                             (progn (beginning-of-defun) (point)))
893           (goto-char (point-max))
894           (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
895     (error nil)))
896 \f
897 (defun c-indent-command (&optional whole-exp)
898   "Indent current line as C code, or in some cases insert a tab character.
899 If `c-tab-always-indent' is non-nil (the default), always indent current line.
900 Otherwise, indent the current line only if point is at the left margin or
901 in the line's indentation; otherwise insert a tab.
902
903 A numeric argument, regardless of its value, means indent rigidly all the
904 lines of the expression starting after point so that this line becomes
905 properly indented.  The relative indentation among the lines of the
906 expression are preserved."
907   (interactive "P")
908   (if whole-exp
909       ;; If arg, always indent this line as C
910       ;; and shift remaining lines of expression the same amount.
911       (let ((shift-amt (c-indent-line))
912             beg end)
913         (save-excursion
914           (if c-tab-always-indent
915               (beginning-of-line))
916           ;; Find beginning of following line.
917           (save-excursion
918             (forward-line 1) (setq beg (point)))
919           ;; Find first beginning-of-sexp for sexp extending past this line.
920           (while (< (point) beg)
921             (forward-sexp 1)
922             (setq end (point))
923             (skip-chars-forward " \t\n")))
924         (if (> end beg)
925             (indent-code-rigidly beg end shift-amt "#")))
926     (if (and (not c-tab-always-indent)
927              (save-excursion
928                (skip-chars-backward " \t")
929                (not (bolp))))
930         (insert-tab)
931       (c-indent-line))))
932
933 (defun c-indent-line ()
934   "Indent current line as C code.
935 Return the amount the indentation changed by."
936   (let ((indent (calculate-c-indent nil))
937         beg shift-amt
938         (case-fold-search nil)
939         (pos (- (point-max) (point))))
940     (beginning-of-line)
941     (setq beg (point))
942     (cond ((eq indent nil)
943            (setq indent (current-indentation)))
944           ((eq indent t)
945            (setq indent (calculate-c-indent-within-comment)))
946           ((looking-at "[ \t]*#")
947            (setq indent 0))
948           (t
949            (skip-chars-forward " \t")
950            (if (listp indent) (setq indent (car indent)))
951            (cond ((or (looking-at c-switch-label-regexp)
952                       (and (looking-at "[A-Za-z]")
953                            (save-excursion
954                              (forward-sexp 1)
955                              (looking-at ":"))))
956                   (setq indent (max 1 (+ indent c-label-offset))))
957                  ((and (looking-at "else\\b")
958                        (not (looking-at "else\\s_")))
959                   (setq indent (save-excursion
960                                  (c-backward-to-start-of-if)
961                                  (current-indentation))))
962                  ((and (looking-at "}[ \t]*else\\b")
963                        (not (looking-at "}[ \t]*else\\s_")))
964                   (setq indent (save-excursion
965                                  (forward-char)
966                                  (backward-sexp)
967                                  (c-backward-to-start-of-if)
968                                  (current-indentation))))
969                  ((and (looking-at "while\\b")
970                        (not (looking-at "while\\s_"))
971                        (save-excursion
972                          (c-backward-to-start-of-do)))
973                   ;; This is a `while' that ends a do-while.
974                   (setq indent (save-excursion
975                                  (c-backward-to-start-of-do)
976                                  (current-indentation))))
977                  ((= (following-char) ?})
978                   (setq indent (- indent c-indent-level)))
979                  ((= (following-char) ?{)
980                   (setq indent (+ indent c-brace-offset))))))
981     (skip-chars-forward " \t")
982     (setq shift-amt (- indent (current-column)))
983     (if (zerop shift-amt)
984         (if (> (- (point-max) pos) (point))
985             (goto-char (- (point-max) pos)))
986       (delete-region beg (point))
987       (indent-to indent)
988       ;; If initial point was within line's indentation,
989       ;; position after the indentation.  Else stay at same point in text.
990       (if (> (- (point-max) pos) (point))
991           (goto-char (- (point-max) pos))))
992     shift-amt))
993
994 (defun calculate-c-indent (&optional parse-start)
995   "Return appropriate indentation for current line as C code.
996 In usual case returns an integer: the column to indent to.
997 Returns nil if line starts inside a string, t if in a comment."
998   (save-excursion
999     (beginning-of-line)
1000     (let ((indent-point (point))
1001           (case-fold-search nil)
1002           state
1003           containing-sexp)
1004       (if parse-start
1005           (goto-char parse-start)
1006         (beginning-of-defun))
1007       (while (< (point) indent-point)
1008         (setq parse-start (point))
1009         (setq state (parse-partial-sexp (point) indent-point 0))
1010         (setq containing-sexp (car (cdr state))))
1011       (cond ((or (nth 3 state) (nth 4 state))
1012              ;; return nil or t if should not change this line
1013              (nth 4 state))
1014             ((null containing-sexp)
1015              ;; Line is at top level.  May be data or function definition,
1016              ;; or may be function argument declaration.
1017              ;; Indent like the previous top level line
1018              ;; unless that ends in a closeparen without semicolon,
1019              ;; in which case this line is the first argument decl.
1020              (goto-char indent-point)
1021              (skip-chars-forward " \t")
1022              (if (= (following-char) ?{)
1023                  0   ; Unless it starts a function body
1024                (c-backward-to-noncomment (or parse-start (point-min)))
1025                ;; Look at previous line that's at column 0
1026                ;; to determine whether we are in top-level decls
1027                ;; or function's arg decls.  Set basic-indent accordingly.
1028                (let ((basic-indent
1029                       (save-excursion
1030                         (re-search-backward "^[^ \^L\t\n#]" nil 'move)
1031                         (let (comment lim)
1032                           ;; Recognize the DEFUN macro in Emacs.
1033                           (if (save-excursion
1034                                 ;; Move down to the (putative) argnames line.
1035                                 (while (and (not (eobp))
1036                                             (not (looking-at " *[({}#/]")))
1037                                   (forward-line 1))
1038                                 ;; Go back to the DEFUN, if it is one.
1039                                 (condition-case nil
1040                                     (backward-sexp 1)
1041                                   (error))
1042                                 (beginning-of-line)
1043                                 (looking-at "DEFUN\\b"))
1044                               c-argdecl-indent
1045                             (if (and (looking-at "\\sw\\|\\s_")
1046                                      ;; This is careful to stop at the first
1047                                      ;; paren if we have
1048                                      ;; int foo Proto ((int, int));
1049                                      (looking-at "[^\"\n=(]*(")
1050                                      (progn
1051                                        (goto-char (1- (match-end 0)))
1052                                        ;; Skip any number of paren-groups.
1053                                        ;; Consider typedef int (*fcn) (int);
1054                                        (while (= (following-char) ?\()
1055                                          (setq lim (point))
1056                                          (condition-case nil
1057                                              (forward-sexp 1)
1058                                            (error))
1059                                          (skip-chars-forward " \t\f"))
1060                                        ;; Have we reached something
1061                                        ;; that shows this isn't a function
1062                                        ;; definition?
1063                                        (and (< (point) indent-point)
1064                                             (not (memq (following-char)
1065                                                        '(?\, ?\;)))))
1066                                      ;; Make sure the "function decl" we found
1067                                      ;; is not inside a comment.
1068                                      (progn
1069                                        ;; Move back to the `(' starting arglist
1070                                        (goto-char lim)
1071                                        (beginning-of-line)
1072                                        (while (and (not comment)
1073                                                    (search-forward "/*" lim t))
1074                                          (setq comment
1075                                                (not (search-forward "*/" lim t))))
1076                                        (not comment)))
1077                                 c-argdecl-indent 0))))))
1078                  basic-indent)))
1079
1080 ;;               ;; Now add a little if this is a continuation line.
1081 ;;               (+ basic-indent (if (or (bobp)
1082 ;;                                       (memq (preceding-char) '(?\) ?\; ?\}))
1083 ;;                                       ;; Line with zero indentation
1084 ;;                                       ;; is probably the return-type
1085 ;;                                       ;; of a function definition,
1086 ;;                                       ;; so following line is function name.
1087 ;;                                       (= (current-indentation) 0))
1088 ;;                                   0 c-continued-statement-offset))
1089
1090             ((/= (char-after containing-sexp) ?{)
1091              ;; line is expression, not statement:
1092              ;; indent to just after the surrounding open.
1093              (goto-char (1+ containing-sexp))
1094              (current-column))
1095             (t
1096              ;; Statement level.  Is it a continuation or a new statement?
1097              ;; Find previous non-comment character.
1098              (goto-char indent-point)
1099              (c-backward-to-noncomment containing-sexp)
1100              ;; Back up over label lines, since they don't
1101              ;; affect whether our line is a continuation.
1102              (while (or (eq (preceding-char) ?\,)
1103                         (and (eq (preceding-char) ?:)
1104                              (or (eq (char-after (- (point) 2)) ?\')
1105                                  (memq (char-syntax (char-after (- (point) 2)))
1106                                        '(?w ?_)))))
1107                (if (eq (preceding-char) ?\,)
1108                    (progn (forward-char -1)
1109                           (c-backward-to-start-of-continued-exp containing-sexp)))
1110                (beginning-of-line)
1111                (c-backward-to-noncomment containing-sexp))
1112              ;; Check for a preprocessor statement or its continuation lines.
1113              ;; Move back to end of previous non-preprocessor line,
1114              ;; or possibly beginning of buffer.
1115              (let ((found (point)) stop)
1116                (while (not stop)
1117                  (beginning-of-line)
1118                  (cond ((bobp)
1119                         (setq found (point)
1120                               stop t))
1121                        ((save-excursion (forward-char -1)
1122                                         (= (preceding-char) ?\\))
1123                         (forward-char -1))
1124                        ;; This line is not preceded by a backslash.
1125                        ;; So either it starts a preprocessor command
1126                        ;; or any following continuation lines
1127                        ;; should not be skipped.
1128                        ((= (following-char) ?#)
1129                         (forward-char -1)
1130                         (setq found (point)))
1131                        (t (setq stop t))))
1132                (goto-char found))
1133              ;; Now we get the answer.
1134              (if (and (not (memq (preceding-char) '(0 ?\, ?\; ?\} ?\{)))
1135                       ;; But don't treat a line with a close-brace
1136                       ;; as a continuation.  It is probably the
1137                       ;; end of an enum type declaration.
1138                       (save-excursion
1139                         (goto-char indent-point)
1140                         (skip-chars-forward " \t")
1141                         (not (= (following-char) ?}))))
1142                  ;; This line is continuation of preceding line's statement;
1143                  ;; indent  c-continued-statement-offset  more than the
1144                  ;; previous line of the statement.
1145                  (progn
1146                    (c-backward-to-start-of-continued-exp containing-sexp)
1147                    (+ c-continued-statement-offset (current-column)
1148                       (if (save-excursion (goto-char indent-point)
1149                                           (skip-chars-forward " \t")
1150                                           (eq (following-char) ?{))
1151                           c-continued-brace-offset 0)))
1152                ;; This line starts a new statement.
1153                ;; Position following last unclosed open.
1154                (goto-char containing-sexp)
1155                ;; Is line first statement after an open-brace?
1156                (or
1157                  ;; If no, find that first statement and indent like it.
1158                  (save-excursion
1159                    (forward-char 1)
1160                    (let ((colon-line-end 0))
1161                      (while (progn (skip-chars-forward " \t\n")
1162                                    (looking-at "#\\|/\\*\\|case[ \t\n'/(].*:\\|[a-zA-Z0-9_$]*:"))
1163                        ;; Skip over comments and labels following openbrace.
1164                        (cond ((= (following-char) ?\#)
1165                               (forward-line 1))
1166                              ((= (following-char) ?\/)
1167                               (forward-char 2)
1168                               (search-forward "*/" nil 'move))
1169                              ;; case or label:
1170                              (t
1171                               (save-excursion (end-of-line)
1172                                               (setq colon-line-end (point)))
1173                               (search-forward ":"))))
1174                      ;; The first following code counts
1175                      ;; if it is before the line we want to indent.
1176                      (and (< (point) indent-point)
1177                           (-
1178                            (if (> colon-line-end (point))
1179                                (- (current-indentation) c-label-offset)
1180                              (current-column))
1181                            ;; If prev stmt starts with open-brace, that
1182                            ;; open brace was offset by c-brace-offset.
1183                            ;; Compensate to get the column where
1184                            ;; an ordinary statement would start.
1185                            (if (= (following-char) ?\{) c-brace-offset 0)))))
1186                  ;; If no previous statement,
1187                  ;; indent it relative to line brace is on.
1188                  (calculate-c-indent-after-brace))))))))
1189
1190 (defun calculate-c-indent-after-brace ()
1191   "Return the proper C indent for the first line after an open-brace.
1192 This function is called with point before the brace."
1193   ;; For open brace in column zero, don't let statement
1194   ;; start there too.  If c-indent-level is zero,
1195   ;; use c-brace-offset + c-continued-statement-offset instead.
1196   ;; For open-braces not the first thing in a line,
1197   ;; add in c-brace-imaginary-offset.
1198   (+ (if (and (bolp) (zerop c-indent-level))
1199          (+ c-brace-offset c-continued-statement-offset)
1200        c-indent-level)
1201      ;; Move back over whitespace before the openbrace.
1202      ;; If openbrace is not first nonwhite thing on the line,
1203      ;; add the c-brace-imaginary-offset.
1204      (progn (skip-chars-backward " \t")
1205             (if (bolp) 0 c-brace-imaginary-offset))
1206      ;; If the openbrace is preceded by a parenthesized exp,
1207      ;; move to the beginning of that;
1208      ;; possibly a different line
1209      (progn
1210        (if (eq (preceding-char) ?\))
1211            (forward-sexp -1))
1212        ;; Get initial indentation of the line we are on.
1213        (current-indentation))))
1214
1215 (defun calculate-c-indent-within-comment (&optional after-star)
1216   "Return the indentation amount for line inside a block comment.
1217 Optional arg AFTER-STAR means, if lines in the comment have a leading star,
1218 return the indentation of the text that would follow this star."
1219   (let (end star-start)
1220     (save-excursion
1221       (beginning-of-line)
1222       (skip-chars-forward " \t")
1223       (setq star-start (= (following-char) ?\*))
1224       (skip-chars-backward " \t\n")
1225       (setq end (point))
1226       (beginning-of-line)
1227       (skip-chars-forward " \t")
1228       (if after-star
1229           (and (looking-at "\\*")
1230                (re-search-forward "\\*[ \t]*")))
1231       (and (re-search-forward "/\\*[ \t]*" end t)
1232            star-start
1233            (not after-star)
1234            (goto-char (1+ (match-beginning 0))))
1235       (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
1236           (1+ (current-column))
1237         (current-column)))))
1238
1239
1240 (defun c-backward-to-noncomment (lim)
1241   (let (opoint stop)
1242     (while (not stop)
1243       (skip-chars-backward " \t\n\f" lim)
1244       (setq opoint (point))
1245       (if (and (>= (point) (+ 2 lim))
1246                (save-excursion
1247                  (forward-char -2)
1248                  (looking-at "\\*/")))
1249           (search-backward "/*" lim 'move)
1250         (setq stop (or (<= (point) lim)
1251                        (save-excursion
1252                          (beginning-of-line)
1253                          (skip-chars-forward " \t")
1254                          (not (looking-at "#")))))
1255         (or stop (beginning-of-line))))))
1256
1257 (defun c-backward-to-start-of-continued-exp (lim)
1258   (if (memq (preceding-char) '(?\) ?\"))
1259       (forward-sexp -1))
1260   (beginning-of-line)
1261   (if (<= (point) lim)
1262       (goto-char (1+ lim)))
1263   (skip-chars-forward " \t"))
1264
1265 (defun c-backward-to-start-of-if (&optional limit)
1266   "Move to the start of the last \"unbalanced\" `if'."
1267   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
1268   (let ((if-level 1)
1269         (case-fold-search nil))
1270     (while (and (not (bobp)) (not (zerop if-level)))
1271       (backward-sexp 1)
1272       (cond ((and (looking-at "else\\b")
1273                   (not (looking-at "else\\s_")))
1274              (setq if-level (1+ if-level)))
1275             ((and (looking-at "if\\b")
1276                   (not (looking-at "if\\s_")))
1277              (setq if-level (1- if-level)))
1278             ((< (point) limit)
1279              (setq if-level 0)
1280              (goto-char limit))))))
1281
1282 (defun c-backward-to-start-of-do (&optional limit)
1283   "If point follows a `do' statement, move to beginning of it and return t.
1284 Otherwise return nil and don't move point."
1285   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
1286   (let ((first t)
1287         (startpos (point))
1288         (done nil))
1289     (while (not done)
1290       (let ((next-start (point)))
1291         (condition-case nil
1292             ;; Move back one token or one brace or paren group.
1293             (backward-sexp 1)
1294           ;; If we find an open-brace, we lose.
1295           (error (setq done 'fail)))
1296         (if done
1297             nil
1298           ;; If we reached a `do', we win.
1299           (if (looking-at "do\\b")
1300               (setq done 'succeed)
1301             ;; Otherwise, if we skipped a semicolon, we lose.
1302             ;; (Exception: we can skip one semicolon before getting
1303             ;; to a the last token of the statement, unless that token
1304             ;; is a close brace.)
1305             (if (save-excursion
1306                   (forward-sexp 1)
1307                   (or (and (not first) (= (preceding-char) ?}))
1308                       (search-forward ";" next-start t
1309                                       (if (and first
1310                                                (/= (preceding-char) ?}))
1311                                           2 1))))
1312                 (setq done 'fail)
1313               (setq first nil)
1314               ;; If we go too far back in the buffer, we lose.
1315               (if (< (point) limit)
1316                   (setq done 'fail)))))))
1317     (if (eq done 'succeed)
1318         t
1319       (goto-char startpos)
1320       nil)))
1321 \f
1322 (defun c-beginning-of-statement (count)
1323   "Go to the beginning of the innermost C statement.
1324 With prefix arg, go back N - 1 statements.  If already at the beginning of a
1325 statement then go to the beginning of the preceding one.
1326 If within a string or comment, or next to a comment (only whitespace between),
1327 move by sentences instead of statements."
1328   (interactive "p")
1329   (let ((here (point)) state)
1330     (save-excursion
1331       (beginning-of-defun)
1332       (setq state (parse-partial-sexp (point) here nil nil)))
1333     (if (or (nth 3 state) (nth 4 state)
1334             (looking-at (concat "[ \t]*" comment-start-skip))
1335             (save-excursion (skip-chars-backward " \t")
1336                             (goto-char (- (point) 2))
1337                             (looking-at "\\*/")))
1338         (forward-sentence (- count))
1339       (while (> count 0)
1340         (c-beginning-of-statement-1)
1341         (setq count (1- count)))
1342       (while (< count 0)
1343         (c-end-of-statement-1)
1344         (setq count (1+ count))))))
1345
1346 (defun c-end-of-statement (count)
1347   "Go to the end of the innermost C statement.
1348 With prefix arg, go forward N - 1 statements.
1349 Move forward to end of the next statement if already at end.
1350 If within a string or comment, move by sentences instead of statements."
1351   (interactive "p")
1352   (c-beginning-of-statement (- count)))
1353
1354 (defun c-beginning-of-statement-1 ()
1355   (let ((last-begin (point))
1356         (first t))
1357     (condition-case ()
1358         (progn
1359           (while (and (not (bobp))
1360                       (progn
1361                         (backward-sexp 1)
1362                         (or first
1363                             (not (re-search-forward "[;{}]" last-begin t)))))
1364             (setq last-begin (point) first nil))
1365           (goto-char last-begin))
1366       (error (if first (backward-up-list 1) (goto-char last-begin))))))
1367
1368 (defun c-end-of-statement-1 ()
1369   (condition-case ()
1370       (progn
1371         (while (and (not (eobp))
1372                     (let ((beg (point)))
1373                       (forward-sexp 1)
1374                       (let ((end (point)))
1375                         (save-excursion
1376                           (goto-char beg)
1377                           (not (re-search-forward "[;{}]" end t)))))))
1378         (re-search-backward "[;}]")
1379         (forward-char 1))
1380     (error
1381      (let ((beg (point)))
1382        (backward-up-list -1)
1383        (let ((end (point)))
1384          (goto-char beg)
1385          (search-forward ";" end 'move))))))
1386 \f
1387 (defun mark-c-function ()
1388   "Put mark at end of C function, point at beginning."
1389   (interactive)
1390   (push-mark (point))
1391   (end-of-defun)
1392   (push-mark (point) nil t)
1393   (beginning-of-defun)
1394   (backward-paragraph))
1395 \f
1396 ;; Idea of ENDPOS is, indent each line, stopping when
1397 ;; ENDPOS is encountered.  But it's too much of a pain to make that work.
1398 (defun indent-c-exp (&optional endpos)
1399   "Indent each line of the C grouping following point."
1400   (interactive)
1401   (let* ((indent-stack (list nil))
1402          (opoint (point))  ;; May be altered below.
1403          (contain-stack
1404           (list (if endpos
1405                     (let (funbeg)
1406                       ;; Find previous fcn-start.
1407                       (save-excursion (forward-char 1)
1408                                       (beginning-of-defun)
1409                                       (setq funbeg (point)))
1410                       (setq opoint funbeg)
1411                       ;; Try to find containing open,
1412                       ;; but don't scan past that fcn-start.
1413                       (save-restriction
1414                         (narrow-to-region funbeg (point))
1415                         (condition-case nil
1416                             (save-excursion
1417                               (backward-up-list 1)
1418                               (point))
1419                           ;; We gave up: must be between fcns.
1420                           ;; Set opoint to beg of prev fcn
1421                           ;; since otherwise calculate-c-indent
1422                           ;; will get wrong answers.
1423                           (error (setq opoint funbeg)
1424                                  (point)))))
1425                   (point))))
1426          (case-fold-search nil)
1427          restart outer-loop-done inner-loop-done state ostate
1428          this-indent last-sexp
1429          at-else at-brace at-while
1430          last-depth this-point
1431          (next-depth 0))
1432     ;; If the braces don't match, get an error right away.
1433     (save-excursion
1434       (forward-sexp 1))
1435     ;; Realign the comment on the first line, even though we don't reindent it.
1436     (save-excursion
1437       (let ((beg (point)))
1438         (and (re-search-forward
1439               comment-start-skip
1440               (save-excursion (end-of-line) (point)) t)
1441              ;; Make sure this isn't a comment alone on a line
1442              ;; (which should be indented like code instead).
1443              (save-excursion
1444                (goto-char (match-beginning 0))
1445                (skip-chars-backward " \t")
1446                (not (bolp)))
1447              ;; Make sure the comment starter we found
1448              ;; is not actually in a string or quoted.
1449              (let ((new-state
1450                     (parse-partial-sexp beg (point)
1451                                         nil nil state)))
1452                (and (not (nth 3 new-state)) (not (nth 5 new-state))))
1453             (progn (indent-for-comment) (beginning-of-line)))))
1454     (save-excursion
1455       (setq outer-loop-done nil)
1456       (while (and (not (eobp))
1457                   (if endpos (< (point) endpos)
1458                     (not outer-loop-done)))
1459         (setq last-depth next-depth)
1460         ;; Compute how depth changes over this line
1461         ;; plus enough other lines to get to one that
1462         ;; does not end inside a comment or string.
1463         ;; Meanwhile, do appropriate indentation on comment lines.
1464         (setq inner-loop-done nil)
1465         (while (and (not inner-loop-done)
1466                     (not (and (eobp) (setq outer-loop-done t))))
1467           (setq ostate state)
1468           (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
1469                                           nil nil state))
1470           (setq next-depth (car state))
1471           (if (and (car (cdr (cdr state)))
1472                    (>= (car (cdr (cdr state))) 0))
1473               (setq last-sexp (car (cdr (cdr state)))))
1474           ;; If this line started within a comment, indent it as such.
1475           (if (or (nth 4 ostate) (nth 7 ostate))
1476               (c-indent-line))
1477           ;; If it ends outside of comments or strings, exit the inner loop.
1478           ;; Otherwise move on to next line.
1479           (if (or (nth 3 state) (nth 4 state) (nth 7 state))
1480               (forward-line 1)
1481             (setq inner-loop-done t)))
1482         (and endpos
1483              (while (< next-depth 0)
1484                (setq indent-stack (append indent-stack (list nil)))
1485                (setq contain-stack (append contain-stack (list nil)))
1486                (setq next-depth (1+ next-depth))
1487                (setq last-depth (1+ last-depth))
1488                (setcar (nthcdr 6 state) (1+ (nth 6 state)))))
1489         (setq outer-loop-done (and (not endpos) (<= next-depth 0)))
1490         (if outer-loop-done
1491             nil
1492           ;; If this line had ..))) (((.. in it, pop out of the levels
1493           ;; that ended anywhere in this line, even if the final depth
1494           ;; doesn't indicate that they ended.
1495           (while (> last-depth (nth 6 state))
1496             (setq indent-stack (cdr indent-stack)
1497                   contain-stack (cdr contain-stack)
1498                   last-depth (1- last-depth)))
1499           (if (/= last-depth next-depth)
1500               (setq last-sexp nil))
1501           ;; Add levels for any parens that were started in this line.
1502           (while (< last-depth next-depth)
1503             (setq indent-stack (cons nil indent-stack)
1504                   contain-stack (cons nil contain-stack)
1505                   last-depth (1+ last-depth)))
1506           (if (null (car contain-stack))
1507               (setcar contain-stack (or (car (cdr state))
1508                                         (save-excursion (forward-sexp -1)
1509                                                         (point)))))
1510           (forward-line 1)
1511           (skip-chars-forward " \t")
1512           ;; Don't really reindent if the line is just whitespace,
1513           ;; or if it is past the endpos.
1514           ;; (The exit test in the outer while
1515           ;; does not exit until we have passed the first line
1516           ;; past the region.)
1517           (if (or (eolp) (and endpos (>= (point) endpos)))
1518               nil
1519             ;; Is this line in a new nesting level?
1520             ;; In other words, is this the first line that
1521             ;; starts in the new level?
1522             (if (and (car indent-stack)
1523                      (>= (car indent-stack) 0))
1524                 nil
1525               ;; Yes.
1526               ;; Compute the standard indent for this level.
1527               (let (val)
1528                 (if (= (char-after (car contain-stack)) ?{)
1529                     (save-excursion
1530                       (goto-char (car contain-stack))
1531                       (setq val (calculate-c-indent-after-brace)))
1532                   (setq val (calculate-c-indent
1533                              (if (car indent-stack)
1534                                  (- (car indent-stack))
1535                                opoint))))
1536                 ;; t means we are in a block comment and should
1537                 ;; calculate accordingly.
1538                 (if (eq val t)
1539                     (setq val (calculate-c-indent-within-comment)))
1540                 (setcar indent-stack val)))
1541             ;; Adjust indent of this individual line
1542             ;; based on its predecessor.
1543             ;; Handle continuation lines, if, else, while, and so on.
1544             (if (/= (char-after (car contain-stack)) ?{)
1545                 (setq this-indent (car indent-stack))
1546               ;; Line is at statement level.
1547               ;; Is it a new statement?  Is it an else?
1548               ;; Find last non-comment character before this line
1549               (save-excursion
1550                 (setq this-point (point))
1551                 (setq at-else (and (looking-at "else\\b")
1552                                    (not (looking-at "else\\s_"))))
1553                 (setq at-brace (= (following-char) ?{))
1554                 (setq at-while (and (looking-at "while\\b")
1555                                     (not (looking-at "while\\s_"))))
1556                 (if (= (following-char) ?})
1557                     (setq this-indent (car indent-stack))
1558                   (c-backward-to-noncomment opoint)
1559                   (if (not (memq (preceding-char) '(0 ?\, ?\; ?} ?: ?{)))
1560                       ;; Preceding line did not end in comma or semi;
1561                       ;; indent this line  c-continued-statement-offset
1562                       ;; more than previous.
1563                       (progn
1564                         (c-backward-to-start-of-continued-exp (car contain-stack))
1565                         (setq this-indent
1566                               (+ c-continued-statement-offset (current-column)
1567                                  (if at-brace c-continued-brace-offset 0))))
1568                     ;; Preceding line ended in comma or semi;
1569                     ;; use the standard indent for this level.
1570                     (cond (at-else (progn (c-backward-to-start-of-if opoint)
1571                                           (setq this-indent
1572                                                 (current-indentation))))
1573                           ((and at-while (c-backward-to-start-of-do opoint))
1574                            (setq this-indent (current-indentation)))
1575                           ((eq (preceding-char) ?\,)
1576                            (goto-char this-point)
1577                            (setq this-indent (calculate-c-indent)))
1578                           (t (setq this-indent (car indent-stack))))))))
1579             ;; Adjust line indentation according to its contents
1580             (if (or (looking-at c-switch-label-regexp)
1581                     (and (looking-at "[A-Za-z]")
1582                          (save-excursion
1583                            (forward-sexp 1)
1584                            (looking-at ":"))))
1585                 (setq this-indent (max 1 (+ this-indent c-label-offset))))
1586             (if (= (following-char) ?})
1587                 (setq this-indent (- this-indent c-indent-level)))
1588             (if (= (following-char) ?{)
1589                 ;; Don't move an open-brace in column 0.
1590                 ;; This is good when constructs such as
1591                 ;; `extern "C" {' surround a function definition
1592                 ;; that should be indented as usual.
1593                 ;; It is also good for nested functions.
1594                 ;; It is bad when an open-brace is indented at column 0
1595                 ;; and you want to fix that, but we can't win 'em all.
1596                 (if (zerop (current-column))
1597                     (setq this-indent 0)
1598                   (setq this-indent (+ this-indent c-brace-offset))))
1599             ;; Don't leave indentation in empty lines.
1600             (if (eolp) (setq this-indent 0))
1601             ;; Put chosen indentation into effect.
1602             (or (= (current-column) this-indent)
1603                 (= (following-char) ?\#)
1604                 (progn
1605                   (delete-region (point) (progn (beginning-of-line) (point)))
1606                   (indent-to this-indent)))
1607             ;; Indent any comment following the text.
1608             (or (looking-at comment-start-skip)
1609                 (save-excursion
1610                   (let ((beg (point)))
1611                     (and (re-search-forward
1612                           comment-start-skip
1613                           (save-excursion (end-of-line) (point)) t)
1614                          ;; Make sure the comment starter we found
1615                          ;; is not actually in a string or quoted.
1616                          (let ((new-state
1617                                 (parse-partial-sexp beg (point)
1618                                                     nil nil state)))
1619                            (and (not (nth 3 new-state)) (not (nth 5 new-state))))
1620                          (indent-for-comment)))))))))))
1621
1622 ;; Look at all comment-start strings in the current line after point.
1623 ;; Return t if one of them starts a real comment.
1624 ;; This is not used yet, because indent-for-comment
1625 ;; isn't smart enough to handle the cases this can find.
1626 (defun indent-c-find-real-comment ()
1627   (let (win)
1628     (while (and (not win)
1629                 (re-search-forward comment-start-skip
1630                                    (save-excursion (end-of-line) (point))
1631                                    t))
1632       ;; Make sure the comment start is not quoted.
1633       (let ((state-1
1634              (parse-partial-sexp
1635               (save-excursion (beginning-of-line) (point))
1636               (point) nil nil state)))
1637         (setq win (and (null (nth 3 state-1)) (null (nth 5 state-1))))))
1638     win))
1639
1640 ;; Indent every line whose first char is between START and END inclusive.
1641 (defun c-indent-region (start end)
1642   (save-excursion
1643     (goto-char start)
1644     ;; Advance to first nonblank line.
1645     (skip-chars-forward " \t\n")
1646     (beginning-of-line)
1647     (let ((endmark (copy-marker end))
1648           (c-tab-always-indent t))
1649       (while (and (bolp) (not (eobp)) (< (point) endmark))
1650         ;; Indent one line as with TAB.
1651         (let ((shift-amt (c-indent-line))
1652               nextline sexpbeg sexpend)
1653           (if (save-excursion (beginning-of-line) (looking-at "[ \t]*#"))
1654               (forward-line 1)
1655             (save-excursion
1656               ;; Find beginning of following line.
1657               (save-excursion
1658                 (forward-line 1) (setq nextline (point)))
1659               ;; Find first beginning-of-sexp for sexp extending past this line.
1660               (beginning-of-line)
1661               (while (< (point) nextline)
1662                 (condition-case nil
1663                     (progn
1664                       (forward-sexp 1)
1665                       (setq sexpend (point-marker)))
1666                   (error (setq sexpend nil)
1667                          (goto-char nextline)))
1668                 (skip-chars-forward " \t\n"))
1669               (if sexpend
1670                   (progn
1671                     ;; Make sure the sexp we found really starts on the
1672                     ;; current line and extends past it.
1673                     (goto-char sexpend)
1674                     (backward-sexp 1)
1675                     (setq sexpbeg (point)))))
1676             ;; If that sexp ends within the region,
1677             ;; indent it all at once, fast.
1678             (if (and sexpend (> sexpend nextline) (<= sexpend endmark)
1679                      (< sexpbeg nextline))
1680                 (progn
1681                   (indent-c-exp)
1682                   (goto-char sexpend)))
1683             ;; Move to following line and try again.
1684             (and sexpend (set-marker sexpend nil))
1685             (forward-line 1))))
1686       (set-marker endmark nil))))
1687 \f
1688 (defun set-c-style (style &optional global)
1689   "Set C-mode variables to use one of several different indentation styles.
1690 The arguments are a string representing the desired style
1691 and a flag which, if non-nil, means to set the style globally.
1692 \(Interactively, the flag comes from the prefix argument.)
1693 Available styles are GNU, K&R, BSD and Whitesmith."
1694   (interactive (list (let ((completion-ignore-case t))
1695                        (completing-read "Use which C indentation style? "
1696                                         c-style-alist nil t))
1697                      current-prefix-arg))
1698   (let ((vars (cdr (assoc style c-style-alist))))
1699     (or vars
1700         (error "Invalid C indentation style `%s'" style))
1701     (while vars
1702       (or global
1703           (make-local-variable (car (car vars))))
1704       (set (car (car vars)) (cdr (car vars)))
1705       (setq vars (cdr vars)))))
1706 \f
1707 ;;; This page handles insertion and removal of backslashes for C macros.
1708
1709 (defcustom c-backslash-column 48
1710   "*Minimum column for end-of-line backslashes of macro definitions."
1711   :type 'integer
1712   :group 'old-c)
1713
1714 (defun c-backslash-region (from to delete-flag)
1715   "Insert, align, or delete end-of-line backslashes on the lines in the region.
1716 With no argument, inserts backslashes and aligns existing backslashes.
1717 With an argument, deletes the backslashes.
1718
1719 This function does not modify the last line of the region if the region ends
1720 right at the start of the following line; it does not modify blank lines
1721 at the start of the region.  So you can put the region around an entire macro
1722 definition and conveniently use this command."
1723   (interactive "r\nP")
1724   (save-excursion
1725     (goto-char from)
1726     (let ((column c-backslash-column)
1727           (endmark (make-marker)))
1728       (move-marker endmark to)
1729       ;; Compute the smallest column number past the ends of all the lines.
1730       (if (not delete-flag)
1731           (while (< (point) to)
1732             (end-of-line)
1733             (if (= (preceding-char) ?\\)
1734                 (progn (forward-char -1)
1735                        (skip-chars-backward " \t")))
1736             (setq column (max column (1+ (current-column))))
1737             (forward-line 1)))
1738       ;; Adjust upward to a tab column, if that doesn't push past the margin.
1739       (if (> (% column tab-width) 0)
1740           (let ((adjusted (* (/ (+ column tab-width -1) tab-width) tab-width)))
1741             (if (< adjusted (window-width))
1742                 (setq column adjusted))))
1743       ;; Don't modify blank lines at start of region.
1744       (goto-char from)
1745       (while (and (< (point) endmark) (eolp))
1746         (forward-line 1))
1747       ;; Add or remove backslashes on all the lines.
1748       (while (and (< (point) endmark)
1749                   ;; Don't backslashify the last line
1750                   ;; if the region ends right at the start of the next line.
1751                   (save-excursion
1752                     (forward-line 1)
1753                     (< (point) endmark)))
1754         (if (not delete-flag)
1755             (c-append-backslash column)
1756           (c-delete-backslash))
1757         (forward-line 1))
1758       (move-marker endmark nil))))
1759
1760 (defun c-append-backslash (column)
1761   (end-of-line)
1762   ;; Note that "\\\\" is needed to get one backslash.
1763   (if (= (preceding-char) ?\\)
1764       (progn (forward-char -1)
1765              (delete-horizontal-space)
1766              (indent-to column))
1767     (indent-to column)
1768     (insert "\\")))
1769
1770 (defun c-delete-backslash ()
1771   (end-of-line)
1772   (or (bolp)
1773       (progn
1774         (forward-char -1)
1775         (if (looking-at "\\\\")
1776             (delete-region (1+ (point))
1777                            (progn (skip-chars-backward " \t") (point)))))))
1778 \f
1779 (defun c-up-conditional (count)
1780   "Move back to the containing preprocessor conditional, leaving mark behind.
1781 A prefix argument acts as a repeat count.  With a negative argument,
1782 move forward to the end of the containing preprocessor conditional.
1783 When going backwards, `#elif' is treated like `#else' followed by `#if'.
1784 When going forwards, `#elif' is ignored."
1785   (interactive "p")
1786   (c-forward-conditional (- count) t))
1787
1788 (defun c-backward-conditional (count &optional up-flag)
1789   "Move back across a preprocessor conditional, leaving mark behind.
1790 A prefix argument acts as a repeat count.  With a negative argument,
1791 move forward across a preprocessor conditional."
1792   (interactive "p")
1793   (c-forward-conditional (- count) up-flag))
1794
1795 (defun c-forward-conditional (count &optional up-flag)
1796   "Move forward across a preprocessor conditional, leaving mark behind.
1797 A prefix argument acts as a repeat count.  With a negative argument,
1798 move backward across a preprocessor conditional."
1799   (interactive "p")
1800   (let* ((forward (> count 0))
1801          (increment (if forward -1 1))
1802          (search-function (if forward 're-search-forward 're-search-backward))
1803          (opoint (point))
1804          (new))
1805     (save-excursion
1806       (while (/= count 0)
1807         (let ((depth (if up-flag 0 -1)) found)
1808           (save-excursion
1809             ;; Find the "next" significant line in the proper direction.
1810             (while (and (not found)
1811                         ;; Rather than searching for a # sign that comes
1812                         ;; at the beginning of a line aside from whitespace,
1813                         ;; search first for a string starting with # sign.
1814                         ;; Then verify what precedes it.
1815                         ;; This is faster on account of the fastmap feature of
1816                         ;; the regexp matcher.
1817                         (funcall search-function
1818                                  "#[ \t]*\\(if\\|elif\\|endif\\)"
1819                                  nil t))
1820               (beginning-of-line)
1821               ;; Now verify it is really a preproc line.
1822               (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")
1823                   (let ((prev depth))
1824                     ;; Update depth according to what we found.
1825                     (beginning-of-line)
1826                     (cond ((looking-at "[ \t]*#[ \t]*endif")
1827                            (setq depth (+ depth increment)))
1828                           ((looking-at "[ \t]*#[ \t]*elif")
1829                            (if (and forward (= depth 0))
1830                                (setq found (point))))
1831                           (t (setq depth (- depth increment))))
1832                     ;; If we are trying to move across, and we find
1833                     ;; an end before we find a beginning, get an error.
1834                     (if (and (< prev 0) (< depth prev))
1835                         (error (if forward
1836                                    "No following conditional at this level"
1837                                  "No previous conditional at this level")))
1838                     ;; When searching forward, start from next line
1839                     ;; so that we don't find the same line again.
1840                     (if forward (forward-line 1))
1841                     ;; If this line exits a level of conditional, exit inner loop.
1842                     (if (< depth 0)
1843                         (setq found (point))))
1844                 ;; If the line is not really a conditional, skip past it.
1845                 (if forward (end-of-line)))))
1846           (or found
1847               (error "No containing preprocessor conditional"))
1848           (goto-char (setq new found)))
1849         (setq count (+ count increment))))
1850     (push-mark)
1851     (goto-char new)))
1852 \f
1853 ;;; begin stuff from cc-mode
1854
1855 (defsubst c-region-is-active-p ()
1856   ;; Return t when the region is active.  The determination of region
1857   ;; activeness is different in both Emacs and XEmacs.
1858   (cond
1859    ;; XEmacs
1860    ((and (fboundp 'region-active-p)
1861          (boundp 'zmacs-regions)
1862          zmacs-regions)
1863     (region-active-p))
1864    ;; Emacs
1865    ((boundp 'mark-active) mark-active)
1866    ;; fallback; shouldn't get here
1867    (t (mark t))))
1868
1869 (defun c-fn-region-is-active-p ()
1870   ;; Function version of the macro for use in places that aren't
1871   ;; compiled, e.g. in the menus.
1872   (c-region-is-active-p))
1873
1874 (defun c-indent-line-or-region ()
1875   "When the region is active, indent it.  Otherwise indent the current line."
1876   ;; Emacs has a variable called mark-active, XEmacs uses region-active-p
1877   (interactive)
1878   (if (c-region-is-active-p)
1879       (c-indent-region (region-beginning) (region-end))
1880     (indent-according-to-mode)))
1881
1882 (defmacro c-point (position &optional point)
1883   ;; Returns the value of certain commonly referenced POSITIONs
1884   ;; relative to POINT.  The current point is used if POINT isn't
1885   ;; specified.  POSITION can be one of the following symbols:
1886   ;; 
1887   ;; bol  -- beginning of line
1888   ;; eol  -- end of line
1889   ;; bod  -- beginning of defun
1890   ;; eod  -- end of defun
1891   ;; boi  -- back to indentation
1892   ;; ionl -- indentation of next line
1893   ;; iopl -- indentation of previous line
1894   ;; bonl -- beginning of next line
1895   ;; bopl -- beginning of previous line
1896   ;; 
1897   ;; This function does not modify point or mark.
1898   `(save-excursion
1899      ,(if point `(goto-char ,point))
1900      ,(if (and (eq (car-safe position) 'quote)
1901                (symbolp (eval position)))
1902           (let ((position (eval position)))
1903             (cond
1904              ((eq position 'bol)  `(beginning-of-line))
1905              ((eq position 'eol)  `(end-of-line))
1906              ((eq position 'boi)  `(back-to-indentation))
1907              ((eq position 'bonl) `(forward-line 1))
1908              ((eq position 'bopl) `(forward-line -1))
1909              ((eq position 'bod)  `(c-beginning-of-defun-1))
1910              ((eq position 'eod)  `(c-end-of-defun-1))
1911              ((eq position 'iopl) `(progn
1912                                      (forward-line -1)
1913                                      (back-to-indentation)))
1914              ((eq position 'ionl) `(progn
1915                                      (forward-line 1)
1916                                      (back-to-indentation)))
1917              (t (error "unknown buffer position requested: %s" position))))
1918         ;;(message "c-point long expansion")
1919         `(let ((position ,position))
1920            (cond
1921             ((eq position 'bol)  (beginning-of-line))
1922             ((eq position 'eol)  (end-of-line))
1923             ((eq position 'boi)  (back-to-indentation))
1924             ((eq position 'bonl) (forward-line 1))
1925             ((eq position 'bopl) (forward-line -1))
1926             ((eq position 'bod)  (c-beginning-of-defun-1))
1927             ((eq position 'eod)  (c-end-of-defun-1))
1928             ((eq position 'iopl) (progn
1929                                    (forward-line -1)
1930                                    (back-to-indentation)))
1931             ((eq position 'ionl) (progn
1932                                    (forward-line 1)
1933                                    (back-to-indentation)))
1934             (t (error "unknown buffer position requested: %s" position)))))
1935      (point)))
1936
1937 (defmacro c-safe (&rest body)
1938   ;; safely execute BODY, return nil if an error occurred
1939   `(condition-case nil
1940        (progn ,@body)
1941      (error nil)))
1942
1943 (defmacro c-forward-sexp (&optional arg)
1944   ;; like forward-sexp except
1945   ;;   1. this is much stripped down from the XEmacs version
1946   ;;   2. this cannot be used as a command, so we're insulated from
1947   ;;      XEmacs' losing efforts to make forward-sexp more user
1948   ;;      friendly
1949   ;;   3. Preserves the semantics most of CC Mode is based on
1950   (or arg (setq arg 1))
1951   `(goto-char (or (scan-sexps (point) ,arg)
1952                   ,(if (numberp arg)
1953                        (if (> arg 0) `(point-max) `(point-min))
1954                      `(if (> ,arg 0) (point-max) (point-min))))))
1955
1956 (defmacro c-backward-sexp (&optional arg)
1957   ;; See c-forward-sexp and reverse directions
1958   (or arg (setq arg 1))
1959   `(c-forward-sexp ,(if (numberp arg) (- arg) `(- ,arg))))
1960
1961 (defun c-indent-exp (&optional shutup-p)
1962   "Indent each line in the balanced expression following point syntactically.
1963 If optional SHUTUP-P is non-nil, no errors are signalled if no
1964 balanced expression is found."
1965   (interactive "*P")
1966   (let ((here (point-marker))
1967         end)
1968     (set-marker-insertion-type here t)
1969     (unwind-protect
1970         (let ((start (progn
1971                        ;; try to be smarter about finding the range of
1972                        ;; lines to indent. skip all following
1973                        ;; whitespace, then try to find any
1974                        ;; opening paren on the current line
1975                        (skip-chars-forward " \t\n")
1976                        (save-restriction
1977                          (narrow-to-region (point-min) (c-point 'eol))
1978                          (c-safe (1- (scan-lists (point) 1 -1)))))))
1979           ;; find balanced expression end
1980           (setq end (and (c-safe (progn (c-forward-sexp 1) t))
1981                          (point)))
1982           ;; sanity check
1983           (if (not start)
1984              (unless shutup-p
1985                (error "Cannot find start of balanced expression to indent"))
1986             (if (not end)
1987                 (unless shutup-p
1988                   (error "Cannot find end of balanced expression to indent"))
1989               (c-indent-region start end))))
1990       (goto-char here)
1991       (set-marker here nil))))
1992
1993 (defun c-insert-matching-endif ()
1994   "Insert a #endif expression matching the corresponding #if... statement.
1995 This skips across any number of intervening #if/#endif pairs to find the
1996 matching #if/#ifdef/#ifndef statement and inserts a #endif with a comment
1997 corresponding to the expression following the #if.  If the statement is
1998 a #ifndef, the word \"not\" appears in the comment.  If there are spaces
1999 between the '#' and the 'if', the same number of spaces appear in the
2000 #endif.  Comments following the #if statement are ignored and do not appear
2001 in the #endif comment."
2002   (interactive)
2003   (let (spaces expr notp)
2004     (save-excursion
2005       (c-up-conditional 1)
2006       ;; we have to construct the regexps carefully to avoid running into
2007       ;; problems due to the greedy operators.  XEmacs has non-greedy
2008       ;; operators, which would simplify matters, but they're not present
2009       ;; in GNU Emacs.
2010       (or (looking-at "#\\( *\\)if\\(n?\\)[a-z]*\\(.*[^ \t\n]\\)[ \t]*/[*/].*")
2011           (looking-at "#\\( *\\)if\\(n?\\)[a-z]*\\(.*[^ \t\n]\\)")
2012           (error "Malformed #if... expression"))
2013       (setq spaces (match-string 1))
2014       (setq notp (> (match-end 2) (match-beginning 2)))
2015       (setq expr (match-string 3)))
2016     (insert "#" spaces "endif /*" (if notp " not" "") expr " */\n")))
2017
2018 ;;; end stuff from cc-mode
2019
2020 \f
2021
2022 (provide 'c-mode)
2023
2024 ;;; old-c-mode.el ends here