home *** CD-ROM | disk | FTP | other *** search
/ Geek Gadgets 1 / ADE-1.bin / ade-dist / emacs-19.28-src.tgz / tar.out / fsf / emacs / lisp / c-mode.el < prev    next >
Lisp/Scheme  |  1996-09-28  |  55KB  |  1,492 lines

  1. ;;; c-mode.el --- C code editing commands for Emacs
  2. ;; Copyright (C) 1985, 1986, 1987, 1992, 1994 Free Software Foundation, Inc.
  3.  
  4. ;; Maintainer: FSF
  5. ;; Keywords: c
  6.  
  7. ;; This file is part of GNU Emacs.
  8.  
  9. ;; GNU Emacs is free software; you can redistribute it and/or modify
  10. ;; it under the terms of the GNU General Public License as published by
  11. ;; the Free Software Foundation; either version 2, or (at your option)
  12. ;; any later version.
  13.  
  14. ;; GNU Emacs is distributed in the hope that it will be useful,
  15. ;; but WITHOUT ANY WARRANTY; without even the implied warranty of
  16. ;; MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
  17. ;; GNU General Public License for more details.
  18.  
  19. ;; You should have received a copy of the GNU General Public License
  20. ;; along with GNU Emacs; see the file COPYING.  If not, write to
  21. ;; the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
  22.  
  23. ;;; Commentary:
  24.  
  25. ;; A smart editing mode for C code.  It knows a lot about C syntax and tries
  26. ;; to position the curser according to C layout conventions.  You can
  27. ;; change the details of the layout style with option variables.  Load it
  28. ;; and do M-x describe-mode for details.
  29.  
  30. ;;; Code:
  31.  
  32. (defvar c-mode-abbrev-table nil
  33.   "Abbrev table in use in C mode.")
  34. (define-abbrev-table 'c-mode-abbrev-table ())
  35.  
  36. (defvar c-mode-map (make-sparse-keymap)
  37.   "Keymap used in C mode.")
  38.  
  39. (define-key c-mode-map "{" 'electric-c-brace)
  40. (define-key c-mode-map "}" 'electric-c-brace)
  41. (define-key c-mode-map ";" 'electric-c-semi)
  42. (define-key c-mode-map "#" 'electric-c-sharp-sign)
  43. (define-key c-mode-map ":" 'electric-c-terminator)
  44. (define-key c-mode-map "\e\C-h" 'mark-c-function)
  45. (define-key c-mode-map "\e\C-q" 'indent-c-exp)
  46. (define-key c-mode-map "\ea" 'c-beginning-of-statement)
  47. (define-key c-mode-map "\ee" 'c-end-of-statement)
  48. (define-key c-mode-map "\eq" 'c-fill-paragraph)
  49. (define-key c-mode-map "\C-c\C-n" 'c-forward-conditional)
  50. (define-key c-mode-map "\C-c\C-p" 'c-backward-conditional)
  51. (define-key c-mode-map "\C-c\C-u" 'c-up-conditional)
  52. (define-key c-mode-map "\177" 'backward-delete-char-untabify)
  53. (define-key c-mode-map "\t" 'c-indent-command)
  54.  
  55. (define-key c-mode-map [menu-bar] (make-sparse-keymap))
  56.  
  57. (define-key c-mode-map [menu-bar c]
  58.   (cons "C" (make-sparse-keymap "C")))
  59.  
  60. (define-key c-mode-map [menu-bar c comment-region]
  61.   '("Comment Out Region" . comment-region))
  62. (define-key c-mode-map [menu-bar c c-macro-expand]
  63.   '("Macro Expand Region" . c-macro-expand))
  64. (define-key c-mode-map [menu-bar c c-backslash-region]
  65.   '("Backslashify" . c-backslash-region))
  66. (define-key c-mode-map [menu-bar c indent-exp]
  67.   '("Indent Expression" . indent-c-exp))
  68. (define-key c-mode-map [menu-bar c indent-line]
  69.   '("Indent Line" . c-indent-command))
  70. (define-key c-mode-map [menu-bar c fill]
  71.   '("Fill Comment Paragraph" . c-fill-paragraph))
  72. (define-key c-mode-map [menu-bar c up]
  73.   '("Up Conditional" . c-up-conditional))
  74. (define-key c-mode-map [menu-bar c backward]
  75.   '("Backward Conditional" . c-backward-conditional))
  76. (define-key c-mode-map [menu-bar c forward]
  77.   '("Forward Conditional" . c-forward-conditional))
  78. (define-key c-mode-map [menu-bar c backward-stmt]
  79.   '("Backward Statement" . c-beginning-of-statement))
  80. (define-key c-mode-map [menu-bar c forward-stmt]
  81.   '("Forward Statement" . c-end-of-statement))
  82.  
  83. (autoload 'c-macro-expand "cmacexp"
  84.   "Display the result of expanding all C macros occurring in the region.
  85. The expansion is entirely correct because it uses the C preprocessor."
  86.   t)
  87.  
  88. (defvar c-mode-syntax-table nil
  89.   "Syntax table in use in C-mode buffers.")
  90.  
  91. (if c-mode-syntax-table
  92.     ()
  93.   (setq c-mode-syntax-table (make-syntax-table))
  94.   (modify-syntax-entry ?\\ "\\" c-mode-syntax-table)
  95.   (modify-syntax-entry ?/ ". 14" c-mode-syntax-table)
  96.   (modify-syntax-entry ?* ". 23" c-mode-syntax-table)
  97.   (modify-syntax-entry ?+ "." c-mode-syntax-table)
  98.   (modify-syntax-entry ?- "." c-mode-syntax-table)
  99.   (modify-syntax-entry ?= "." c-mode-syntax-table)
  100.   (modify-syntax-entry ?% "." c-mode-syntax-table)
  101.   (modify-syntax-entry ?< "." c-mode-syntax-table)
  102.   (modify-syntax-entry ?> "." c-mode-syntax-table)
  103.   (modify-syntax-entry ?& "." c-mode-syntax-table)
  104.   (modify-syntax-entry ?| "." c-mode-syntax-table)
  105.   (modify-syntax-entry ?\' "\"" c-mode-syntax-table))
  106.  
  107. (defconst c-indent-level 2
  108.   "*Indentation of C statements with respect to containing block.")
  109. (defconst c-brace-imaginary-offset 0
  110.   "*Imagined indentation of a C open brace that actually follows a statement.")
  111. (defconst c-brace-offset 0
  112.   "*Extra indentation for braces, compared with other text in same context.")
  113. (defconst c-argdecl-indent 5
  114.   "*Indentation level of declarations of C function arguments.")
  115. (defconst c-label-offset -2
  116.   "*Offset of C label lines and case statements relative to usual indentation.")
  117. (defconst c-continued-statement-offset 2
  118.   "*Extra indent for lines not starting new statements.")
  119. (defconst c-continued-brace-offset 0
  120.   "*Extra indent for substatements that start with open-braces.
  121. This is in addition to c-continued-statement-offset.")
  122. (defconst c-style-alist
  123.   '(("GNU"
  124.      (c-indent-level               .  2)
  125.      (c-argdecl-indent             .  5)
  126.      (c-brace-offset               .  0)
  127.      (c-label-offset               . -2)
  128.      (c-continued-statement-offset .  2))
  129.     ("K&R"
  130.      (c-indent-level               .  5)
  131.      (c-argdecl-indent             .  0)
  132.      (c-brace-offset               . -5)
  133.      (c-label-offset               . -5)
  134.      (c-continued-statement-offset .  5))
  135.     ("BSD"
  136.      (c-indent-level               .  4)
  137.      (c-argdecl-indent             .  4)
  138.      (c-brace-offset               . -4)
  139.      (c-label-offset               . -4)
  140.      (c-continued-statement-offset .  4))
  141.     ("C++"
  142.      (c-indent-level               . 4)
  143.      (c-continued-statement-offset . 4)
  144.      (c-brace-offset               . -4)
  145.      (c-argdecl-indent             . 0)
  146.      (c-label-offset               . -4)
  147.      (c-auto-newline               . t))
  148.     ("Whitesmith"
  149.      (c-indent-level               .  4)
  150.      (c-argdecl-indent             .  4)
  151.      (c-brace-offset               .  0)
  152.      (c-label-offset               . -4)
  153.      (c-continued-statement-offset .  4))))
  154.  
  155. (defconst c-auto-newline nil
  156.   "*Non-nil means automatically newline before and after braces,
  157. and after colons and semicolons, inserted in C code.
  158. If you do not want a leading newline before braces then use:
  159.   (define-key c-mode-map \"{\" 'electric-c-semi)")
  160.  
  161. (defconst c-tab-always-indent t
  162.   "*Non-nil means TAB in C mode should always reindent the current line,
  163. regardless of where in the line point is when the TAB command is used.")
  164.  
  165. ;;; Regular expression used internally to recognize labels in switch
  166. ;;; statements.
  167. (defconst c-switch-label-regexp "case[ \t'/(]\\|default\\(\\S_\\|'\\)")
  168.  
  169.  
  170. (defun c-mode ()
  171.   "Major mode for editing C code.
  172. Expression and list commands understand all C brackets.
  173. Tab indents for C code.
  174. Comments are delimited with /* ... */.
  175. Paragraphs are separated by blank lines only.
  176. Delete converts tabs to spaces as it moves back.
  177. \\{c-mode-map}
  178. Variables controlling indentation style:
  179.  c-tab-always-indent
  180.     Non-nil means TAB in C mode should always reindent the current line,
  181.     regardless of where in the line point is when the TAB command is used.
  182.  c-auto-newline
  183.     Non-nil means automatically newline before and after braces,
  184.     and after colons and semicolons, inserted in C code.
  185.  c-indent-level
  186.     Indentation of C statements within surrounding block.
  187.     The surrounding block's indentation is the indentation
  188.     of the line on which the open-brace appears.
  189.  c-continued-statement-offset
  190.     Extra indentation given to a substatement, such as the
  191.     then-clause of an if or body of a while.
  192.  c-continued-brace-offset
  193.     Extra indentation given to a brace that starts a substatement.
  194.     This is in addition to c-continued-statement-offset.
  195.  c-brace-offset
  196.     Extra indentation for line if it starts with an open brace.
  197.  c-brace-imaginary-offset
  198.     An open brace following other text is treated as if it were
  199.     this far to the right of the start of its line.
  200.  c-argdecl-indent
  201.     Indentation level of declarations of C function arguments.
  202.  c-label-offset
  203.     Extra indentation for line that is a label, or case or default.
  204.  
  205. Settings for K&R and BSD indentation styles are
  206.   c-indent-level                5    8
  207.   c-continued-statement-offset  5    8
  208.   c-brace-offset               -5   -8
  209.   c-argdecl-indent              0    8
  210.   c-label-offset               -5   -8
  211.  
  212. Turning on C mode calls the value of the variable c-mode-hook with no args,
  213. if that value is non-nil."
  214.   (interactive)
  215.   (kill-all-local-variables)
  216.   (use-local-map c-mode-map)
  217.   (setq major-mode 'c-mode)
  218.   (setq mode-name "C")
  219.   (setq local-abbrev-table c-mode-abbrev-table)
  220.   (set-syntax-table c-mode-syntax-table)
  221.   (make-local-variable 'paragraph-start)
  222.   (setq paragraph-start (concat "^$\\|" page-delimiter))
  223.   (make-local-variable 'paragraph-separate)
  224.   (setq paragraph-separate paragraph-start)
  225.   (make-local-variable 'paragraph-ignore-fill-prefix)
  226.   (setq paragraph-ignore-fill-prefix t)
  227.   (make-local-variable 'indent-line-function)
  228.   (setq indent-line-function 'c-indent-line)
  229.   (make-local-variable 'indent-region-function)
  230.   (setq indent-region-function 'c-indent-region)
  231.   (make-local-variable 'require-final-newline)
  232.   (setq require-final-newline t)
  233.   (make-local-variable 'outline-regexp)
  234.   (setq outline-regexp "[^#\n\^M]")
  235.   (make-local-variable 'outline-level)
  236.   (setq outline-level 'c-outline-level)
  237.   (make-local-variable 'comment-start)
  238.   (setq comment-start "/* ")
  239.   (make-local-variable 'comment-end)
  240.   (setq comment-end " */")
  241.   (make-local-variable 'comment-column)
  242.   (setq comment-column 32)
  243.   (make-local-variable 'comment-start-skip)
  244.   (setq comment-start-skip "/\\*+ *")
  245.   (make-local-variable 'comment-indent-function)
  246.   (setq comment-indent-function 'c-comment-indent)
  247.   (make-local-variable 'parse-sexp-ignore-comments)
  248.   (setq parse-sexp-ignore-comments t)
  249.   (run-hooks 'c-mode-hook))
  250.  
  251. (defun c-outline-level ()
  252.   (save-excursion
  253.     (skip-chars-forward "\t ")
  254.     (current-column)))
  255.  
  256. ;; This is used by indent-for-comment
  257. ;; to decide how much to indent a comment in C code
  258. ;; based on its context.
  259. (defun c-comment-indent ()
  260.   (if (looking-at "^/\\*")
  261.       0                ;Existing comment at bol stays there.
  262.     (let ((opoint (point)))
  263.       (save-excursion
  264.     (beginning-of-line)
  265.     (cond ((looking-at "[ \t]*}[ \t]*\\($\\|/\\*\\)")
  266.            ;; A comment following a solitary close-brace
  267.            ;; should have only one space.
  268.            (search-forward "}")
  269.            (1+ (current-column)))
  270.           ((or (looking-at "^#[ \t]*endif[ \t]*")
  271.            (looking-at "^#[ \t]*else[ \t]*"))
  272.            7)            ;2 spaces after #endif
  273.           ((progn
  274.          (goto-char opoint)
  275.          (skip-chars-backward " \t")
  276.          (and (= comment-column 0) (bolp)))
  277.            ;; If comment-column is 0, and nothing but space
  278.            ;; before the comment, align it at 0 rather than 1.
  279.            0)
  280.           (t
  281.            (max (1+ (current-column))    ;Else indent at comment column
  282.             comment-column)))))))    ; except leave at least one space.
  283.  
  284. (defun c-fill-paragraph (&optional arg)
  285.   "Like \\[fill-paragraph] but handle C comments.
  286. If any of the current line is a comment or within a comment,
  287. fill the comment or the paragraph of it that point is in,
  288. preserving the comment indentation or line-starting decorations."
  289.   (interactive "P")
  290.   (let* (comment-start-place
  291.      (first-line
  292.       ;; Check for obvious entry to comment.
  293.       (save-excursion
  294.         (beginning-of-line)
  295.         (skip-chars-forward " \t\n")
  296.         (and (looking-at comment-start-skip)
  297.          (setq comment-start-place (point))))))
  298.     (if (and (eq major-mode 'c++-mode)
  299.          (save-excursion
  300.            (beginning-of-line)
  301.            (looking-at ".*//")))
  302.     (let (fill-prefix
  303.           (paragraph-start
  304.            ;; Lines containing just a comment start or just an end
  305.            ;; should not be filled into paragraphs they are next to.
  306.            (concat 
  307.         paragraph-start
  308.         "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[ \t/*]*$"))
  309.           (paragraph-separate
  310.            (concat
  311.         paragraph-separate
  312.         "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[ \t/*]*$")))
  313.       (save-excursion
  314.         (beginning-of-line)
  315.         ;; Move up to first line of this comment.
  316.         (while (and (not (bobp)) (looking-at "[ \t]*//"))
  317.           (forward-line -1))
  318.         (if (not (looking-at ".*//"))
  319.         (forward-line 1))
  320.         ;; Find the comment start in this line.
  321.         (re-search-forward "[ \t]*//[ \t]*")
  322.         ;; Set the fill-prefix to be what all lines except the first
  323.         ;; should start with.
  324.         (let ((endcol (current-column)))
  325.           (skip-chars-backward " \t")
  326.           (setq fill-prefix
  327.             (concat (make-string (- (current-column) 2) ?\ )
  328.                 "//"
  329.                 (make-string (- endcol (current-column)) ?\ ))))
  330.         (save-restriction
  331.           ;; Narrow down to just the lines of this comment.
  332.           (narrow-to-region (point)
  333.                 (save-excursion
  334.                   (forward-line 1)
  335.                   (while (looking-at "[ \t]*//")
  336.                     (forward-line 1))
  337.                   (point)))
  338.           (insert fill-prefix)
  339.           (fill-paragraph arg)
  340.           (delete-region (point-min)
  341.                  (+ (point-min) (length fill-prefix))))))
  342.       (if (or first-line
  343.           ;; t if we enter a comment between start of function and this line.
  344.           (eq (calculate-c-indent) t)
  345.           ;; t if this line contains a comment starter.
  346.           (setq first-line
  347.             (save-excursion
  348.               (beginning-of-line)
  349.               (prog1
  350.               (re-search-forward comment-start-skip
  351.                          (save-excursion (end-of-line)
  352.                                  (point))
  353.                          t)
  354.             (setq comment-start-place (point))))))
  355.       ;; Inside a comment: fill one comment paragraph.
  356.       (let ((fill-prefix
  357.          ;; The prefix for each line of this paragraph
  358.          ;; is the appropriate part of the start of this line,
  359.          ;; up to the column at which text should be indented.
  360.          (save-excursion
  361.            (beginning-of-line)
  362.            (if (looking-at "[ \t]*/\\*.*\\*/")
  363.                (progn (re-search-forward comment-start-skip)
  364.                   (make-string (current-column) ?\ ))
  365.              (if first-line (forward-line 1))
  366.  
  367.              (let ((line-width (progn (end-of-line) (current-column))))
  368.                (beginning-of-line)
  369.                (prog1
  370.                (buffer-substring
  371.                 (point)
  372.  
  373.                 ;; How shall we decide where the end of the
  374.                 ;; fill-prefix is?
  375.                 ;; calculate-c-indent-within-comment bases its value
  376.                 ;; on the indentation of previous lines; if they're
  377.                 ;; indented specially, it could return a column
  378.                 ;; that's well into the current line's text.  So
  379.                 ;; we'll take at most that many space, tab, or *
  380.                 ;; characters, and use that as our fill prefix.
  381.                 (let ((max-prefix-end
  382.                    (progn
  383.                      (move-to-column
  384.                       (calculate-c-indent-within-comment t)
  385.                       t)
  386.                      (point))))
  387.                   (beginning-of-line)
  388.                   (skip-chars-forward " \t*" max-prefix-end)
  389.                   ;; Don't include part of comment terminator
  390.                   ;; in the fill-prefix.
  391.                   (and (eq (following-char) ?/)
  392.                    (eq (preceding-char) ?*)
  393.                    (backward-char 1))
  394.                   (point)))
  395.  
  396.              ;; If the comment is only one line followed by a blank
  397.              ;; line, calling move-to-column above may have added
  398.              ;; some spaces and tabs to the end of the line; the
  399.              ;; fill-paragraph function will then delete it and the
  400.              ;; newline following it, so we'll lose a blank line
  401.              ;; when we shouldn't.  So delete anything
  402.              ;; move-to-column added to the end of the line.  We
  403.              ;; record the line width instead of the position of the
  404.              ;; old line end because move-to-column might break a
  405.              ;; tab into spaces, and the new characters introduced
  406.              ;; there shouldn't be deleted.
  407.  
  408.              ;; If you can see a better way to do this, please make
  409.              ;; the change.  This seems very messy to me.
  410.              (delete-region (progn (move-to-column line-width)
  411.                            (point))
  412.                     (progn (end-of-line) (point))))))))
  413.  
  414.         (paragraph-start
  415.          ;; Lines containing just a comment start or just an end
  416.          ;; should not be filled into paragraphs they are next to.
  417.          (concat 
  418.           paragraph-start
  419.           "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[ \t/*]*$"))
  420.         (paragraph-separate
  421.          (concat
  422.           paragraph-separate
  423.           "\\|^[ \t]*/\\*[ \t]*$\\|^[ \t]*\\*/[ \t]*$\\|^[ \t/*]*$"))
  424.         (chars-to-delete 0))
  425.         (save-restriction
  426.           ;; Don't fill the comment together with the code following it.
  427.           ;; So temporarily exclude everything before the comment start,
  428.           ;; and everything after the line where the comment ends.
  429.           ;; If comment-start-place is non-nil, the comment starter is there.
  430.           ;; Otherwise, point is inside the comment.
  431.           (narrow-to-region (save-excursion
  432.                   (if comment-start-place
  433.                       (goto-char comment-start-place)
  434.                     (search-backward "/*"))
  435.                   ;; Protect text before the comment start 
  436.                   ;; by excluding it.  Add spaces to bring back 
  437.                   ;; proper indentation of that point.
  438.                   (let ((column (current-column)))
  439.                     (prog1 (point)
  440.                       (setq chars-to-delete column)
  441.                       (insert-char ?\  column))))
  442.                 (save-excursion
  443.                   (if comment-start-place
  444.                       (goto-char (+ comment-start-place 2)))
  445.                   (search-forward "*/" nil 'move)
  446.                   (forward-line 1)
  447.                   (point)))
  448.           (fill-paragraph arg)
  449.           (save-excursion
  450.         ;; Delete the chars we inserted to avoid clobbering
  451.         ;; the stuff before the comment start.
  452.         (goto-char (point-min))
  453.         (if (> chars-to-delete 0)
  454.             (delete-region (point) (+ (point) chars-to-delete)))
  455.         ;; Find the comment ender (should be on last line of buffer,
  456.         ;; given the narrowing) and don't leave it on its own line.
  457.         ;; Do this with a fill command, so as to preserve sentence
  458.         ;; boundaries.
  459.         (goto-char (point-max))
  460.         (forward-line -1)
  461.         (search-forward "*/" nil 'move)
  462.         (beginning-of-line)
  463.         (if (looking-at "[ \t]*\\*/")
  464.             (let ((fill-column (+ fill-column 9999)))
  465.               (forward-line -1)
  466.               (fill-region-as-paragraph (point) (point-max)))))))
  467.     ;; Outside of comments: do ordinary filling.
  468.     (fill-paragraph arg)))))
  469.  
  470. (defun electric-c-brace (arg)
  471.   "Insert character and correct line's indentation."
  472.   (interactive "P")
  473.   (let (insertpos)
  474.     (if (and (not arg)
  475.          (eolp)
  476.          (or (save-excursion
  477.            (skip-chars-backward " \t")
  478.            (bolp))
  479.          (if c-auto-newline (progn (c-indent-line) (newline) t) nil)))
  480.     (progn
  481.       (insert last-command-char)
  482.       (c-indent-line)
  483.       (if c-auto-newline
  484.           (progn
  485.         (newline)
  486.         ;; (newline) may have done auto-fill
  487.         (setq insertpos (- (point) 2))
  488.         (c-indent-line)))
  489.       (save-excursion
  490.         (if insertpos (goto-char (1+ insertpos)))
  491.         (delete-char -1))))
  492.     (if insertpos
  493.     (save-excursion
  494.       (goto-char insertpos)
  495.       (self-insert-command (prefix-numeric-value arg)))
  496.       (self-insert-command (prefix-numeric-value arg)))))
  497.  
  498. (defun electric-c-sharp-sign (arg)
  499.   "Insert character and correct line's indentation."
  500.   (interactive "P")
  501.   (if (save-excursion
  502.     (skip-chars-backward " \t")
  503.     (bolp))
  504.       (let ((c-auto-newline nil))
  505.     (electric-c-terminator arg))
  506.     (self-insert-command (prefix-numeric-value arg))))
  507.  
  508. (defun electric-c-semi (arg)
  509.   "Insert character and correct line's indentation."
  510.   (interactive "P")
  511.   (if c-auto-newline
  512.       (electric-c-terminator arg)
  513.     (self-insert-command (prefix-numeric-value arg))))
  514.  
  515. (defun electric-c-terminator (arg)
  516.   "Insert character and correct line's indentation."
  517.   (interactive "P")
  518.   (let (insertpos (end (point)))
  519.     (if (and (not arg) (eolp)
  520.          (not (save-excursion
  521.             (beginning-of-line)
  522.             (skip-chars-forward " \t")
  523.             (or (= (following-char) ?#)
  524.             ;; Colon is special only after a label, or case ....
  525.             ;; So quickly rule out most other uses of colon
  526.             ;; and do no indentation for them.
  527.             (and (eq last-command-char ?:)
  528.                  (not (looking-at c-switch-label-regexp))
  529.                  (save-excursion
  530.                    (skip-chars-forward "a-zA-Z0-9_$")
  531.                    (skip-chars-forward " \t")
  532.                    (< (point) end)))
  533.             (progn
  534.               (beginning-of-defun)
  535.               (let ((pps (parse-partial-sexp (point) end)))
  536.                 (or (nth 3 pps) (nth 4 pps) (nth 5 pps))))))))
  537.     (progn
  538.       (insert last-command-char)
  539.       (c-indent-line)
  540.       (and c-auto-newline
  541.            (not (c-inside-parens-p))
  542.            (progn
  543.          (newline)
  544.          ;; (newline) may have done auto-fill
  545.          (setq insertpos (- (point) 2))
  546.          (c-indent-line)))
  547.       (save-excursion
  548.         (if insertpos (goto-char (1+ insertpos)))
  549.         (delete-char -1))))
  550.     (if insertpos
  551.     (save-excursion
  552.       (goto-char insertpos)
  553.       (self-insert-command (prefix-numeric-value arg)))
  554.       (self-insert-command (prefix-numeric-value arg)))))
  555.  
  556. (defun c-inside-parens-p ()
  557.   (condition-case ()
  558.       (save-excursion
  559.     (save-restriction
  560.       (narrow-to-region (point)
  561.                 (progn (beginning-of-defun) (point)))
  562.       (goto-char (point-max))
  563.       (= (char-after (or (scan-lists (point) -1 1) (point-min))) ?\()))
  564.     (error nil)))
  565.  
  566. (defun c-indent-command (&optional whole-exp)
  567.   "Indent current line as C code, or in some cases insert a tab character.
  568. If `c-tab-always-indent' is non-nil (the default), always indent current line.
  569. Otherwise, indent the current line only if point is at the left margin or
  570. in the line's indentation; otherwise insert a tab.
  571.  
  572. A numeric argument, regardless of its value, means indent rigidly all the
  573. lines of the expression starting after point so that this line becomes
  574. properly indented.  The relative indentation among the lines of the
  575. expression are preserved."
  576.   (interactive "P")
  577.   (if whole-exp
  578.       ;; If arg, always indent this line as C
  579.       ;; and shift remaining lines of expression the same amount.
  580.       (let ((shift-amt (c-indent-line))
  581.         beg end)
  582.     (save-excursion
  583.       (if c-tab-always-indent
  584.           (beginning-of-line))
  585.       ;; Find beginning of following line.
  586.       (save-excursion
  587.         (forward-line 1) (setq beg (point)))
  588.       ;; Find first beginning-of-sexp for sexp extending past this line.
  589.       (while (< (point) beg)
  590.         (forward-sexp 1)
  591.         (setq end (point))
  592.         (skip-chars-forward " \t\n")))
  593.     (if (> end beg)
  594.         (indent-code-rigidly beg end shift-amt "#")))
  595.     (if (and (not c-tab-always-indent)
  596.          (save-excursion
  597.            (skip-chars-backward " \t")
  598.            (not (bolp))))
  599.     (insert-tab)
  600.       (c-indent-line))))
  601.  
  602. (defun c-indent-line ()
  603.   "Indent current line as C code.
  604. Return the amount the indentation changed by."
  605.   (let ((indent (calculate-c-indent nil))
  606.     beg shift-amt
  607.     (case-fold-search nil)
  608.     (pos (- (point-max) (point))))
  609.     (beginning-of-line)
  610.     (setq beg (point))
  611.     (cond ((eq indent nil)
  612.        (setq indent (current-indentation)))
  613.       ((eq indent t)
  614.        (setq indent (calculate-c-indent-within-comment)))
  615.       ((looking-at "[ \t]*#")
  616.        (setq indent 0))
  617.       (t
  618.        (skip-chars-forward " \t")
  619.        (if (listp indent) (setq indent (car indent)))
  620.        (cond ((or (looking-at c-switch-label-regexp)
  621.               (and (looking-at "[A-Za-z]")
  622.                (save-excursion
  623.                  (forward-sexp 1)
  624.                  (looking-at ":"))))
  625.           (setq indent (max 1 (+ indent c-label-offset))))
  626.          ((and (looking-at "else\\b")
  627.                (not (looking-at "else\\s_")))
  628.           (setq indent (save-excursion
  629.                  (c-backward-to-start-of-if)
  630.                  (current-indentation))))
  631.          ((looking-at "}[ \t]*else")
  632.           (setq indent (save-excursion
  633.                  (forward-char)
  634.                  (backward-sexp)
  635.                  (c-backward-to-start-of-if)
  636.                  (current-indentation))))
  637.          ((and (looking-at "while\\b")
  638.                (save-excursion
  639.              (c-backward-to-start-of-do)))
  640.           ;; This is a `while' that ends a do-while.
  641.           (setq indent (save-excursion
  642.                  (c-backward-to-start-of-do)
  643.                  (current-indentation))))
  644.          ((= (following-char) ?})
  645.           (setq indent (- indent c-indent-level)))
  646.          ((= (following-char) ?{)
  647.           (setq indent (+ indent c-brace-offset))))))
  648.     (skip-chars-forward " \t")
  649.     (setq shift-amt (- indent (current-column)))
  650.     (if (zerop shift-amt)
  651.     (if (> (- (point-max) pos) (point))
  652.         (goto-char (- (point-max) pos)))
  653.       (delete-region beg (point))
  654.       (indent-to indent)
  655.       ;; If initial point was within line's indentation,
  656.       ;; position after the indentation.  Else stay at same point in text.
  657.       (if (> (- (point-max) pos) (point))
  658.       (goto-char (- (point-max) pos))))
  659.     shift-amt))
  660.  
  661. (defun calculate-c-indent (&optional parse-start)
  662.   "Return appropriate indentation for current line as C code.
  663. In usual case returns an integer: the column to indent to.
  664. Returns nil if line starts inside a string, t if in a comment."
  665.   (save-excursion
  666.     (beginning-of-line)
  667.     (let ((indent-point (point))
  668.       (case-fold-search nil)
  669.       state
  670.       containing-sexp)
  671.       (if parse-start
  672.       (goto-char parse-start)
  673.     (beginning-of-defun))
  674.       (while (< (point) indent-point)
  675.     (setq parse-start (point))
  676.     (setq state (parse-partial-sexp (point) indent-point 0))
  677.     (setq containing-sexp (car (cdr state))))
  678.       (cond ((or (nth 3 state) (nth 4 state))
  679.          ;; return nil or t if should not change this line
  680.          (nth 4 state))
  681.         ((null containing-sexp)
  682.          ;; Line is at top level.  May be data or function definition,
  683.          ;; or may be function argument declaration.
  684.          ;; Indent like the previous top level line
  685.          ;; unless that ends in a closeparen without semicolon,
  686.          ;; in which case this line is the first argument decl.
  687.          (goto-char indent-point)
  688.          (skip-chars-forward " \t")
  689.          (if (= (following-char) ?{)
  690.          0   ; Unless it starts a function body
  691.            (c-backward-to-noncomment (or parse-start (point-min)))
  692.            ;; Look at previous line that's at column 0
  693.            ;; to determine whether we are in top-level decls
  694.            ;; or function's arg decls.  Set basic-indent accordingly.
  695.            (let ((basic-indent
  696.               (save-excursion
  697.             (re-search-backward "^[^ \^L\t\n#]" nil 'move)
  698.             (let (comment lim)
  699.               ;; Recognize the DEFUN macro in Emacs.
  700.               (if (save-excursion
  701.                 ;; Move down to the (putative) argnames line.
  702.                 (while (and (not (eobp))
  703.                         (not (looking-at " *[({}#/]")))
  704.                   (forward-line 1))
  705.                 ;; Go back to the DEFUN, if it is one.
  706.                 (condition-case nil
  707.                     (backward-sexp 1)
  708.                   (error))
  709.                 (beginning-of-line)
  710.                 (looking-at "DEFUN\\b"))
  711.                   c-argdecl-indent
  712.                 (if (and (looking-at "\\sw\\|\\s_")
  713.                      ;; This is careful to stop at the first
  714.                      ;; paren if we have
  715.                      ;; int foo Proto ((int, int));
  716.                      (looking-at "[^\"\n=(]*(")
  717.                      (progn
  718.                        (goto-char (1- (match-end 0)))
  719.                        (setq lim (point))
  720.                        (condition-case nil
  721.                        (forward-sexp 1)
  722.                      (error))
  723.                        (skip-chars-forward " \t\f")
  724.                        (and (< (point) indent-point)
  725.                         (not (memq (following-char)
  726.                                '(?\, ?\;)))))
  727.                      ;; Make sure the "function decl" we found
  728.                      ;; is not inside a comment.
  729.                      (progn
  730.                        ;; Move back to the `(' starting arglist
  731.                        (goto-char lim)
  732.                        (beginning-of-line)
  733.                        (while (and (not comment)
  734.                            (search-forward "/*" lim t))
  735.                      (setq comment
  736.                            (not (search-forward "*/" lim t))))
  737.                        (not comment)))
  738.                 c-argdecl-indent 0))))))
  739.          basic-indent)))
  740.  
  741. ;;          ;; Now add a little if this is a continuation line.
  742. ;;          (+ basic-indent (if (or (bobp)
  743. ;;                      (memq (preceding-char) '(?\) ?\; ?\}))
  744. ;;                      ;; Line with zero indentation
  745. ;;                      ;; is probably the return-type
  746. ;;                      ;; of a function definition,
  747. ;;                      ;; so following line is function name.
  748. ;;                      (= (current-indentation) 0))
  749. ;;                     0 c-continued-statement-offset))
  750.  
  751.         ((/= (char-after containing-sexp) ?{)
  752.          ;; line is expression, not statement:
  753.          ;; indent to just after the surrounding open.
  754.          (goto-char (1+ containing-sexp))
  755.          (current-column))
  756.         (t
  757.          ;; Statement level.  Is it a continuation or a new statement?
  758.          ;; Find previous non-comment character.
  759.          (goto-char indent-point)
  760.          (c-backward-to-noncomment containing-sexp)
  761.          ;; Back up over label lines, since they don't
  762.          ;; affect whether our line is a continuation.
  763.          (while (or (eq (preceding-char) ?\,)
  764.             (and (eq (preceding-char) ?:)
  765.                  (or (eq (char-after (- (point) 2)) ?\')
  766.                  (memq (char-syntax (char-after (- (point) 2)))
  767.                        '(?w ?_)))))
  768.            (if (eq (preceding-char) ?\,)
  769.            (progn (forward-char -1)
  770.               (c-backward-to-start-of-continued-exp containing-sexp)))
  771.            (beginning-of-line)
  772.            (c-backward-to-noncomment containing-sexp))
  773.          ;; Check for a preprocessor statement or its continuation lines.
  774.          ;; Move back to end of previous non-preprocessor line,
  775.          ;; or possibly beginning of buffer.
  776.          (let ((found (point)) stop)
  777.            (while (not stop)
  778.          (beginning-of-line)
  779.          (cond ((bobp)
  780.             (setq found (point)
  781.                   stop t))
  782.                ((save-excursion (forward-char -1)
  783.                     (= (preceding-char) ?\\))
  784.             (forward-char -1))
  785.                ;; This line is not preceded by a backslash.
  786.                ;; So either it starts a preprocessor command
  787.                ;; or any following continuation lines
  788.                ;; should not be skipped.
  789.                ((= (following-char) ?#)
  790.             (forward-char -1)
  791.             (setq found (point)))
  792.                (t (setq stop t))))
  793.            (goto-char found))
  794.          ;; Now we get the answer.
  795.          (if (and (not (memq (preceding-char) '(0 ?\, ?\; ?\} ?\{)))
  796.               ;; But don't treat a line with a close-brace
  797.               ;; as a continuation.  It is probably the
  798.               ;; end of an enum type declaration.
  799.               (save-excursion
  800.             (goto-char indent-point)
  801.             (skip-chars-forward " \t")
  802.             (not (= (following-char) ?}))))
  803.          ;; This line is continuation of preceding line's statement;
  804.          ;; indent  c-continued-statement-offset  more than the
  805.          ;; previous line of the statement.
  806.          (progn
  807.            (c-backward-to-start-of-continued-exp containing-sexp)
  808.            (+ c-continued-statement-offset (current-column)
  809.               (if (save-excursion (goto-char indent-point)
  810.                       (skip-chars-forward " \t")
  811.                       (eq (following-char) ?{))
  812.               c-continued-brace-offset 0)))
  813.            ;; This line starts a new statement.
  814.            ;; Position following last unclosed open.
  815.            (goto-char containing-sexp)
  816.            ;; Is line first statement after an open-brace?
  817.            (or
  818.          ;; If no, find that first statement and indent like it.
  819.          (save-excursion
  820.            (forward-char 1)
  821.            (let ((colon-line-end 0))
  822.              (while (progn (skip-chars-forward " \t\n")
  823.                    (looking-at "#\\|/\\*\\|case[ \t\n'/(].*:\\|[a-zA-Z0-9_$]*:"))
  824.                ;; Skip over comments and labels following openbrace.
  825.                (cond ((= (following-char) ?\#)
  826.                   (forward-line 1))
  827.                  ((= (following-char) ?\/)
  828.                   (forward-char 2)
  829.                   (search-forward "*/" nil 'move))
  830.                  ;; case or label:
  831.                  (t
  832.                   (save-excursion (end-of-line)
  833.                           (setq colon-line-end (point)))
  834.                   (search-forward ":"))))
  835.              ;; The first following code counts
  836.              ;; if it is before the line we want to indent.
  837.              (and (< (point) indent-point)
  838.               (- 
  839.                (if (> colon-line-end (point))
  840.                    (- (current-indentation) c-label-offset)
  841.                  (current-column))
  842.                ;; If prev stmt starts with open-brace, that
  843.                ;; open brace was offset by c-brace-offset.
  844.                ;; Compensate to get the column where
  845.                ;; an ordinary statement would start.
  846.                (if (= (following-char) ?\{) c-brace-offset 0)))))
  847.          ;; If no previous statement,
  848.          ;; indent it relative to line brace is on.
  849.          ;; For open brace in column zero, don't let statement
  850.          ;; start there too.  If c-indent-level is zero,
  851.          ;; use c-brace-offset + c-continued-statement-offset instead.
  852.          ;; For open-braces not the first thing in a line,
  853.          ;; add in c-brace-imaginary-offset.
  854.          (+ (if (and (bolp) (zerop c-indent-level))
  855.             (+ c-brace-offset c-continued-statement-offset)
  856.               c-indent-level)
  857.             ;; Move back over whitespace before the openbrace.
  858.             ;; If openbrace is not first nonwhite thing on the line,
  859.             ;; add the c-brace-imaginary-offset.
  860.             (progn (skip-chars-backward " \t")
  861.                (if (bolp) 0 c-brace-imaginary-offset))
  862.             ;; If the openbrace is preceded by a parenthesized exp,
  863.             ;; move to the beginning of that;
  864.             ;; possibly a different line
  865.             (progn
  866.               (if (eq (preceding-char) ?\))
  867.               (forward-sexp -1))
  868.               ;; Get initial indentation of the line we are on.
  869.               (current-indentation))))))))))
  870.  
  871. (defun calculate-c-indent-within-comment (&optional after-star)
  872.   "Return the indentation amount for line inside a block comment.
  873. Optional arg AFTER-STAR means, if lines in the comment have a leading star,
  874. return the indentation of the text that would follow this star."
  875.   (let (end star-start)
  876.     (save-excursion
  877.       (beginning-of-line)
  878.       (skip-chars-forward " \t")
  879.       (setq star-start (= (following-char) ?\*))
  880.       (skip-chars-backward " \t\n")
  881.       (setq end (point))
  882.       (beginning-of-line)
  883.       (skip-chars-forward " \t")
  884.       (if after-star
  885.       (and (looking-at "\\*")
  886.            (re-search-forward "\\*[ \t]*")))
  887.       (and (re-search-forward "/\\*[ \t]*" end t)
  888.        star-start
  889.        (not after-star)
  890.        (goto-char (1+ (match-beginning 0))))
  891.       (if (and (looking-at "[ \t]*$") (= (preceding-char) ?\*))
  892.       (1+ (current-column))
  893.     (current-column)))))
  894.  
  895.  
  896. (defun c-backward-to-noncomment (lim)
  897.   (let (opoint stop)
  898.     (while (not stop)
  899.       (skip-chars-backward " \t\n\f" lim)
  900.       (setq opoint (point))
  901.       (if (and (>= (point) (+ 2 lim))
  902.            (save-excursion
  903.          (forward-char -2)
  904.          (looking-at "\\*/")))
  905.       (search-backward "/*" lim 'move)
  906.     (setq stop (or (<= (point) lim)
  907.                (save-excursion
  908.              (beginning-of-line)
  909.              (skip-chars-forward " \t")
  910.              (not (looking-at "#")))))
  911.     (or stop (beginning-of-line))))))
  912.  
  913. (defun c-backward-to-start-of-continued-exp (lim)
  914.   (if (memq (preceding-char) '(?\) ?\"))
  915.       (forward-sexp -1))
  916.   (beginning-of-line)
  917.   (if (<= (point) lim)
  918.       (goto-char (1+ lim)))
  919.   (skip-chars-forward " \t"))
  920.  
  921. (defun c-backward-to-start-of-if (&optional limit)
  922.   "Move to the start of the last \"unbalanced\" `if'."
  923.   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
  924.   (let ((if-level 1)
  925.     (case-fold-search nil))
  926.     (while (and (not (bobp)) (not (zerop if-level)))
  927.       (backward-sexp 1)
  928.       (cond ((looking-at "else\\b")
  929.          (setq if-level (1+ if-level)))
  930.         ((looking-at "if\\b")
  931.          (setq if-level (1- if-level)))
  932.         ((< (point) limit)
  933.          (setq if-level 0)
  934.          (goto-char limit))))))
  935.  
  936. (defun c-backward-to-start-of-do (&optional limit)
  937.   "If point follows a `do' statement, move to beginning of it and return t.
  938. Otherwise return nil and don't move point."
  939.   (or limit (setq limit (save-excursion (beginning-of-defun) (point))))
  940.   (let ((first t)
  941.     (startpos (point))
  942.     (done nil))
  943.     (while (not done)
  944.       (let ((next-start (point)))
  945.     (condition-case nil
  946.         ;; Move back one token or one brace or paren group.
  947.         (backward-sexp 1)
  948.       ;; If we find an open-brace, we lose.
  949.       (error (setq done 'fail)))
  950.     (if done
  951.         nil
  952.       ;; If we reached a `do', we win.
  953.       (if (looking-at "do\\b")
  954.           (setq done 'succeed)
  955.         ;; Otherwise, if we skipped a semicolon, we lose.
  956.         ;; (Exception: we can skip one semicolon before getting
  957.         ;; to a the last token of the statement, unless that token
  958.         ;; is a close brace.)
  959.         (if (save-excursion
  960.           (forward-sexp 1)
  961.           (or (and (not first) (= (preceding-char) ?}))
  962.               (search-forward ";" next-start t
  963.                       (if (and first
  964.                            (/= (preceding-char) ?}))
  965.                       2 1))))
  966.         (setq done 'fail)
  967.           (setq first nil)
  968.           ;; If we go too far back in the buffer, we lose.
  969.           (if (< (point) limit)
  970.           (setq done 'fail)))))))
  971.     (if (eq done 'succeed)
  972.     t
  973.       (goto-char startpos)
  974.       nil)))
  975.  
  976. (defun c-beginning-of-statement (count)
  977.   "Go to the beginning of the innermost C statement.
  978. With prefix arg, go back N - 1 statements.  If already at the beginning of a
  979. statement then go to the beginning of the preceding one.
  980. If within a string or comment, or next to a comment (only whitespace between),
  981. move by sentences instead of statements."
  982.   (interactive "p")
  983.   (let ((here (point)) state)
  984.     (save-excursion
  985.       (beginning-of-defun)
  986.       (setq state (parse-partial-sexp (point) here nil nil)))
  987.     (if (or (nth 3 state) (nth 4 state)
  988.         (looking-at (concat "[ \t]*" comment-start-skip))
  989.         (save-excursion (skip-chars-backward " \t")
  990.                 (goto-char (- (point) 2))
  991.                 (looking-at "\\*/")))
  992.     (forward-sentence (- count))
  993.       (while (> count 0)
  994.     (c-beginning-of-statement-1)
  995.     (setq count (1- count)))
  996.       (while (< count 0)
  997.     (c-end-of-statement-1)
  998.     (setq count (1+ count))))))
  999.  
  1000. (defun c-end-of-statement (count)
  1001.   "Go to the end of the innermost C statement.
  1002. With prefix arg, go forward N - 1 statements.
  1003. Move forward to end of the next statement if already at end.
  1004. If within a string or comment, move by sentences instead of statements."
  1005.   (interactive "p")
  1006.   (c-beginning-of-statement (- count)))
  1007.  
  1008. (defun c-beginning-of-statement-1 ()
  1009.   (let ((last-begin (point))
  1010.     (first t))
  1011.     (condition-case ()
  1012.     (progn
  1013.       (while (and (not (bobp))
  1014.               (progn
  1015.             (backward-sexp 1)
  1016.             (or first
  1017.                 (not (re-search-forward "[;{}]" last-begin t)))))
  1018.         (setq last-begin (point) first nil))
  1019.       (goto-char last-begin))
  1020.       (error (if first (backward-up-list 1) (goto-char last-begin))))))
  1021.  
  1022. (defun c-end-of-statement-1 ()
  1023.   (condition-case ()
  1024.       (progn
  1025.     (while (and (not (eobp))
  1026.             (let ((beg (point)))
  1027.               (forward-sexp 1)
  1028.               (let ((end (point)))
  1029.             (save-excursion
  1030.               (goto-char beg)
  1031.               (not (re-search-forward "[;{}]" end t)))))))
  1032.     (re-search-backward "[;}]")
  1033.     (forward-char 1))
  1034.     (error 
  1035.      (let ((beg (point)))
  1036.        (backward-up-list -1)
  1037.        (let ((end (point)))
  1038.      (goto-char beg)
  1039.      (search-forward ";" end 'move))))))
  1040.  
  1041. (defun mark-c-function ()
  1042.   "Put mark at end of C function, point at beginning."
  1043.   (interactive)
  1044.   (push-mark (point))
  1045.   (end-of-defun)
  1046.   (push-mark (point) nil t)
  1047.   (beginning-of-defun)
  1048.   (backward-paragraph))
  1049.  
  1050. ;; Idea of ENDPOS is, indent each line, stopping when
  1051. ;; ENDPOS is encountered.  But it's too much of a pain to make that work.
  1052. (defun indent-c-exp (&optional endpos)
  1053.   "Indent each line of the C grouping following point."
  1054.   (interactive)
  1055.   (let* ((indent-stack (list nil))
  1056.      (opoint (point))  ;; May be altered below.
  1057.      (contain-stack
  1058.       (list (if endpos
  1059.             (let (funbeg)
  1060.               ;; Find previous fcn-start.
  1061.               (save-excursion (forward-char 1)
  1062.                       (beginning-of-defun)
  1063.                       (setq funbeg (point)))
  1064.               (setq opoint funbeg)
  1065.               ;; Try to find containing open,
  1066.               ;; but don't scan past that fcn-start.
  1067.               (save-restriction
  1068.             (narrow-to-region funbeg (point))
  1069.             (condition-case nil
  1070.                 (save-excursion
  1071.                   (backward-up-list 1)
  1072.                   (point))
  1073.               ;; We gave up: must be between fcns.
  1074.               ;; Set opoint to beg of prev fcn
  1075.               ;; since otherwise calculate-c-indent
  1076.               ;; will get wrong answers.
  1077.               (error (setq opoint funbeg)
  1078.                  (point)))))
  1079.           (point))))
  1080.      (case-fold-search nil)
  1081.      restart outer-loop-done inner-loop-done state ostate
  1082.      this-indent last-sexp
  1083.      at-else at-brace at-while
  1084.      last-depth this-point
  1085.      (next-depth 0))
  1086.     ;; If the braces don't match, get an error right away.
  1087.     (save-excursion
  1088.       (forward-sexp 1))
  1089.     ;; Realign the comment on the first line, even though we don't reindent it.
  1090.     (save-excursion
  1091.       (let ((beg (point)))
  1092.     (and (re-search-forward
  1093.           comment-start-skip
  1094.           (save-excursion (end-of-line) (point)) t)
  1095.          ;; Make sure this isn't a comment alone on a line
  1096.          ;; (which should be indented like code instead).
  1097.          (save-excursion
  1098.            (goto-char (match-beginning 0))
  1099.            (skip-chars-backward " \t")
  1100.            (not (bolp)))
  1101.          ;; Make sure the comment starter we found
  1102.          ;; is not actually in a string or quoted.
  1103.          (let ((new-state
  1104.             (parse-partial-sexp beg (point)
  1105.                     nil nil state)))
  1106.            (and (not (nth 3 new-state)) (not (nth 5 new-state))))
  1107.         (progn (indent-for-comment) (beginning-of-line)))))
  1108.     (save-excursion
  1109.       (setq outer-loop-done nil)
  1110.       (while (and (not (eobp))
  1111.           (if endpos (< (point) endpos)
  1112.             (not outer-loop-done)))
  1113.     (setq last-depth next-depth)
  1114.     ;; Compute how depth changes over this line
  1115.     ;; plus enough other lines to get to one that
  1116.     ;; does not end inside a comment or string.
  1117.     ;; Meanwhile, do appropriate indentation on comment lines.
  1118.     (setq inner-loop-done nil)
  1119.     (while (and (not inner-loop-done)
  1120.             (not (and (eobp) (setq outer-loop-done t))))
  1121.       (setq ostate state)
  1122.       (setq state (parse-partial-sexp (point) (progn (end-of-line) (point))
  1123.                       nil nil state))
  1124.       (setq next-depth (car state))
  1125.       (if (and (car (cdr (cdr state)))
  1126.            (>= (car (cdr (cdr state))) 0))
  1127.           (setq last-sexp (car (cdr (cdr state)))))
  1128.       ;; If this line started within a comment, indent it as such.
  1129.       (if (or (nth 4 ostate) (nth 7 ostate))
  1130.           (c-indent-line))
  1131.       ;; If it ends outside of comments or strings, exit the inner loop.
  1132.       ;; Otherwise move on to next line.
  1133.       (if (or (nth 3 state) (nth 4 state) (nth 7 state))
  1134.           (forward-line 1)
  1135.         (setq inner-loop-done t)))
  1136.     (and endpos
  1137.          (while (< next-depth 0)
  1138.            (setq indent-stack (append indent-stack (list nil)))
  1139.            (setq contain-stack (append contain-stack (list nil)))
  1140.            (setq next-depth (1+ next-depth))
  1141.            (setq last-depth (1+ last-depth))
  1142.            (setcar (nthcdr 6 state) (1+ (nth 6 state)))))
  1143.     (setq outer-loop-done (and (not endpos) (<= next-depth 0)))
  1144.     (if outer-loop-done
  1145.         nil
  1146.       ;; If this line had ..))) (((.. in it, pop out of the levels
  1147.       ;; that ended anywhere in this line, even if the final depth
  1148.       ;; doesn't indicate that they ended.
  1149.       (while (> last-depth (nth 6 state))
  1150.         (setq indent-stack (cdr indent-stack)
  1151.           contain-stack (cdr contain-stack)
  1152.           last-depth (1- last-depth)))
  1153.       (if (/= last-depth next-depth)
  1154.           (setq last-sexp nil))
  1155.       ;; Add levels for any parens that were started in this line.
  1156.       (while (< last-depth next-depth)
  1157.         (setq indent-stack (cons nil indent-stack)
  1158.           contain-stack (cons nil contain-stack)
  1159.           last-depth (1+ last-depth)))
  1160.       (if (null (car contain-stack))
  1161.           (setcar contain-stack (or (car (cdr state))
  1162.                     (save-excursion (forward-sexp -1)
  1163.                             (point)))))
  1164.       (forward-line 1)
  1165.       (skip-chars-forward " \t")
  1166.       ;; Don't really reindent if the line is just whitespace,
  1167.       ;; or if it is past the endpos.
  1168.       ;; (The exit test in the outer while
  1169.       ;; does not exit until we have passed the first line
  1170.       ;; past the region.)
  1171.       (if (or (eolp) (and endpos (>= (point) endpos)))
  1172.           nil
  1173.         (if (and (car indent-stack)
  1174.              (>= (car indent-stack) 0))
  1175.         ;; Line is on an existing nesting level.
  1176.         ;; Lines inside parens are handled specially.
  1177.         (if (/= (char-after (car contain-stack)) ?{)
  1178.             (setq this-indent (car indent-stack))
  1179.           ;; Line is at statement level.
  1180.           ;; Is it a new statement?  Is it an else?
  1181.           ;; Find last non-comment character before this line
  1182.           (save-excursion
  1183.             (setq this-point (point))
  1184.             (setq at-else (looking-at "else\\W"))
  1185.             (setq at-brace (= (following-char) ?{))
  1186.             (setq at-while (looking-at "while\\b"))
  1187.             (if (= (following-char) ?})
  1188.             (setq this-indent (car indent-stack))
  1189.               (c-backward-to-noncomment opoint)
  1190.               (if (not (memq (preceding-char) '(0 ?\, ?\; ?} ?: ?{)))
  1191.               ;; Preceding line did not end in comma or semi;
  1192.               ;; indent this line  c-continued-statement-offset
  1193.               ;; more than previous.
  1194.               (progn
  1195.                 (c-backward-to-start-of-continued-exp (car contain-stack))
  1196.                 (setq this-indent
  1197.                   (+ c-continued-statement-offset (current-column)
  1198.                      (if at-brace c-continued-brace-offset 0))))
  1199.             ;; Preceding line ended in comma or semi;
  1200.             ;; use the standard indent for this level.
  1201.             (cond (at-else (progn (c-backward-to-start-of-if opoint)
  1202.                           (setq this-indent
  1203.                             (current-indentation))))
  1204.                   ((and at-while (c-backward-to-start-of-do opoint))
  1205.                    (setq this-indent (current-indentation)))
  1206.                   ((eq (preceding-char) ?\,)
  1207.                    (goto-char this-point)
  1208.                    (setq this-indent (calculate-c-indent)))
  1209.                   (t (setq this-indent (car indent-stack))))))))
  1210.           ;; Just started a new nesting level.
  1211.           ;; Compute the standard indent for this level.
  1212.           (let ((val (calculate-c-indent
  1213.                (if (car indent-stack)
  1214.                    (- (car indent-stack))
  1215.                  opoint))))
  1216.         ;; t means we are in a block comment and should
  1217.         ;; calculate accordingly.
  1218.         (if (eq val t)
  1219.             (setq val (calculate-c-indent-within-comment)))
  1220.         (setcar indent-stack
  1221.             (setq this-indent val))))
  1222.         ;; Adjust line indentation according to its contents
  1223.         (if (or (looking-at c-switch-label-regexp)
  1224.             (and (looking-at "[A-Za-z]")
  1225.              (save-excursion
  1226.                (forward-sexp 1)
  1227.                (looking-at ":"))))
  1228.         (setq this-indent (max 1 (+ this-indent c-label-offset))))
  1229.         (if (= (following-char) ?})
  1230.         (setq this-indent (- this-indent c-indent-level)))
  1231.         (if (= (following-char) ?{)
  1232.         ;; Don't move an open-brace in column 0.
  1233.         ;; This is good when constructs such as
  1234.         ;; `extern "C" {' surround a function definition
  1235.         ;; that should be indented as usual.
  1236.         ;; It is also good for nested functions.
  1237.         ;; It is bad when an open-brace is indented at column 0
  1238.         ;; and you want to fix that, but we can't win 'em all.
  1239.         (if (zerop (current-column))
  1240.             (setq this-indent 0)
  1241.           (setq this-indent (+ this-indent c-brace-offset))))
  1242.         ;; Don't leave indentation in empty lines.
  1243.         (if (eolp) (setq this-indent 0))
  1244.         ;; Put chosen indentation into effect.
  1245.         (or (= (current-column) this-indent)
  1246.         (= (following-char) ?\#)
  1247.         (progn
  1248.           (delete-region (point) (progn (beginning-of-line) (point)))
  1249.           (indent-to this-indent)))
  1250.         ;; Indent any comment following the text.
  1251.         (or (looking-at comment-start-skip)
  1252.         (save-excursion
  1253.           (let ((beg (point)))
  1254.             (and (re-search-forward
  1255.               comment-start-skip
  1256.               (save-excursion (end-of-line) (point)) t)
  1257.              ;; Make sure the comment starter we found
  1258.              ;; is not actually in a string or quoted.
  1259.              (let ((new-state
  1260.                 (parse-partial-sexp beg (point)
  1261.                             nil nil state)))
  1262.                (and (not (nth 3 new-state)) (not (nth 5 new-state))))
  1263.              (indent-for-comment)))))))))))
  1264.  
  1265. ;; Look at all comment-start strings in the current line after point.
  1266. ;; Return t if one of them starts a real comment.
  1267. ;; This is not used yet, because indent-for-comment
  1268. ;; isn't smart enough to handle the cases this can find.
  1269. (defun indent-c-find-real-comment ()
  1270.   (let (win)
  1271.     (while (and (not win)
  1272.         (re-search-forward comment-start-skip
  1273.                    (save-excursion (end-of-line) (point))
  1274.                    t))
  1275.       ;; Make sure the comment start is not quoted.
  1276.       (let ((state-1
  1277.          (parse-partial-sexp
  1278.           (save-excursion (beginning-of-line) (point))
  1279.           (point) nil nil state)))
  1280.     (setq win (and (null (nth 3 state-1)) (null (nth 5 state-1))))))
  1281.     win))
  1282.  
  1283. ;; Indent every line whose first char is between START and END inclusive.
  1284. (defun c-indent-region (start end)
  1285.   (save-excursion
  1286.     (goto-char start)
  1287.     ;; Advance to first nonblank line.
  1288.     (skip-chars-forward " \t\n")
  1289.     (beginning-of-line)
  1290.     (let ((endmark (copy-marker end))
  1291.       (c-tab-always-indent t))
  1292.       (while (and (bolp) (not (eobp)) (< (point) endmark))
  1293.     ;; Indent one line as with TAB.
  1294.     (let ((shift-amt (c-indent-line))
  1295.           nextline sexpbeg sexpend)
  1296.       (if (save-excursion (beginning-of-line) (looking-at "[ \t]*#"))
  1297.           (forward-line 1)
  1298.         (save-excursion
  1299.           ;; Find beginning of following line.
  1300.           (save-excursion
  1301.         (forward-line 1) (setq nextline (point)))
  1302.           ;; Find first beginning-of-sexp for sexp extending past this line.
  1303.           (beginning-of-line)
  1304.           (while (< (point) nextline)
  1305.         (condition-case nil
  1306.             (progn
  1307.               (forward-sexp 1)
  1308.               (setq sexpend (point-marker)))
  1309.           (error (setq sexpend nil)
  1310.              (goto-char nextline)))
  1311.         (skip-chars-forward " \t\n"))
  1312.           (if sexpend
  1313.           (progn
  1314.             ;; Make sure the sexp we found really starts on the
  1315.             ;; current line and extends past it.
  1316.             (goto-char sexpend)
  1317.             (backward-sexp 1)
  1318.             (setq sexpbeg (point)))))
  1319.         ;; If that sexp ends within the region,
  1320.         ;; indent it all at once, fast.
  1321.         (if (and sexpend (> sexpend nextline) (<= sexpend endmark)
  1322.              (< sexpbeg nextline))
  1323.         (progn
  1324.           (indent-c-exp)
  1325.           (goto-char sexpend)))
  1326.         ;; Move to following line and try again.
  1327.         (and sexpend (set-marker sexpend nil))
  1328.         (forward-line 1))))
  1329.       (set-marker endmark nil))))
  1330.  
  1331. (defun set-c-style (style &optional global)
  1332.   "Set C-mode variables to use one of several different indentation styles.
  1333. The arguments are a string representing the desired style
  1334. and a flag which, if non-nil, means to set the style globally.
  1335. \(Interactively, the flag comes from the prefix argument.)
  1336. Available styles are GNU, K&R, BSD and Whitesmith."
  1337.   (interactive (list (completing-read "Use which C indentation style? "
  1338.                                       c-style-alist nil t)
  1339.              current-prefix-arg))
  1340.   (let ((vars (cdr (assoc style c-style-alist))))
  1341.     (or vars
  1342.     (error "Invalid C indentation style `%s'" style))
  1343.     (while vars
  1344.       (or global
  1345.       (make-local-variable (car (car vars))))
  1346.       (set (car (car vars)) (cdr (car vars)))
  1347.       (setq vars (cdr vars)))))
  1348.  
  1349. ;;; This page handles insertion and removal of backslashes for C macros.
  1350.  
  1351. (defvar c-backslash-column 48
  1352.   "*Minimum column for end-of-line backslashes of macro definitions.")
  1353.  
  1354. (defun c-backslash-region (from to delete-flag)
  1355.   "Insert, align, or delete end-of-line backslashes on the lines in the region.
  1356. With no argument, inserts backslashes and aligns existing backslashes.
  1357. With an argument, deletes the backslashes.
  1358.  
  1359. This function does not modify the last line of the region if the region ends 
  1360. right at the start of the following line; it does not modify blank lines
  1361. at the start of the region.  So you can put the region around an entire macro
  1362. definition and conveniently use this command."
  1363.   (interactive "r\nP")
  1364.   (save-excursion
  1365.     (goto-char from)
  1366.     (let ((column c-backslash-column)
  1367.       (endmark (make-marker)))
  1368.       (move-marker endmark to)
  1369.       ;; Compute the smallest column number past the ends of all the lines.
  1370.       (if (not delete-flag)
  1371.       (while (< (point) to)
  1372.         (end-of-line)
  1373.         (if (= (preceding-char) ?\\)
  1374.         (progn (forward-char -1)
  1375.                (skip-chars-backward " \t")))
  1376.         (setq column (max column (1+ (current-column))))
  1377.         (forward-line 1)))
  1378.       ;; Adjust upward to a tab column, if that doesn't push past the margin.
  1379.       (if (> (% column tab-width) 0)
  1380.       (let ((adjusted (* (/ (+ column tab-width -1) tab-width) tab-width)))
  1381.         (if (< adjusted (window-width))
  1382.         (setq column adjusted))))
  1383.       ;; Don't modify blank lines at start of region.
  1384.       (goto-char from)
  1385.       (while (and (< (point) endmark) (eolp))
  1386.     (forward-line 1))
  1387.       ;; Add or remove backslashes on all the lines.
  1388.       (while (and (< (point) endmark)
  1389.           ;; Don't backslashify the last line
  1390.           ;; if the region ends right at the start of the next line.
  1391.           (save-excursion
  1392.             (forward-line 1)
  1393.             (< (point) endmark)))
  1394.     (if (not delete-flag)
  1395.         (c-append-backslash column)
  1396.       (c-delete-backslash))
  1397.     (forward-line 1))
  1398.       (move-marker endmark nil))))
  1399.  
  1400. (defun c-append-backslash (column)
  1401.   (end-of-line)
  1402.   ;; Note that "\\\\" is needed to get one backslash.
  1403.   (if (= (preceding-char) ?\\)
  1404.       (progn (forward-char -1)
  1405.          (delete-horizontal-space)
  1406.          (indent-to column))
  1407.     (indent-to column)
  1408.     (insert "\\")))
  1409.  
  1410. (defun c-delete-backslash ()
  1411.   (end-of-line)
  1412.   (or (bolp)
  1413.       (progn
  1414.     (forward-char -1)
  1415.     (if (looking-at "\\\\")
  1416.         (delete-region (1+ (point))
  1417.                (progn (skip-chars-backward " \t") (point)))))))
  1418.  
  1419. (defun c-up-conditional (count)
  1420.   "Move back to the containing preprocessor conditional, leaving mark behind.
  1421. A prefix argument acts as a repeat count.  With a negative argument,
  1422. move forward to the end of the containing preprocessor conditional.
  1423. When going backwards, `#elif' is treated like `#else' followed by `#if'.
  1424. When going forwards, `#elif' is ignored."
  1425.   (interactive "p")
  1426.   (c-forward-conditional (- count) t))
  1427.  
  1428. (defun c-backward-conditional (count &optional up-flag)
  1429.   "Move back across a preprocessor conditional, leaving mark behind.
  1430. A prefix argument acts as a repeat count.  With a negative argument,
  1431. move forward across a preprocessor conditional."
  1432.   (interactive "p")
  1433.   (c-forward-conditional (- count) up-flag))
  1434.  
  1435. (defun c-forward-conditional (count &optional up-flag)
  1436.   "Move forward across a preprocessor conditional, leaving mark behind.
  1437. A prefix argument acts as a repeat count.  With a negative argument,
  1438. move backward across a preprocessor conditional."
  1439.   (interactive "p")
  1440.   (let* ((forward (> count 0))
  1441.      (increment (if forward -1 1))
  1442.      (search-function (if forward 're-search-forward 're-search-backward))
  1443.      (opoint (point))
  1444.      (new))
  1445.     (save-excursion
  1446.       (while (/= count 0)
  1447.     (let ((depth (if up-flag 0 -1)) found)
  1448.       (save-excursion
  1449.         ;; Find the "next" significant line in the proper direction.
  1450.         (while (and (not found)
  1451.             ;; Rather than searching for a # sign that comes
  1452.             ;; at the beginning of a line aside from whitespace,
  1453.             ;; search first for a string starting with # sign.
  1454.             ;; Then verify what precedes it.
  1455.             ;; This is faster on account of the fastmap feature of
  1456.             ;; the regexp matcher.
  1457.             (funcall search-function
  1458.                  "#[ \t]*\\(if\\|elif\\|endif\\)"
  1459.                  nil t))
  1460.           (beginning-of-line)
  1461.           ;; Now verify it is really a preproc line.
  1462.           (if (looking-at "^[ \t]*#[ \t]*\\(if\\|elif\\|endif\\)")
  1463.           (let ((prev depth))
  1464.             ;; Update depth according to what we found.
  1465.             (beginning-of-line)
  1466.             (cond ((looking-at "[ \t]*#[ \t]*endif")
  1467.                (setq depth (+ depth increment)))
  1468.               ((looking-at "[ \t]*#[ \t]*elif")
  1469.                (if (and forward (= depth 0))
  1470.                    (setq found (point))))
  1471.               (t (setq depth (- depth increment))))
  1472.             ;; If we are trying to move across, and we find
  1473.             ;; an end before we find a beginning, get an error.
  1474.             (if (and (< prev 0) (< depth prev))
  1475.             (error (if forward
  1476.                    "No following conditional at this level"
  1477.                  "No previous conditional at this level")))
  1478.             ;; When searching forward, start from next line
  1479.             ;; so that we don't find the same line again.
  1480.             (if forward (forward-line 1))
  1481.             ;; If this line exits a level of conditional, exit inner loop.
  1482.             (if (< depth 0)
  1483.             (setq found (point)))))))
  1484.       (or found
  1485.           (error "No containing preprocessor conditional"))
  1486.       (goto-char (setq new found)))
  1487.     (setq count (+ count increment))))
  1488.     (push-mark)
  1489.     (goto-char new)))
  1490.  
  1491. ;;; c-mode.el ends here
  1492.