This manual is for CC Mode in Emacs.

Copyright © 1995, 1996, 1997, 1998, 1999, 2000, 2001, 2002, 2003 Free Software Foundation, Inc.

     Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.1 or any later version published by the Free Software Foundation; with the Invariant Sections being ``The GNU Manifesto'', ``Distribution'' and ``GNU GENERAL PUBLIC LICENSE'', with the Front-Cover texts being ``A GNU Manual'', and with the Back-Cover Texts as in (a) below.  A copy of the license is included in the section entitled ``GNU Free Documentation License'' in the Emacs manual.

     (a) The FSF's Back-Cover Text is: ``You have freedom to copy and modify this GNU Manual, like GNU software.  Copies published by the Free Software Foundation raise funds for GNU development.''

     This document is part of a collection distributed under the GNU Free Documentation License.  If you want to distribute this document separately from the collection, you can do so by adding a copy of the license to the document, as described in section 6 of the license.

CC Mode
*******

CC Mode is a GNU Emacs mode for editing files containing C, C++, Objective-C, Java, CORBA IDL (and the variants PSDL and CIDL), Pike code and to a certain extent, AWK code see AWK Mode.  It provides syntax-based indentation, font locking, and has several handy commands and some minor modes to make the editing easier.  It does not provide tools to look up and navigate between functions, classes etc - there are other packages for that.

Introduction
************

Welcome to CC Mode, a GNU Emacs mode for editing files containing C, C++, Objective-C, Java, CORBA IDL (and the variants CORBA PSDL and CIDL), Pike and to a certain extent, AWK code (see AWK Mode).  This incarnation of the mode is descended from c-mode.el (also called ``Boring Old C Mode'' or BOCM :-), and c++-mode.el version 2, which Barry has been maintaining since 1992.  Late in 1997, Martin joined the CC Mode Maintainers Team, and implemented the Pike support. As of 2000 Martin has taken over as the sole maintainer.  CC Mode did not originally contain the font lock support for its languages --- that was added in version 5.30.  AWK support was also added in 5.30 by Alan Mackenzie.

This manual describes CC Mode version 5.30.

CC Mode supports the editing of K&R and ANSI C, C++, Objective-C, Java, CORBA's Interface Definition Language, Pike (A C-like scripting language with its roots in the LPC language used in some MUD engines.  See http://pike.ida.liu.se/.) and AWK files.  In this way, you can easily set up consistent font locking and coding styles for use in editing all of these languages, although AWK is not yet as uniformly integrated as the other languages.

Note that the name of this package is ``CC Mode,'' but there is no top level cc-mode entry point.  All of the variables, commands, and functions in CC Mode are prefixed with c-THING, and c-mode, c++-mode, objc-mode, java-mode, idl-mode, pike-mode, and awk-mode entry points are provided.  This package is intended to be a replacement for c-mode.el, c++-mode.el and awk-mode.el.

A special word of thanks goes to Krishna Padmasola for his work in converting the original README file to Texinfo format.  I'd also like to thank all the CC Mode victims who help enormously during the early beta stages of CC Mode's development.

Getting Connected
*****************

If you got this version of CC Mode with Emacs or XEmacs, it should work just fine right out of the box.  Note however that you may not have the latest CC Mode release and may want to upgrade your copy.

If you are upgrading an existing CC Mode installation, please see the README file for installation details.  CC Mode may not work with older versions of Emacs or XEmacs.  See the CC Mode release notes at http://cc-mode.sourceforge.net for the latest information on Emacs version and package compatibility (see Getting the Latest CC Mode Release).

 -- Command: c-version
     You can find out what version of CC Mode you are using by visiting a C file and entering M-x c-version RET.  You should see this message in the echo area:

          Using CC Mode version 5.XX

     where XX is the minor release number.

Indentation Engine
******************

CC Mode has an indentation engine that provides a flexible and general mechanism for customizing indentation. It separates indentation calculation into two steps: first, CC Mode analyzes the line of code being indented to determine the kind of language construct it's looking at, then it applies user defined offsets to the current line based on this analysis.

This section will briefly cover how indentation is calculated in CC Mode. It is important to understand the indentation model being used so that you will know how to customize CC Mode for your personal coding style.  All the details are in Customizing Indentation, and later chapters.

 -- User Option: c-syntactic-indentation
     Syntactic analysis for indentation is done when this is non-nil (which is the default).  When it's nil every line is just indented to the same level as the previous one, and TAB (c-indent-command) adjusts the indentation in steps of c-basic-offset.  The indentation style has no effect, nor any of the indentation associated variables, e.g., c-special-indent-hook.

Syntactic Analysis
==================

The first thing CC Mode does when indenting a line of code, is to analyze the line, determining the syntactic component list of the construct on that line.  A syntactic component consists of a pair of elements (in lisp parlance, a cons cell), the first being a syntactic symbol, the second being a relative buffer position.  Syntactic symbols describe elements of C code (Unless otherwise noted, the term ``C code'' refers to all the C-like languages.), e.g., statement, substatement, class-open, class-close, etc.  See Syntactic Symbols, for a complete list of currently recognized syntactic symbols and their semantics.  The style variable c-offsets-alist also contains the list of currently supported syntactic symbols.

Conceptually, a line of C code is always indented relative to the indentation of some line higher up in the buffer.  This is represented by the relative buffer position in the syntactic component.

Here is an example.  Suppose we had the following code as the only thing in a C++ buffer  (The line numbers in this and future examples don't actually appear in the buffer, of course!):

      1: void swap( int& a, int& b )
      2: {
      3:     int tmp = a;
      4:     a = b;
      5:     b = tmp;
      6: }

We can use the command C-c C-s (bound to c-show-syntactic-information) to simply report what the syntactic analysis is for the current line.  Running this command on line 4 of this example, we'd see in the echo area (With a universal argument (i.e., C-u C-c C-s) the analysis is inserted into the buffer as a comment on the current line.):

     ((statement 35))

This tells us that the line is a statement and it is indented relative to buffer position 35, which happens to be the i in int on line 3.  If you were to move point to line 3 and hit C-c C-s, you would see:

     ((defun-block-intro 29))

This indicates that the int line is the first statement in a top level function block, and is indented relative to buffer position 29, which is the brace just after the function header.

Here's another example:

      1: int add( int val, int incr, int doit )
      2: {
      3:     if( doit )
      4:         {
      5:             return( val + incr );
      6:         }
      7:     return( val );
      8: }

Hitting C-c C-s on line 4 gives us:

     ((substatement-open 46))

which tells us that this is a brace that opens a substatement block.  (A substatement is the line after a conditional statement, such as if, else, while, do, switch, etc.  A substatement block is a brace block following one of these conditional statements.)

Syntactic component lists can contain more than one component, and individual syntactic components need not have relative buffer positions. The most common example of this is a line that contains a comment only line.

      1: void draw_list( List<Drawables>& drawables )
      2: {
      3:         // call the virtual draw() method on each element in list
      4:     for( int i=0; i < drawables.count(), ++i )
      5:     {
      6:         drawables[i].draw();
      7:     }
      8: }

Hitting C-c C-s on line 3 of this example gives:

     ((comment-intro) (defun-block-intro 46))

and you can see that the syntactic component list contains two syntactic components.  Also notice that the first component, (comment-intro) has no relative buffer position.

Indentation Calculation
=======================

Indentation for a line is calculated using the syntactic component list derived in step 1 above (see Syntactic Analysis). Each component contributes to the final total indentation of the line in two ways.

First, the syntactic symbols are looked up in the c-offsets-alist style variable, which is an association list of syntactic symbols and the offsets to apply for those symbols.  These offsets are added to a running total.

Second, if the component has a relative buffer position, CC Mode adds the column number of that position to the running total.  By adding up the offsets and columns for every syntactic component on the list, the final total indentation for the current line is computed.

Let's use our two code examples above to see how this works.  Here is our first example again:

      1: void swap( int& a, int& b )
      2: {
      3:     int tmp = a;
      4:     a = b;
      5:     b = tmp;
      6: }

Let's say point is on line 3 and we hit the TAB key to reindent the line.  Remember that the syntactic component list for that line is:

     ((defun-block-intro 29))

CC Mode looks up defun-block-intro in the c-offsets-alist style variable.  Let's say it finds the value 4; it adds this to the running total (initialized to zero), yielding a running total indentation of 4 spaces.

Next CC Mode goes to buffer position 29 and asks for the current column.  This brace is in column zero, so CC Mode adds 0 to the running total.  Since there is only one syntactic component on the list for this line, indentation calculation is complete, and the total indentation for the line is 4 spaces.

Here's another example:

      1: int add( int val, int incr, int doit )
      2: {
      3:     if( doit )
      4:         {
      5:             return( val + incr );
      6:         }
      7:     return( val );
      8: }

If we were to hit TAB on line 4 in the above example, the same basic process is performed, despite the differences in the syntactic component list.  Remember that the list for this line is:

     ((substatement-open 46))

Here, CC Mode first looks up the substatement-open symbol in c-offsets-alist. Let's say it finds the value 4.  This yields a running total of 4.  CC Mode then goes to buffer position 46, which is the i in if on line 3.  This character is in the fourth column on that line so adding this to the running total yields an indentation for the line of 8 spaces.

Simple, huh?

Actually, the mode usually just does The Right Thing without you having to think about it in this much detail.  But when customizing indentation, it's helpful to understand the general indentation model being used.

As you configure CC Mode, you might want to set the variable c-echo-syntactic-information-p to non-nil so that the syntactic component list and calculated offset will always be echoed in the minibuffer when you hit TAB.

Minor Modes
***********

CC Mode contains two minor-mode-like features that you should find useful while entering new C code.  The first is called auto-newline mode, and the second is called hungry-delete mode.  These minor modes can be toggled on and off independently, and CC Mode can be configured so that it starts up with any combination of these minor modes.  By default, both of these minor modes are turned off.

The state of the minor modes is always reflected in the minor mode list on the modeline of the CC Mode buffer.  When auto-newline mode is enabled, you will see C/a on the mode line (The C
would be replaced with the name of the language in question for the
other languages CC Mode supports.).  When hungry delete mode is enabled you will see C/h and if both modes were enabled, you'd see C/ah.

CC Mode provides key bindings which allow you to toggle the minor modes on the fly while editing code.  To toggle just the auto-newline state, hit C-c C-a (bound to c-toggle-auto-state).  When you do this, you should see the a indicator either appear or disappear on the modeline.  Similarly, to toggle just the hungry-delete state, use C-c C-d (c-toggle-hungry-state), and to toggle both states, use C-c C-t (c-toggle-auto-hungry-state).

To set up the auto-newline and hungry-delete states to your preferred values, you would need to add some lisp to your .emacs file that called one of the c-toggle-*-state functions directly.  When called programmatically, each function takes a numeric value, where a positive number enables the minor mode, a negative number disables the mode, and zero toggles the current state of the mode.

So for example, if you wanted to enable both auto-newline and hungry-delete for all your C file editing, you could add the following to your .emacs file:

     (add-hook 'c-mode-common-hook
               (lambda () (c-toggle-auto-hungry-state 1)))

Auto-newline Insertion
======================

Auto-newline minor mode works by enabling certain electric characters.  Special characters such as the left and right braces, colons, semicolons, etc., have been made electric to perform some magic formatting in addition to inserting the typed character.  As a general rule, electric characters are only electric when the following conditions apply:

  * Auto-newline minor mode is enabled, as evidenced by a C/a or C/ah indicator on the modeline.

  * The character was not typed inside of a literal  (A literal is defined as any comment, string, or preprocessor macro definition.  These constructs are also known as syntactic whitespace since they are usually ignored when scanning C code.).

  * No numeric argument was supplied to the command (i.e., it was typed as normal, with no C-u prefix).

Hanging Braces
--------------

When you type either an open or close brace (i.e., { or }), the electric command c-electric-brace gets run.  This command has two electric formatting behaviors.  First, it will perform some reindentation of the line the brace was typed on, and second, it will add various newlines before and/or after the typed brace. Reindentation occurs automatically whenever the electric behavior is enabled.  If the brace ends up on a line other than the one it was typed on, then that line is also reindented.

The default in auto-newline mode is to insert newlines both before and after a brace, but that can be controlled by the c-hanging-braces-alist style variable.

 -- User Option: c-hanging-braces-alist

     This variable contains a mapping between syntactic symbols related to braces, and a list of places to insert a newline.  The syntactic symbols that are useful for this list are brace-list-intro, statement-cont, inexpr-class-open, inexpr-class-close, and all the *-open and *-close symbols.  See Syntactic Symbols, for a more detailed description of these syntactic symbols, except for inexpr-class-open and inexpr-class-close, which aren't actual syntactic symbols.

     The braces of anonymous inner classes in Java are given the special symbols inexpr-class-open and inexpr-class-close, so that they can be distinguished from the braces of normal classes (The braces of anonymous classes produce a combination of inexpr-class, and class-open or class-close in normal indentation analysis.).

     Note that the aggregate constructs in Pike mode, ({, }), ([, ]), and (<, >), do not count as brace lists in this regard, even though they do for normal indentation purposes.  It's currently not possible to set automatic newlines on these constructs.

     The value associated with each syntactic symbol in this association list is called an ACTION, which can be either a function or a list. See Custom Brace and Colon Hanging, for a more detailed discussion of using a function as a brace hanging ACTION.

     When the ACTION is a list, it can contain any combination of the symbols before and after, directing CC Mode where to put newlines in relationship to the brace being inserted.  Thus, if the list contains only the symbol after, then the brace is said to hang on the right side of the line, as in:

          // here, open braces always `hang'
          void spam( int i ) {
              if( i == 7 ) {
                  dosomething(i);
              }
          }

     When the list contains both after and before, the braces will appear on a line by themselves, as shown by the close braces in the above example.  The list can also be empty, in which case no newlines are added either before or after the brace.

     If a syntactic symbol is missing entirely from c-hanging-braces-alist, it's treated in the same way as an ACTION with a list containing before and after, so that braces by default end up on their own line.

     For example, the default value of c-hanging-braces-alist is:

          ((brace-list-open)
           (brace-entry-open)
           (statement-cont)
           (substatement-open after)
           (block-close . c-snug-do-while)
           (extern-lang-open after)
           (inexpr-class-open after)
           (inexpr-class-close before))

     which says that brace-list-open, brace-entry-open and statement-cont (Brace lists inside statements, such as initializers for static array variables inside functions in C, are recognized as statement-cont.  All normal substatement blocks are recognized with other symbols.) braces should both hang on the right side and allow subsequent text to follow on the same line as the brace.  Also, substatement-open, extern-lang-open, and inexpr-class-open braces should hang on the right side, but subsequent text should follow on the next line. The opposite holds for inexpr-class-close braces; they won't hang, but the following text continues on the same line.  Here, in the block-close entry, you also see an example of using a function as an ACTION.  In all other cases, braces are put on a line by themselves.

Hanging Colons
--------------

Using a mechanism similar to brace hanging (see Hanging Braces), colons can also be made to hang using the style variable c-hanging-colons-alist.

 -- User Option: c-hanging-colons-alist

     The syntactic symbols appropriate for this association list are: case-label, label, access-label, member-init-intro, and inher-intro.  Note however that for c-hanging-colons-alist, ACTIONs as functions are not supported. See also Custom Brace and Colon Hanging for details.

     In C++, double-colons are used as a scope operator but because these colons always appear right next to each other, newlines before and after them are controlled by a different mechanism, called clean-ups in CC Mode.  See Clean-ups, for details.

Hanging Semicolons and Commas
-----------------------------

Semicolons and commas are also electric in CC Mode, but since these characters do not correspond directly to syntactic symbols, a different mechanism is used to determine whether newlines should be automatically inserted after these characters.  See Customizing Semicolons and Commas, for details.

Other Electric Commands
-----------------------

A few other keys also provide electric behavior, often only to reindent the line.  Common to all of them is that they only reindent if used in normal code (as opposed to in a string literal or comment), and c-syntactic-indentation isn't nil.  They are:

#
     Pound (bound to c-electric-pound) is electric when typed as the first non-whitespace character on a line and not within a macro definition.  In this case, the variable c-electric-pound-behavior is consulted for the electric behavior.  This variable takes a list value, although the only element currently defined is alignleft, which tells this command to force the # character into column zero.  This is useful for entering preprocessor macro definitions.

     Pound is not electric in AWK buffers, where # starts a comment, and is bound to self-insert-command like any typical printable character.

*
/
     Stars and slashes (bound to c-electric-star and c-electric-slash respectively) are also electric under certain circumstances.  If a * is inserted as the second character of a C style block comment on a comment-only line, then the comment delimiter is indented as defined by c-offsets-alist.  A comment-only line is defined as a line which contains only a comment, as in:

          void spam( int i )
          {
              // this is a comment-only line...
              if( i == 7 )                // but this is not
              {
                  dosomething(i);
              }
          }

     Likewise, if a / is inserted as the second slash in a C++ style line comment (also only on a comment-only line), then the line is indented as defined by c-offsets-alist.

     In AWK mode, * and / do not delimit comments and are bound to self-insert-command.

<
>
     Less-than and greater-than signs (bound to c-electric-lt-gt) are electric, but only in C++ mode.  Hitting the second of two < or > keys reindents the line if it is a C++ style stream operator.

(
)
     The normal parenthesis characters ( and ) reindent the current line.  This is useful for getting the closing parenthesis of an argument list aligned automatically.

 -- Command: c-electric-continued-statement

     Certain keywords, depending on language, are electric to cause reindentation when they are preceded only by whitespace on the line. The keywords are those that continue an earlier statement instead of starting a new one: else, while, catch (only in C++ and Java) and finally (only in Java).

     An example:

          for (i = 0; i < 17; i++)
            if (a[i])
              res += a[i]->offset;
          else

     Here, the else should be indented like the preceding if, since it continues that statement. CC Mode will automatically reindent it after the else has been typed in full, since it's not until then it's possible to decide whether it's a new statement or a continuation of the preceding if.

     CC Mode uses Abbrev mode (see Abbrevs (The Emacs Editor)) to accomplish this. It's therefore turned on by default in all language modes except IDL mode, since CORBA IDL doesn't have any statements.

Clean-ups
---------

Clean-ups are mechanisms complementary to colon and brace hanging. On the surface, it would seem that clean-ups overlap the functionality provided by the c-hanging-*-alist variables.  Clean-ups are however used to adjust code ``after-the-fact,'' i.e., to adjust the whitespace in constructs after they are typed.

Most of the clean-ups are only applicable to counteract automatically inserted newlines, and will therefore only have any effect if the auto-newline minor mode is turned on.  Others will work all the time.

 -- User Option: c-cleanup-list

     You can configure CC Mode's clean-ups by setting the style variable c-cleanup-list, which is a list of clean-up symbols.  By default, CC Mode cleans up only the scope-operator construct, which is necessary for proper C++ support.  Note that clean-ups are only performed when the construct does not occur within a literal (see Auto-newline Insertion), and when there is nothing but whitespace appearing between the individual components of the construct.

These are the clean-ups that are only active in the auto-newline minor mode:

brace-else-brace
     Clean up } else { constructs by placing the entire construct on a single line.  Clean-up occurs when the open brace after the else is typed.  So for example, this:

          void spam(int i)
          {
              if( i==7 ) {
                  dosomething();
              }
              else
              {

     appears like this after the last open brace is typed:

          void spam(int i)
          {
              if( i==7 ) {
                  dosomething();
              } else {

brace-elseif-brace
     Similar to the brace-else-brace clean-up, but this cleans up } else if (...) { constructs.  For example:

          void spam(int i)
          {
              if( i==7 ) {
                  dosomething();
              }
              else if( i==3 )
              {

     appears like this after the last open parenthesis is typed:

          void spam(int i)
          {
              if( i==7 ) {
                  dosomething();
              } else if( i==3 )
              {

     and like this after the last open brace is typed:

          void spam(int i)
          {
              if( i==7 ) {
                  dosomething();
              } else if( i==3 ) {

brace-catch-brace
     Analogous to brace-elseif-brace, but cleans up } catch (...) { in C++ and Java mode.

empty-defun-braces
     Clean up braces following a top-level function or class definition that contains no body.  Clean up occurs when the closing brace is typed. Thus the following:

          class Spam
          {
          }

     is transformed into this when the close brace is typed:

          class Spam
          {}

defun-close-semi
     Clean up the terminating semicolon on top-level function or class definitions when they follow a close brace.  Clean up occurs when the semicolon is typed.  So for example, the following:

          class Spam
          {
          }
          ;

     is transformed into this when the semicolon is typed:

          class Spam
          {
          };

list-close-comma
     Clean up commas following braces in array and aggregate initializers. Clean up occurs when the comma is typed.

scope-operator
     Clean up double colons which may designate a C++ scope operator split across multiple lines (Certain C++ constructs introduce ambiguous situations, so scope-operator clean-ups may not always be correct.  This usually only occurs when scoped identifiers appear in switch label tags.).  Clean up occurs when the second colon is typed. You will always want scope-operator in the c-cleanup-list when you are editing C++ code.

The following clean-ups are always active when they occur on c-cleanup-list, and are thus not affected by the auto-newline minor mode:

space-before-funcall
     Insert a space between the function name and the opening parenthesis of a function call.  This produces function calls in the style mandated by the GNU coding standards, e.g., signal (SIGINT, SIG_IGN) and abort ().  Clean up occurs when the opening parenthesis is typed.

compact-empty-funcall
     Clean up any space between the function name and the opening parenthesis of a function call that has no arguments.  This is typically used together with space-before-funcall if you prefer the GNU function call style for functions with arguments but think it looks ugly when it's only an empty parenthesis pair.  I.e., you will get signal (SIGINT, SIG_IGN), but abort().  Clean up occurs when the closing parenthesis is typed.

Hungry-deletion of Whitespace
=============================

Hungry deletion of whitespace, or as it more commonly called, hungry-delete mode, is a simple feature that some people find extremely useful.  In fact, you might find yourself wanting hungry-delete in all your editing modes!

In a nutshell, when hungry-delete mode is enabled, hitting the DEL or C-d keys will consume all preceding or following whitespace, including newlines and tabs.  This can really cut down on the number of times you have to hit these keys if, for example, you made a mistake on the preceding line.

 -- Command: c-electric-backspace
     This command is run by default when you hit the DEL key.  It deletes any amount of whitespace in the backwards direction if hungry-delete mode is enabled.  When it's disabled, or when used with a prefix argument or in a literal (see Auto-newline Insertion), the function contained in the c-backspace-function variable is called with the prefix argument.

 -- Variable: c-backspace-function
     Hook that gets called by c-electric-backspace when it doesn't do an ``electric'' deletion of the preceding whitespace.  The default value is backward-delete-char-untabify.

 -- Command: c-electric-delete-forward
     This function, which is bound to C-d by default, works just like c-electric-backspace but in the forward direction.  When it doesn't do an ``electric'' deletion of the following whitespace, it calls the function in c-delete-function with its prefix argument.

 -- Variable: c-delete-function
     Hook that gets called by c-electric-delete-forward when it doesn't do an ``electric'' deletion of the following whitespace.  The default value is delete-char.

Above we have only talked about the DEL and C-d key events, without connecting them to the physical keys commonly known as Backspace and Delete.  The default behavior of those two depends on the flavor of (X)Emacs you are using.

In XEmacs 20.3 and beyond, the Backspace key is bound to c-electric-backspace and the Delete key is bound to c-electric-delete.  You control the direction it deletes in by setting the variable delete-key-deletes-forward, a standard XEmacs variable.  When this variable is non-nil, c-electric-delete will do forward deletion with c-electric-delete-forward, otherwise it does backward deletion with c-electric-backspace.

In other Emacs versions, CC Mode doesn't bind either Backspace or Delete.  In XEmacs 19 and Emacs prior to 21 that means that it's up to you to fix them.  Emacs 21 automatically binds them as appropriate to DEL and C-d.

Another way to use hungry deletion is to bind c-hungry-backspace and c-hungry-delete-forward directly to keys, and not use the mode toggling.  For example C-c C-d and C-c DEL to match plain C-d and DEL,

     (add-hook
      'c-mode-common-hook
      (lambda ()
        (define-key c-mode-base-map
                    [?\C-c ?\d] 'c-hungry-backspace)
        (define-key c-mode-base-map
                    [?\C-c ?\C-d] 'c-hungry-delete-forward)))

 -- Command: c-hungry-backspace
     Delete any amount of whitespace in the backwards direction (regardless whether hungry-delete mode is enabled or not).

 -- Command: c-hungry-delete-forward
     Delete any amount of whitespace in the forward direction (regardless whether hungry-delete mode is enabled or not).

Text Filling and Line Breaking
******************************

Since there's a lot of normal text in comments and string literals, CC Mode provides features to edit these like in text mode.  The goal is to do it as seamlessly as possible, i.e., you can use auto fill mode, sentence and paragraph movement, paragraph filling, adaptive filling etc wherever there's a piece of normal text without having to think much about it.  CC Mode should keep the indentation, fix the comment line decorations, and so on, for you.  It does that by hooking in on the different line breaking functions and tuning relevant variables as necessary.

To make Emacs recognize comments and treat text in them as normal paragraphs, CC Mode makes several standard variables (comment-start, comment-end, comment-start-skip, paragraph-start, paragraph-separate, paragraph-ignore-fill-prefix, adaptive-fill-mode, adaptive-fill-regexp, and adaptive-fill-first-line-regexp.) buffer local and modifies them according to the language syntax and the comment line prefix.

 -- User Option: c-comment-prefix-regexp
     This style variable contains the regexp used to recognize the comment line prefix, which is the line decoration that starts every line in a comment.  The default is //+\\|\\**, which matches C++ style line comments like

          // blah blah

     with two or more slashes in front of them, and C style block comments like

          /*
           * blah blah
           */

     with zero or more stars at the beginning of every line.  If you change this variable, please make sure it still matches the comment starter (i.e., //) of line comments and the line prefix inside block comments.

     Also note that since CC Mode uses the value of c-comment-prefix-regexp to set up several other variables at mode initialization, there won't be any effect if you just change it inside a CC Mode buffer.  You need to call the command c-setup-paragraph-variables too, to update those other variables with the new value.  That's also the case if you modify this variable in a mode hook, since CC Mode sets up all variables before calling them.

Line breaks are by default handled (almost) the same regardless whether they are made by auto fill mode (see Auto Fill (The Emacs Editor)), paragraph filling (e.g., with M-q), or explicitly with M-j or similar methods.  In string literals, the new line gets the same indentation as the previous nonempty line (may be changed with the string syntactic symbol).  In comments, CC Mode uses c-comment-prefix-regexp to adapt the line prefix from the other lines in the comment.

CC Mode uses adaptive fill mode (see Adaptive Fill (The Emacs Editor)) to make Emacs correctly keep the line prefix when filling paragraphs.  That also makes Emacs preserve the text indentation inside the comment line prefix.  e.g., in the following comment, both paragraphs will be filled with the left margins of the texts kept intact:

     /* Make a balanced b-tree of the nodes in the incoming
      * stream.  But, to quote the famous words of Donald E.
      * Knuth,
      *
      *     Beware of bugs in the above code; I have only
      *     proved it correct, not tried it.
      */

It's also possible to use other adaptive filling packages, notably Kyle E. Jones' Filladapt package (It's available from http://www.wonderworks.com/.  As of version 2.12, it does however lack a feature that makes it work suboptimally when c-comment-prefix-regexp matches the empty string (which it does by default).  A patch for that is available from the CC Mode web site.), which handles things like bulleted lists nicely.  There's a convenience function c-setup-filladapt that tunes the relevant variables in Filladapt for use in CC Mode.  Call it from a mode hook, e.g., with something like this in your .emacs:

     (defun my-c-mode-common-hook ()
       (c-setup-filladapt)
       (filladapt-mode 1))
     (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

 -- User Option: c-block-comment-prefix
     Normally the comment line prefix inserted for a new line inside a comment is deduced from other lines in it.  However there's one situation when there's no hint about what the prefix should look like, namely when a block comment is broken for the first time.  This style variable (In versions before 5.26, this variable was called
     c-comment-continuation-stars.  As a compatibility measure,
     CC Mode still uses the value on that variable if it's set.) is used then as the comment prefix.  It defaults to * (Actually, this default setting of c-block-comment-prefix typically gets overriden by the default style gnu, which sets it to blank.  You can see the line splitting effect described here by setting a different style, e.g. k&r see Choosing a Style.), which makes a comment

          /* Got O(n^2) here, which is a Bad Thing. */

     break into

          /* Got O(n^2) here,
           * which is a Bad Thing. */

     Note that it won't work to adjust the indentation by putting leading spaces in c-block-comment-prefix, since CC Mode still uses the normal indentation engine to indent the line.  Thus, the right way to fix the indentation is by customizing the c syntactic symbol.  It defaults to c-lineup-C-comments, which handles the indentation of most common comment styles, see Indentation Functions.

 -- User Option: c-ignore-auto-fill
     When auto fill mode is enabled, CC Mode can selectively ignore it depending on the context the line break would occur in, e.g., to never break a line automatically inside a string literal.  This variable takes a list of symbols for the different contexts where auto-filling never should occur:

     string
          Inside a string or character literal.

     c
          Inside a C style block comment.

     c++
          Inside a C++ style line comment.

     cpp
          Inside a preprocessor directive.

     code
          Anywhere else, i.e., in normal code.

     By default, c-ignore-auto-fill is set to '(string cpp code), which means that auto-filling only occurs in comments when auto-fill mode is activated.  In literals, it's often desirable to have explicit control over newlines.  In preprocessor directives, the necessary \ escape character before the newline is not automatically inserted, so an automatic line break would produce invalid code.  In normal code, line breaks are normally dictated by some logical structure in the code rather than the last whitespace character, so automatic line breaks there will produce poor results in the current implementation.

The commands that do the actual work follow.

M-q (c-fill-paragraph)
     This is the replacement for fill-paragraph in CC Mode buffers. It's used to fill multiline string literals and both block and line style comments.  In Java buffers, the Javadoc markup words are recognized as paragraph starters.  The line oriented Pike autodoc markup words are recognized in the same way in Pike mode.

     The function keeps the comment starters and enders of block comments as they were before the filling.  This means that a comment ender on the same line as the paragraph being filled will be filled with the paragraph, and one on a line by itself will stay as it is.  The comment starter is handled similarly (This means that the variables
     c-hanging-comment-starter-p and c-hanging-comment-ender-p,
     which controlled this behavior in earlier versions of CC Mode, are now
     obsolete.).

M-j (c-indent-new-comment-line)
     This is the replacement for indent-new-comment-line.  It breaks the line at point and indents the new line like the current one.

     If inside a comment and comment-multi-line is non-nil, the indentation and line prefix are preserved.  If inside a comment and comment-multi-line is nil, a new comment of the same type is started on the next line and indented as appropriate for comments.

     Note that CC Mode sets comment-multi-line to t at startup.  The reason is that M-j could otherwise produce sequences of single line block comments for texts that should logically be treated as one comment, and the rest of the paragraph handling code (e.g., M-q and M-a) can't cope with that, which would lead to inconsistent behavior.

M-x c-context-line-break
     This is a function that works like indent-new-comment-line in comments and newline-and-indent elsewhere, thus combining those two in a way that uses each one in the context it's best suited for. I.e., in comments the comment line prefix and indentation is kept for the new line, and in normal code it's indented according to context by the indentation engine.

     In macros it acts like newline-and-indent but additionally inserts and optionally aligns the line ending backslash so that the macro remains unbroken.  See Macro Handling, for details about the backslash alignment.

     It's not bound to a key by default, but it's intended to be used on the RET key.  If you like the behavior of newline-and-indent on RET, you should consider switching to this function.

M-x c-context-open-line
     This is to C-o (M-x open-line) as c-context-line-break is to RET.  I.e., it works just like c-context-line-break but leaves the point before the inserted line break.

Macro Handling
**************

Preprocessor directives are handled as syntactic whitespace from other code, i.e., they can be interspersed anywhere without affecting the syntactic analysis, just like comments.

The code inside macro definitions is still analyzed syntactically so that you get relative indentation there just as you'd get if the same code was outside a macro.  However, since there is no hint about the syntactic context, i.e., whether the macro expands to an expression, to some statements, or perhaps to whole functions, the syntactic recognition can be wrong.  CC Mode manages to figure it out correctly most of the time, though.  See Syntactic Symbols, for details about the indentation.

 -- User Option: c-syntactic-indentation-in-macros
     Enable syntactic analysis inside macros, which is the default.  If this is nil, all lines inside macro definitions are analyzed as cpp-macro-cont.

CC Mode provides some tools to help keep the line continuation backslashes in macros neat and tidy:

C-c C-\ (c-backslash-region)
     This function inserts and aligns or deletes the end-of-line backslashes in the current region.

     With no prefix argument, it inserts any missing backslashes and aligns them according to the c-backslash-column and c-backslash-max-column variables.  With a prefix argument, it deletes any backslashes.

     The function does not modify blank lines at the start of the region.  If the region ends at the start of a line, it always deletes the backslash (if any) at the end of the previous line.

 -- User Option: c-backslash-column
 -- User Option: c-backslash-max-column
     These variables control the alignment columns for line continuation backslashes in multiline macros.  They are used by the functions that automatically insert or align such backslashes, e.g., c-backslash-region and c-context-line-break.

     c-backslash-column specifies the minimum column for the backslashes.  If any line in the macro exceeds it then the next tab stop from that line is used as the alignment column for all the backslashes, so that they remain in a single column.  However, if some lines exceed c-backslash-max-column then the backslashes in the rest of the macro will be kept at that column, so that the lines which are too long ``stick out'' instead.

 -- User Option: c-auto-align-backslashes
     Align automatically inserted line continuation backslashes if non-nil.  When line continuation backslashes are inserted automatically for line breaks in multiline macros, e.g., by c-context-line-break, they are aligned with the other backslashes in the same macro if this flag is set.  Otherwise the inserted backslashes are preceded by a single space.

The recommended line breaking function, c-context-line-break (see Text Filling and Line Breaking), is especially nice if you edit multiline macros frequently.  When used inside a macro, it automatically inserts and adjusts the mandatory backslash at the end of the line to keep the macro together, and it leaves the point at the right indentation column for the code.  Thus you can write code inside macros almost exactly as you can elsewhere, without having to bother with the trailing backslashes.

Font Locking
************

Please note: The font locking in AWK mode is currently not integrated with the rest of CC Mode, so this section does not apply there. See AWK Mode Font Locking, instead.

CC Mode provides font locking for its supported languages by supplying patterns for use with Font Lock mode.  This means that you get distinct faces on the various syntactic parts such as comments, strings, keywords and types, which is very helpful in telling them apart at a glance and discovering syntactic errors.  See Font Lock (The Emacs Editor), for ways to enable font locking in CC Mode buffers.

Font Locking Preliminaries
==========================

The font locking for most of the CC Mode languages were provided directly by the Font Lock package prior to version 5.30 of CC Mode. In the transition to CC Mode the patterns have been reworked completely and are applied uniformly across all the languages except AWK mode, just like the indentation rules (although each language still has some pecularities of its own, of course).  Since the languages previously had completely separate font locking patterns, this means that it's a bit different in most languages now.

The main goal for the font locking in CC Mode is accuracy, to provide a dependable aid in recognizing the various constructs.  Some, like strings and comments, are easy to recognize while others like declarations and types can be very tricky.  CC Mode can go to great lengths to recognize declarations and casts correctly, especially when the types aren't recognized by standard patterns.  This is a fairly demanding analysis which can be slow on older hardware, and it can therefore be disabled by choosing a lower decoration level with the variable font-lock-maximum-decoration.

The decoration levels are used as follows:

 1. Minimal font locking: Fontify only comments, strings and preprocessor directives (in the languages that use cpp).

 2. Fast normal font locking: In addition to level 1, fontify keywords, simple types and declarations that are easy to recognize.  The variables *-font-lock-extra-types (where * is the name of the language) are used to recognize types (see below).  Documentation comments like Javadoc are fontified according to c-doc-comment-style (see Documentation Comments).

     Use this if you think the font locking is too slow.  It's the closest corresponding level to level 3 in the old font lock patterns.

 3. Accurate normal font locking: Like level 2 but uses a different approach that can recognize types and declarations much more accurately.  The *-font-lock-extra-types variables are still used, but user defined types are recognized correctly anyway in most cases.  Therefore those variables should be fairly restrictive and not contain patterns that are uncertain.

     This level is designed for fairly modern hardware and a font lock support mode like Lazy Lock or Just-in-time Lock mode that only fontifies the parts that are actually shown.

Since user defined types are hard to recognize you can provide additional regexps to match those you use:

 -- User Option: c-font-lock-extra-types
 -- User Option: c++-font-lock-extra-types
 -- User Option: objc-font-lock-extra-types
 -- User Option: java-font-lock-extra-types
 -- User Option: idl-font-lock-extra-types
 -- User Option: pike-font-lock-extra-types
     For each language there's a variable *-font-lock-extra-types, where * stands for the language in question.  It contains a list of regexps that matches identifiers that should be recognized as types, e.g., \\sw+_t to recognize all identifiers ending with _t as is customary in C code.  Each regexp should not match more than a single identifier.

     The default values contain regexps for many types in standard runtime libraries that are otherwise difficult to recognize, and patterns for standard type naming conventions like the _t suffix in C and C++. Java, Objective-C and Pike have as a convention to start class names with capitals, so there are patterns for that in those languages.

     Despite the names of these variables, they are not only used for fontification but in other places as well where CC Mode needs to recognize types.

Faces
=====

CC Mode attempts to use the standard faces for programming languages in accordance with their intended purposes as far as possible.  No extra faces are currently provided, with the exception of a replacement face c-invalid-face for emacsen that don't provide font-lock-warning-face.

  * Normal comments are fontified in font-lock-comment-face.

  * Comments that are recognized as documentation (see Documentation Comments) get font-lock-doc-face (Emacs) or font-lock-doc-string-face (XEmacs) if those faces exist.  If they don't then font-lock-comment-face is used.

  * String and character literals are fontified in font-lock-string-face.

  * Keywords are fontified with font-lock-keyword-face.

  * font-lock-function-name-face is used for function names in declarations and definitions, and classes in those contexts.  It's also used for preprocessor defines with arguments.

  * Variables in declarations and definitions, and other identifiers in such variable contexts, get font-lock-variable-name-face.  It's also used for preprocessor defines without arguments.

  * Builtin constants are fontified in font-lock-constant-face if it exists, font-lock-reference-face otherwise.  As opposed to the preceding two faces, this is used on the names in expressions, and it's not used in declarations, even if there happen to be a const in them somewhere.

  * font-lock-type-face is put on types (both predefined and user defined) and classes in type contexts.

  * Label identifiers get font-lock-constant-face if it exists, font-lock-reference-face otherwise.

  * Name qualifiers and identifiers for scope constructs are fontified like labels.

  * Special markup inside documentation comments are also fontified like labels.

  * Preprocessor directives get font-lock-preprocessor-face if it exists (i.e., XEmacs).  In Emacs they get font-lock-builtin-face or font-lock-reference-face, for lack of a closer equivalent.

  * Some kinds of syntactic errors are fontified with font-lock-warning-face in Emacs.  In older XEmacs versions there's no corresponding standard face, so there a special c-invalid-face is used, which is defined to stand out sharply by default.

     Note that it's not used for #error or #warning directives, since those aren't syntactic errors in themselves.

Documentation Comments
======================

There are various tools to supply documentation in the source as specially structured comments, e.g., the standard Javadoc tool in Java. CC Mode provides an extensible mechanism to fontify such comments and the special markup inside them.

 -- User Option: c-doc-comment-style
     This is a style variable that specifies which documentation comment style to recognize, e.g., javadoc for Javadoc comments.

     The value may also be a list of styles, in which case all of them are recognized simultaneously (presumably with markup cues that don't conflict).

     The value may also be an association list to specify different comment styles for different languages.  The symbol for the major mode is then looked up in the alist, and the value of that element is interpreted as above if found.  If it isn't found then the symbol `other' is looked up and its value is used instead.

     Note that CC Mode uses this variable to set other variables that handle fontification etc.  That's done at mode initialization or when you switch to a style which sets this variable.  Thus, if you change it in some other way, e.g., interactively in a CC Mode buffer, you will need to do M-x java-mode (or whatever mode you're currently using) to reinitialize.

     Note also that when CC Mode starts up, the other variables are modified before the mode hooks are run.  If you change this variable in a mode hook, you have to call c-setup-doc-comment-style afterwards to redo that work.

CC Mode currently provides handing of the following doc comment styles:

javadoc
     Javadoc comments, the standard tool in Java.

autodoc
     For Pike autodoc markup, the standard in Pike.

The above is by no means complete.  If you'd like to see support for other doc comment styles, please let us know (see Mailing Lists and Submitting Bug Reports).

You can also write your own doc comment fontification support to use with c-doc-comment-style: Supply a variable or function *-font-lock-keywords where * is the name you want to use in c-doc-comment-style.  If it's a variable, it's prepended to font-lock-keywords.  If it's a function, it's called at mode initialization and the result is prepended.  For an example, see javadoc-font-lock-keywords in cc-fonts.el.

If you add support for another doc comment style, please consider contributing it --- send a note to bug-cc-mode@gnu.org.

Commands
********

See also Text Filling and Line Breaking and Macro Handling, for commands concerning those bits.

Indentation Commands
====================

The following list of commands reindent C constructs.  Note that when you change your coding style, either interactively or through some other means, your file does not automatically get reindented.  You will need to execute one of the following commands to see the effects of your changes.

Also, variables like c-hanging-* and c-cleanup-list only affect how on-the-fly code is formatted.  Changing the ``hanginess'' of a brace and then reindenting, will not move the brace to a different line.  For this, you're better off getting an external program like GNU indent, which will rearrange brace location, among other things.

Reindenting large sections of code can take a long time.  When CC Mode reindents a region of code, it is essentially equivalent to hitting TAB on every line of the region.

These commands are useful when indenting code:

TAB (c-indent-command)
     Indents the current line.  The actual behavior is controlled by several variables, described below.  See c-tab-always-indent, c-insert-tab-function, and indent-tabs-mode.  With a numeric argument, this command rigidly indents the region, preserving the relative indentation among the lines.

C-M-q (c-indent-exp)
     Indent an entire balanced brace or parenthesis expression.  Note that point must be on the opening brace or parenthesis of the expression you want to indent.

C-c C-q (c-indent-defun)
     Indents the entire top-level function, class or macro definition encompassing point.  It leaves point unchanged.  This function can't be used to reindent a nested brace construct, such as a nested class or function, or a Java method.  The top-level construct being reindented must be complete, i.e., it must have both a beginning brace and an ending brace.

C-M-\ (indent-region)
     Indents an arbitrary region of code.  This is a standard Emacs command, tailored for C code in a CC Mode buffer.  Note, of course, that point and mark must delineate the region you want to indent.

M-; (indent-for-comment)
     Insert a comment at the end of the current line, if none is there already. Then reindent the comment according to the variables c-indent-comment-alist, c-indent-comments-syntactically-p and comment-column.  Then position the point after the comment starter.  This is a standard Emacs command, but CC Mode enhances it a bit with two variables:

      -- User Option: c-indent-comment-alist
          This style variable allows you to control which column M-; indents the comment to, depending on the preceding code and the indentation of a similar comment on the preceding line, if there is any.  It is an association list that maps different types of lines to actions describing how they should be handled.  If a certain line type isn't present on the list then the line is indented to the column specified by comment-column.  See the documentation string for c-indent-comment-alist for a full description of the available line types and actions (use C-h v c-indent-comment-alist).

      -- User Option: c-indent-comments-syntactically-p
          Normally, when this variable is nil, M-; will indent comment-only lines according to c-indent-comment-alist, just as it does with lines where other code precede the comments.  However, if you want it to act just like TAB for comment-only lines you can get that by setting c-indent-comments-syntactically-p to non-nil.

          If c-indent-comments-syntactically-p is non-nil then c-indent-comment-alist won't be consulted at all for comment-only lines.

C-M-h (c-mark-function)
     While not strictly an indentation command, this is useful for marking the current top-level function or class definition as the current region.  As with c-indent-defun, this command operates on top-level constructs, and can't be used to mark say, a Java method.

These variables are also useful when indenting code:

 -- User Option: c-tab-always-indent
     This variable controls how TAB (c-indent-command) operates.  When it is t, TAB always indents the current line.  When it is nil, the line is indented only if point is at the left margin, or on or before the first non-whitespace character on the line, otherwise some whitespace is inserted.  If this variable is some other value (not nil or t), then some whitespace is inserted only within strings and comments (literals), but the line is always reindented.

 -- User Option: c-insert-tab-function
     When ``some whitespace'' is inserted as described above, what actually happens is that the function stored in c-insert-tab-function is called.  Normally, this just inserts a real tab character, or the equivalent number of spaces, depending on indent-tabs-mode. Some people, however, set c-insert-tab-function to tab-to-tab-stop so as to get hard tab stops when indenting.

 -- User Option: indent-tabs-mode
     This is a standard Emacs variable that controls how line indentation is composed.  When it's non-nil, tabs can be used in a line's indentation, otherwise only spaces can be used.

 -- User Option: c-progress-interval
     When indenting large regions of code, this variable controls how often a progress message is displayed.  Set this variable to nil to inhibit the progress messages, or set it to an integer which is how often (in seconds) progress messages are to be displayed.

Movement Commands
=================

CC Mode contains some useful commands for moving around in C code.

M-x c-beginning-of-defun
     Move point back to the least-enclosing brace.  This function is analogous to the Emacs built-in command beginning-of-defun, except it eliminates the constraint that the top-level opening brace must be in column zero.  See beginning-of-defun for more information.

     Depending on the coding style being used, you might prefer c-beginning-of-defun to beginning-of-defun.  If so, consider binding C-M-a to the former instead.  For backwards compatibility reasons, the default binding remains in effect.

     In AWK mode, a defun doesn't necessarily have braces at all.  AWK Mode therefore has its own version of this function which is bound by default to C-M-a.  You can thus chose freely which function to bind to C-M-a for the other modes without worrying about AWK buffers.  See AWK Mode Defuns.

M-x c-end-of-defun
     Moves point to the end of the current top-level definition.  This function is analogous to the Emacs built-in command end-of-defun, except it eliminates the constraint that the top-level opening brace of the defun must be in column zero.  See end-of-defun for more information.

     Depending on the coding style being used, you might prefer c-end-of-defun to end-of-defun.  If so, consider binding C-M-e to the former instead.  For backwards compatibility reasons, the default binding remains in effect.

     In AWK Mode, a defun doesn't necessarily have braces at all.  AWK Mode therefore has its own version of this function which is bound by default to C-M-e.  You can thus chose freely which function to bind to C-M-e for the other modes without worrying about AWK buffers.  AWK Mode Defuns.

C-c C-u (c-up-conditional)
     Move point back to the containing preprocessor conditional, leaving the mark behind.  A prefix argument acts as a repeat count.  With a negative argument, move point forward to the end of the containing preprocessor conditional.

     #elif is treated like #else followed by #if, so the function stops at them when going backward, but not when going forward.

M-x c-up-conditional-with-else
     A variety of c-up-conditional that also stops at #else lines.  Normally those lines are ignored.

M-x c-down-conditional
     Move point forward into the next nested preprocessor conditional, leaving the mark behind.  A prefix argument acts as a repeat count. With a negative argument, move point backward into the previous nested preprocessor conditional.

     #elif is treated like #else followed by #if, so the function stops at them when going forward, but not when going backward.

M-x c-down-conditional-with-else
     A variety of c-down-conditional that also stops at #else lines.  Normally those lines are ignored.

C-c C-p (c-backward-conditional)
     Move point back over a preprocessor conditional, leaving the mark behind.  A prefix argument acts as a repeat count.  With a negative argument, move forward.

C-c C-n (c-forward-conditional)
     Move point forward across a preprocessor conditional, leaving the mark behind.  A prefix argument acts as a repeat count.  With a negative argument, move backward.

M-a (c-beginning-of-statement)
     Move point to the beginning of the innermost C statement.  If point is already at the beginning of a statement, move to the beginning of the closest preceding statement, even if that means moving into a block (you can use C-M-b to move over a balanced block).  With prefix argument N, move back N - 1 statements.

     If point is within or next to a comment or a string which spans more than one line, this command moves by sentences instead of statements.

     When called from a program, this function takes three optional arguments: the repetition count, a buffer position limit which is the farthest back to search for the syntactic context, and a flag saying whether to do sentence motion in or near comments and multiline strings.

M-e (c-end-of-statement)
     Move point to the end of the innermost C statement.  If point is at the end of a statement, move to the end of the next statement, even if it's inside a nested block (use C-M-f to move to the other side of the block).  With prefix argument N, move forward N - 1 statements.

     If point is within or next to a comment or a string which spans more than one line, this command moves by sentences instead of statements.

     When called from a program, this function takes three optional arguments: the repetition count, a buffer position limit which is the farthest back to search for the syntactic context, and a flag saying whether to do sentence motion in or near comments and multiline strings.

M-x c-forward-into-nomenclature
     A popular programming style, especially for object-oriented languages such as C++ is to write symbols in a mixed case format, where the first letter of each word is capitalized, and not separated by underscores. e.g., SymbolsWithMixedCaseAndNoUnderlines.

     This command moves point forward to next capitalized word.  With prefix argument N, move N times.

M-x c-backward-into-nomenclature
     Move point backward to beginning of the next capitalized word.  With prefix argument N, move N times.  If N is negative, move forward.

Other Commands
==============

Here are the various other commands that didn't fit anywhere else:

C-c : (c-scope-operator)
     In C++, it is also sometimes desirable to insert the double-colon scope operator without performing the electric behavior of colon insertion. C-c : does just this.

Customizing Indentation
***********************

The context sensitive indentation is mainly controlled by the variable c-offsets-alist:

 -- User Option: c-offsets-alist
     This special style variable contains the mappings between syntactic symbols and the offsets to apply for those symbols.  It's set at mode initialization from a style you may specify.  Styles are groupings of syntactic symbol offsets and other style variable values. Most likely, you'll find that one of the predefined styles will suit your needs.  See Styles, for an explanation of how to set up named styles.

     Only syntactic symbols not already bound on c-offsets-alist will be set from styles.  This means that any association you set on it, be it before or after mode initialization, will not be changed.  The c-offsets-alist variable may therefore be used from e.g., the Customization interface (Available in Emacs 20 and later, and XEmacs 19.15 and later.) to easily change indentation offsets without having to bother about styles.  Initially c-offsets-alist is empty, so that all syntactic symbols are set by the style system.

     The offset associated with any particular syntactic symbol can be an integer, a function or lambda expression, a variable name, a vector, a list, or one of the following special symbols: +, -, ++, --, *, or /.  The meaning of these values are described in detail below.

The special symbols describe an offset in multiples of the value of c-basic-offset:

 -- User Option: c-basic-offset
     Style variable that holds the basic offset between indentation levels.

By defining a style's indentation in terms of c-basic-offset, you can change the amount of whitespace given to an indentation level while maintaining the same basic shape of your code.  Here are the values that the special symbols correspond to:

+
     c-basic-offset times 1

-
     c-basic-offset times -1

++
     c-basic-offset times 2

--
     c-basic-offset times -2

*
     c-basic-offset times 0.5

/
     c-basic-offset times -0.5

When a function is used as offset, it's called an indentation function.  Such functions are useful when more context than just the syntactic symbol is needed to get the desired indentation. See Indentation Functions, and Custom Indentation Functions, for details about them.

If the offset is a vector, its first element sets the absolute indentation column, which will override any previous relative indentation.  It won't override additional relative indentation for nested constructs, though.

The offset can also be a list, in which case it is evaluated recursively using the semantics described above.  The first element of the list that returns a non-nil value succeeds and the evaluation stops.  If none of the list elements return a non-nil value, then an offset of 0 (zero) is used (There is however a variable c-strict-syntax-p that, when set to non-nil, will cause an error to be signaled in that case.  It's now considered obsolete since it doesn't work well with some of the alignment functions that now returns nil instead of zero to be more usable in lists.  You should therefore leave c-strict-syntax-p set to nil.).

So, for example, because most of the default offsets are defined in terms of +, -, and 0, if you like the general indentation style, but you use 4 spaces instead of 2 spaces per level, you can probably achieve your style just by changing c-basic-offset like so (You can try this interactively in a C buffer by typing the text that appears in italics.):

     M-x set-variable RET
     Set variable: c-basic-offset RET
     Set c-basic-offset to value: 4 RET

This would change

     int add( int val, int incr, int doit )
     {
       if( doit )
         {
           return( val + incr );
         }
       return( val );
     }

to

     int add( int val, int incr, int doit )
     {
         if( doit )
             {
                 return( val + incr );
             }
         return( val );
     }

To change indentation styles more radically, you will want to change the offsets associated with other syntactic symbols.  First, I'll show you how to do that interactively, then I'll describe how to make changes to your .emacs file so that your changes are more permanent.

Interactive Customization
=========================

As an example of how to customize indentation, let's change the style of this example (In this and subsequent examples, the original code is formatted using the gnu style unless otherwise indicated.  See Styles.):

      1: int add( int val, int incr, int doit )
      2: {
      3:   if( doit )
      4:     {
      5:       return( val + incr );
      6:     }
      7:   return( val );
      8: }

to:

      1: int add( int val, int incr, int doit )
      2: {
      3:   if( doit )
      4:   {
      5:     return( val + incr );
      6:   }
      7:   return( val );
      8: }

In other words, we want to change the indentation of braces that open a block following a condition so that the braces line up under the conditional, instead of being indented.  Notice that the construct we want to change starts on line 4.  To change the indentation of a line, we need to see which syntactic components affect the offset calculations for that line.  Hitting C-c C-s on line 4 yields:

     ((substatement-open 44))

so we know that to change the offset of the open brace, we need to change the indentation for the substatement-open syntactic symbol.

To do this interactively, just hit C-c C-o.  This prompts you for the syntactic symbol to change, providing a reasonable default. In this case, the default is substatement-open, which is just the syntactic symbol we want to change!

After you hit return, CC Mode will then prompt you for the new offset value, with the old value as the default.  The default in this case is +, but we want no extra indentation so enter 0 and RET.  This will associate the offset 0 with the syntactic symbol substatement-open.

To check your changes quickly, just hit C-c C-q (c-indent-defun) to reindent the entire function.  The example should now look like:

      1: int add( int val, int incr, int doit )
      2: {
      3:   if( doit )
      4:   {
      5:     return( val + incr );
      6:   }
      7:   return( val );
      8: }

Notice how just changing the open brace offset on line 4 is all we needed to do.  Since the other affected lines are indented relative to line 4, they are automatically indented the way you'd expect.  For more complicated examples, this may not always work.  The general approach to take is to always start adjusting offsets for lines higher up in the file, then reindent and see if any following lines need further adjustments.

 -- Command: c-set-offset symbol offset
     This is the command bound to C-c C-o.  It provides a convenient way to set offsets on c-offsets-alist both interactively (see the example above) and from your mode hook.

     It takes two arguments when used programmatically: SYMBOL is the syntactic element symbol to change and OFFSET is the new offset for that syntactic element.

Permanent Customization
=======================

To make your changes permanent, you need to add some lisp code to your .emacs file.  CC Mode supports many different ways to be configured, from the straightforward way by setting variables globally in .emacs or in the Customization interface, to the complex and precisely controlled way by using styles and hook functions.

The simplest way of customizing CC Mode permanently is to set the variables in your .emacs with setq and similar commands. So to make a permanent setting of substatement-open to 0, add this to the .emacs file:

     (setq c-offsets-alist
           '((substatement-open . 0)))

When CC Mode initializes a buffer, it will fill out c-offsets-alist with the remaining syntactic symbols according to the style system.

You can also use the more user friendly Customization interface, but this manual does not cover how that works.

Variables set like this at the top level in .emacs take effect in all CC Mode buffers, regardless of language.  The indentation style related variables, e.g., c-offsets-alist, that you don't set this way get their value from the style system (see Styles), and they therefore depend on the setting of c-default-style.  Note that if you use Customize, this means that the greyed-out default values presented there might not be the ones you actually get, since the actual values depend on the style, which may very well be different for different languages.

If you want to make more advanced configurations, e.g., language-specific customization, setting global variables isn't enough.  For that you can use the language hooks, see Hooks, and/or the style system, see Styles.

 -- User Option: c-style-variables-are-local-p
     By default, all style variables are buffer local, so that different buffers can have different style settings.  If you only use one style in all the files you edit you might want to share them between buffers so that a change take effect in all buffers.  That's done by setting this variable to nil.  The value takes effect when CC Mode is activated in a buffer for the first time in the Emacs session, so you typically set it in your .emacs file and then restart Emacs.

Hooks
=====

CC Mode provides several hooks that you can use to customize the mode according to your coding style.  Each language mode has its own hook, adhering to standard Emacs major mode conventions.  There is also one general hook and one package initialization hook:

 -- Variable: c-initialization-hook
     Hook run only once per Emacs session, when CC Mode is initialized.

 -- Variable: c-mode-common-hook
     Common hook across all languages.  It's run immediately before the language specific hook.

 -- Variable: c-mode-hook
 -- Variable: c++-mode-hook
 -- Variable: objc-mode-hook
 -- Variable: java-mode-hook
 -- Variable: idl-mode-hook
 -- Variable: pike-mode-hook
 -- Variable: awk-mode-hook
     The language specific mode hooks.  The appropriate one is run as the last thing when you enter that language mode.

Note that all the language-specific mode setup that CC Mode does is done prior to both c-mode-common-hook and the language specific hook. That includes installing the indentation style, which can be mode specific (and also is by default for Java mode).  Thus, any style settings done in c-mode-common-hook will override whatever language-specific style is chosen by c-default-style.

Here's a simplified example of what you can add to your .emacs file to do things whenever any CC Mode language is edited.  See the Emacs manuals for more information on customizing Emacs via hooks. See Sample .emacs File, for a more complete sample .emacs file.

     (defun my-c-mode-common-hook ()
       ;; my customizations for all of c-mode and related modes
       (no-case-fold-search)
       )
     (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

Styles
======

Most people only need to edit code formatted in just a few well-defined and consistent styles.  For example, their organization might impose a ``blessed'' style that all its programmers must conform to.  Similarly, people who work on GNU software will have to use the GNU coding style. Some shops are more lenient, allowing a variety of coding styles, and as programmers come and go, there could be a number of styles in use.  For this reason, CC Mode makes it convenient for you to set up logical groupings of customizations called styles, associate a single name for any particular style, and pretty easily start editing new or existing code using these styles.

The variables that the style system affect are called style variables.  They are handled specially in several ways:

  * Style variables are by default buffer local variables.  However, they can instead be made global by setting c-style-variables-are-local-p to nil before CC Mode is initialized.

  * The default value of any style variable (with two exceptions --- see below) is the special symbol set-from-style.  Variables that are still set to that symbol when a CC Mode buffer is initialized will be set according to the current style, otherwise they will keep their current value (This is a big change from versions of CC Mode
     earlier than 5.26, where such settings would get overridden by the style
     system unless special precautions were taken.  That was changed since it
     was counterintuitive and confusing, especially to novice users.  If your
     configuration depends on the old overriding behavior, you can set the
     variable c-old-style-variable-behavior to non-nil.).

     Note that when we talk about the ``default value'' for a style variable, we don't mean the set-from-style symbol that all style variables are set to initially, but instead the value it will get at mode initialization when neither a style nor a global setting has set its value.

     The style variable c-offsets-alist is handled a little differently from the other style variables.  It's an association list, and is thus by default set to the empty list, nil.  When the style system is initialized, any syntactic symbols already on it are kept --- only the missing ones are filled in from the chosen style.

     The style variable c-special-indent-hook is also handled in a special way.  Styles may only add more functions on this hook, so the global settings on it are always preserved (This did not change in version 5.26.).

  * The global settings of style variables get captured in the special user style, which is used as the base for all the other styles. See Built-in Styles, for details.

The style variables are: c-basic-offset, c-comment-only-line-offset, c-block-comment-prefix, c-comment-prefix-regexp, c-cleanup-list, c-hanging-braces-alist, c-hanging-colons-alist, c-hanging-semi&comma-criteria, c-backslash-column, c-backslash-max-column, c-special-indent-hook, c-label-minimum-indentation, and c-offsets-alist.

Built-in Styles
---------------

If you're lucky, one of CC Mode's built-in styles might be just what you're looking for.  These include:

gnu
     Coding style blessed by the Free Software Foundation for C code in GNU programs.

k&r
     The classic Kernighan and Ritchie style for C code.

bsd
     Also known as ``Allman style'' after Eric Allman.

whitesmith
     Popularized by the examples that came with Whitesmiths C, an early commercial C compiler.

stroustrup
     The classic Stroustrup style for C++ code.

ellemtel
     Popular C++ coding standards as defined by ``Programming in C++, Rules and Recommendations,'' Erik Nyquist and Mats Henricson, Ellemtel (This document is available at http://www.doc.ic.ac.uk/lab/cplus/c++.rules/ among other places.).

linux
     C coding standard for Linux (the kernel).

python
     C coding standard for Python extension modules (Python is a high level scripting language with a C/C++ foreign function interface. For more information, see http://www.python.org/.).

java
     The style for editing Java code.  Note that the default value for c-default-style installs this style when you enter java-mode.

user
     This is a special style for several reasons.  First, the CC Mode customizations you do by using either the Customization interface, or by writing setq's at the top level of your .emacs file, will be captured in the user style.  Also, all other styles implicitly inherit their settings from user style.  This means that for any styles you add via c-add-style (see Adding Styles) you need only define the differences between your new style and user style.

Choosing a Style
----------------

Use C-c . to choose a style interactively:

 -- Command: c-set-style style-name
     Switch to the specified style in the current buffer.  Use interactively like this:

          C-c . STYLE-NAME RET

     Note that all style names are case insensitive, even the ones you define.

     Setting a style in this way does not automatically reindent your file.  For commands that you can use to view the effect of your changes, see Commands.

The default style in all newly created buffers is gnu, except in Java mode where it's java.  Although the user style is not the default style, any style variable settings you do with the Customization interface or on the top level in your .emacs file will by default override the style system, so you don't need to set c-default-style to user to see the effect of such settings.

 -- User Option: c-default-style
     This variable specifies which style to install by default in new buffers.  It takes either a style name string, or an association list of major mode symbols to style names:

      1. When c-default-style is a string, it must be an existing style name.  This style is then used for all modes.

      2. When c-default-style is an association list, the mode language is looked up to find a style name string.

      3. If c-default-style is an association list where the mode language mode isn't found then the special symbol other is looked up.  If it's found then the associated style is used.

      4. If other is not found then the gnu style is used.

      5. In all cases, the style described in c-default-style is installed before the language hooks are run, so you can always override this setting by including an explicit call to c-set-style in your language mode hook, or in c-mode-common-hook.

 -- Variable: c-indentation-style
     This variable always contains the buffer's current style name, as a string.

Adding and Amending Styles
--------------------------

If none of the built-in styles is appropriate, you'll probably want to create a new style definition, possibly based on an existing style.  To do this, put the new style's settings into a list with the following format - the list can then be passed as an argument to the function c-add-style:

 -- List: style definition
     ([BASE-STYLE] [(VARIABLE . VALUE) ...])

     Optional BASE-STYLE, if present, must be a string which is the name of the base style from which this style inherits.  At most one BASE-STYLE is allowed in a style definition.  If BASE-STYLE is not specified, the style inherits from a table of default values (This table is stored internally in the
     variable c-fallback-style.  It is computed during the initialisation
     of CC Mode from the factory defaults of the style variables and any
     global values they may have been given since starting Emacs.) instead. All styles eventually inherit from this internal table.  Style loops generate errors.  The list of pre-existing styles can be seen in Built-in Styles.

     The dotted pairs (VARIABLE . VALUE) each consist of a variable and the value it is to be set to when the style is later activated. (In certain circumstances, this value can get
     overridden by another value.)  The variable can be either a CC Mode style variable or an arbitrary Emacs variable.  In the latter case, it is not made buffer local by the CC Mode style system.

Two variables are treated specially in the dotted pair list:

c-offsets-alist
     The value is in turn a dotted list on the form

     (SYNTACTIC-SYMBOL . OFFSET)

     as described in Customizing Indentation.  These are passed to c-set-offset so there is no need to set every syntactic symbol in your style, only those that are different from the inherited style.

c-special-indent-hook
     The value is added to c-special-indent-hook using add-hook, so any functions already on it are kept.  If the value is a list, each element of the list is added with add-hook.

Styles are kept in the c-style-alist variable, but you should never modify this variable directly.  Instead, CC Mode provides the function c-add-style for this purpose.

 -- Function: c-add-style stylename description &optional set-p
     Add or update a style called STYLENAME, a string. DESCRIPTION is the new style definition in the form described above.  If STYLENAME already exists in c-style-alist then it is replaced by DESCRIPTION.  (Note, this replacement is total.  The old style is not merged into the new one.) Otherwise, a new style is added.  If the optional SET-P is non-nil then the new style is applied to the current buffer as well.

     The sample .emacs file provides a concrete example of how a new style can be added and automatically set.  See Sample .emacs File.

 -- Variable: c-style-alist
     This is the variable that holds the definitions for the styles.  It should not be changed directly; use c-add-style instead.

File Styles
-----------

The Emacs manual describes how you can customize certain variables on a per-file basis by including a file local variable block at the end of the file.  So far, you've only seen a functional interface to CC Mode customization, which can't be used there.  CC Mode provides two variables allow customization of the indentation style on a per-file basis:

 -- Variable: c-file-style
     This variable can be set to a style name string.  When the file is visited, CC Mode will automatically set the file's style to this one using c-set-style.

 -- Variable: c-file-offsets
     This variable takes an association list similar to what is allowed in c-offsets-alist.  When the file is visited, CC Mode will automatically institute these offsets using c-set-offset.

Note that file style settings (i.e., c-file-style) are applied before file offset settings (i.e., c-file-offsets).  Also, if either of these are set in a file's local variable section, all the style variable values are made local to that buffer.

Advanced Customizations
=======================

For most users, CC Mode will support their coding styles with very little need for more advanced customizations.  Usually, one of the standard styles (see Built-in Styles) will do the trick.  At most, perhaps one of the syntactic symbol offsets will need to be tweaked slightly, or maybe c-basic-offset will need to be changed. However, some styles require a more flexible framework for customization, and one of the real strengths of CC Mode is that the syntactic analysis model provides just such a framework. This allows you to implement custom indentation calculations for situations not handled by the mode directly.

Custom Indentation Functions
----------------------------

The most flexible way to customize CC Mode is by writing custom indentation functions, and associating them with specific syntactic symbols (see Syntactic Symbols).  CC Mode itself uses indentation functions to provide more sophisticated indentation, for example when lining up C++ stream operator blocks:

      1: void main(int argc, char**)
      2: {
      3:   cout << "There were "
      4:     << argc
      5:     << "arguments passed to the program"
      6:     << endl;
      7: }

In this example, lines 4 through 6 are assigned the stream-op syntactic symbol.  Here, stream-op has an offset of +, and with a c-basic-offset of 2, you can see that lines 4 through 6 are simply indented two spaces to the right of line 3.  But perhaps we'd like CC Mode to be a little more intelligent so that it aligns all the << symbols in lines 3 through 6.  To do this, we have to write a custom indentation function which finds the column of the first stream operator on the first line of the statement.  Here is sample lisp code implementing this:

     (defun c-lineup-streamop (langelem)
       (save-excursion
         (goto-char (cdr langelem))
         (re-search-forward "<<\\|>>" (c-point 'eol) 'move)
         (goto-char (match-beginning 0))
         (vector (current-column))))

Indentation functions take a single argument, which is a syntactic component cons cell (see Syntactic Analysis).  The function can return an integer which is added to the running total indentation for the line, or a vector containing an integer which is an absolute column to align to.  Usually an absolute column is wanted when aligning to existing text, as in this example.

The function should return nil if it's used in a situation where it doesn't want to make any decision.  If the function is used in a list expression (see Customizing Indentation), that will cause CC Mode to go on and check the next entry in the list.

Now, to associate the function c-lineup-streamop with the stream-op syntactic symbol, we can add something like the following to our c++-mode-hook (It probably makes more sense to add this to c++-mode-hook than c-mode-common-hook since stream operators are only relevant for C++.):

     (c-set-offset 'stream-op 'c-lineup-streamop)

Now the function looks like this after reindenting (using C-c C-q):

      1: void main(int argc, char**)
      2: {
      3:   cout << "There were "
      4:        << argc
      5:        << " arguments passed to the program"
      6:        << endl;
      7: }

Custom indentation functions can be as simple or as complex as you like, and any syntactic symbol that appears in c-offsets-alist can have a custom indentation function associated with it.

CC Mode comes with an extensive set of predefined indentation functions, not all of which are used by the default styles.  So there's a good chance the function you want already exists.  See Indentation Functions, for a list of them.  If you have written an indentation function that you think is generally useful, you're very welcome to contribute it; please contact bug-cc-mode@gnu.org.

Custom Brace and Colon Hanging
------------------------------

Syntactic symbols aren't the only place where you can customize CC Mode with the lisp equivalent of callback functions.  Brace ``hanginess'' can also be determined by custom functions associated with syntactic symbols on the c-hanging-braces-alist style variable. Remember that ACTION's are typically a list containing some combination of the symbols before and after (see Hanging Braces).  However, an ACTION can also be a function which gets called when a brace matching that syntactic symbol is entered.

These ACTION functions are called with two arguments: the syntactic symbol for the brace, and the buffer position at which the brace was inserted.  The ACTION function is expected to return a list containing some combination of before and after, including neither of them (i.e., nil).  This return value has the normal brace hanging semantics.

As an example, CC Mode itself uses this feature to dynamically determine the hanginess of braces which close ``do-while'' constructs:

     void do_list( int count, char** atleast_one_string )
     {
         int i=0;
         do {
             handle_string( atleast_one_string[i] );
             i++;
         } while( i < count );
     }

CC Mode assigns the block-close syntactic symbol to the brace that closes the do construct, and normally we'd like the line that follows a block-close brace to begin on a separate line.  However, with ``do-while'' constructs, we want the while clause to follow the closing brace.  To do this, we associate the block-close symbol with the ACTION function c-snug-do-while:

     (defun c-snug-do-while (syntax pos)
       "Dynamically calculate brace hanginess for do-while statements."
       (save-excursion
         (let (langelem)
           (if (and (eq syntax 'block-close)
                    (setq langelem (assq 'block-close c-syntactic-context))
                    (progn (goto-char (cdr langelem))
                           (if (= (following-char) ?{)
                               (forward-sexp -1))
                           (looking-at "\\<do\\>[^_]")))
               '(before)
             '(before after)))))

This function simply looks to see if the brace closes a ``do-while'' clause and if so, returns the list (before) indicating that a newline should be inserted before the brace, but not after it. In all other cases, it returns the list (before after) so that the brace appears on a line by itself.

 -- Variable: c-syntactic-context
     During the call to the indentation or brace hanging ACTION function, this variable is bound to the full syntactic analysis list.

Note that for symmetry, colon hanginess should be customizable by allowing function symbols as ACTIONs on the c-hanging-colons-alist style variable.  Since no use has actually been found for this feature, it isn't currently implemented!

Customizing Semicolons and Commas
---------------------------------

You can also customize the insertion of newlines after semicolons and commas when the auto-newline minor mode is enabled (see Minor Modes).

 -- User Option: c-hanging-semi&comma-criteria
     This style variable takes a list of hooks that get called when a semicolon or comma is inserted.  The hooks are called in order without arguments, and are expected to return one of the following values:

     t
          A newline is inserted, and no more functions from the list are called.

     stop
          No more functions from the list are called, but no newline is inserted.

     nil
          No determination is made, and the next function in the list is called.

     If every function in the list is called without a determination being made, then no newline is added. The default value for this variable is a list containing a single function which inserts newlines only after semicolons which do not appear inside parenthesis lists (i.e., those that separate for-clause statements).

 -- Function: c-semi&comma-no-newlines-before-nonblanks
     This is an example of a criteria function, provided by CC Mode.  It prevents newlines from being inserted after semicolons when there is a non-blank following line.  Otherwise, it makes no determination.  To use, add this function to the front of the c-hanging-semi&comma-criteria list.

          (defun c-semi&comma-no-newlines-before-nonblanks ()
            (save-excursion
              (if (and (eq last-command-char ?\;)
                       (zerop (forward-line 1))
                       (not (looking-at "^[ \t]*$")))
                  'stop
                nil)))

 -- Function: c-semi&comma-inside-parenlist
 -- Function: c-semi&comma-no-newlines-for-oneline-inliners
     The function c-semi&comma-inside-parenlist is what prevents newlines from being inserted inside the parenthesis list of for statements.  In addition to c-semi&comma-no-newlines-before-nonblanks described above, CC Mode also comes with the criteria function c-semi&comma-no-newlines-for-oneline-inliners, which suppresses newlines after semicolons inside one-line inline method definitions (e.g., in C++ or Java).

Other Special Indentations
--------------------------

Here are the remaining odds and ends regarding indentation:

 -- User Option: c-label-minimum-indentation
     In gnu style (see Built-in Styles), a minimum indentation is imposed on lines inside top-level constructs.  This minimum indentation is controlled by this style variable.  The default value is 1.

 -- User Option: c-special-indent-hook
     This style variable is a standard hook variable that is called after every line is indented by CC Mode.  You can use it to do any special indentation or line adjustments your style dictates, such as adding extra indentation to constructors or destructor declarations in a class definition, etc.  Note that you should not change point or mark inside your c-special-indent-hook functions, i.e., you'll probably want to wrap your function in a save-excursion.

     Setting c-special-indent-hook in your style definition is handled slightly differently than other variables.  In your style definition, you should set the value for c-special-indent-hook to a function or list of functions, which will be appended to c-special-indent-hook using add-hook.  That way, the current setting for the buffer local value of c-special-indent-hook won't be overridden.

Syntactic Symbols
*****************

Here is a complete list of the recognized syntactic symbols as described in the c-offsets-alist style variable, along with a brief description.  More detailed descriptions follow.

string
     Inside a multiline string.

c
     Inside a multiline C style block comment.

defun-open
     Brace that opens a top-level function definition.

defun-close
     Brace that closes a top-level function definition.

defun-block-intro
     The first line in a top-level defun.

class-open
     Brace that opens a class definition.

class-close
     Brace that closes a class definition.

inline-open
     Brace that opens an in-class inline method.

inline-close
     Brace that closes an in-class inline method.

func-decl-cont
     The region between a function definition's argument list and the function opening brace (excluding K&R argument declarations).  In C, you cannot put anything but whitespace and comments in this region, however in C++ and Java, throws declarations and other things can appear here.

knr-argdecl-intro
     First line of a K&R C argument declaration.

knr-argdecl
     Subsequent lines in a K&R C argument declaration.

topmost-intro
     The first line in a ``topmost'' definition.

topmost-intro-cont
     Topmost definition continuation lines.  This is only used in the parts that aren't covered by other symbols such as func-decl-cont and knr-argdecl.

member-init-intro
     First line in a member initialization list.

member-init-cont
     Subsequent member initialization list lines.

inher-intro
     First line of a multiple inheritance list.

inher-cont
     Subsequent multiple inheritance lines.

block-open
     Statement block open brace.

block-close
     Statement block close brace.

brace-list-open
     Open brace of an enum or static array list.

brace-list-close
     Close brace of an enum or static array list.

brace-list-intro
     First line in an enum or static array list.

brace-list-entry
     Subsequent lines in an enum or static array list.

brace-entry-open
     Subsequent lines in an enum or static array list where the line begins with an open brace.

statement
     A statement.

statement-cont
     A continuation of a statement.

statement-block-intro
     The first line in a new statement block.

statement-case-intro
     The first line in a case block.

statement-case-open
     The first line in a case block that starts with a brace.

substatement
     The first line after a conditional or loop construct.

substatement-open
     The brace that opens a substatement block.

substatement-label
     The first line after a conditional or loop construct if it's a label.

case-label
     A label in a switch block.

access-label
     C++ access control label.

label
     Any other label.

do-while-closure
     The while line that ends a do-while construct.

else-clause
     The else line of an if-else construct.

catch-clause
     The catch or finally (in Java) line of a try-catch construct.

comment-intro
     A line containing only a comment introduction.

arglist-intro
     The first line in an argument list.

arglist-cont
     Subsequent argument list lines when no arguments follow on the same line as the arglist opening paren.

arglist-cont-nonempty
     Subsequent argument list lines when at least one argument follows on the same line as the arglist opening paren.

arglist-close
     The solo close paren of an argument list.

stream-op
     Lines continuing a stream operator (C++ only).

inclass
     The line is nested inside a class definition.

cpp-macro
     The start of a preprocessor macro definition.

cpp-define-intro
     The first line inside a multiline preproprocessor macro if c-syntactic-indentation-in-macros is set.

cpp-macro-cont
     All lines inside multiline preprocessor macros if c-syntactic-indentation-in-macros is nil.

friend
     A C++ friend declaration.

objc-method-intro
     The first line of an Objective-C method definition.

objc-method-args-cont
     Lines continuing an Objective-C method definition.

objc-method-call-cont
     Lines continuing an Objective-C method call.

extern-lang-open
     Brace that opens an extern block (e.g., extern "C" {...}).

extern-lang-close
     Brace that closes an extern block.

inextern-lang
     Analogous to inclass syntactic symbol, but used inside extern blocks.

namespace-open
namespace-close
innamespace
     These are analogous to the three extern-lang symbols above, but are returned for C++ namespace blocks.

module-open
module-close
inmodule
     Analogous to the above, but for CORBA IDL module blocks.

composition-open
composition-close
incomposition
     Analogous to the above, but for CORBA CIDL composition blocks.

template-args-cont
     C++ template argument list continuations.

inlambda
     Analogous to inclass syntactic symbol, but used inside lambda (i.e., anonymous) functions.  Only used in Pike mode.

lambda-intro-cont
     Lines continuing the header of a lambda function, i.e., between the lambda keyword and the function body.  Only used in Pike mode.

inexpr-statement
     A statement block inside an expression.  The gcc C and C++ extension for this is recognized.  It's also used for the special functions that take a statement block as an argument in Pike.

inexpr-class
     A class definition inside an expression.  This is used for anonymous classes in Java.  It's also used for anonymous array initializers in Java.

Most syntactic symbol names follow a general naming convention.  When a line begins with an open or close brace, the syntactic symbol will contain the suffix -open or -close respectively.

Usually, a distinction is made between the first line that introduces a construct and lines that continue a construct, and the syntactic symbols that represent these lines will contain the suffix -intro or -cont respectively.  As a sub-classification of this scheme, a line which is the first of a particular brace block construct will contain the suffix -block-intro.

Let's look at some examples to understand how this works.  Remember that you can check the syntax of any line by using C-c C-s.

      1: void
      2: swap( int& a, int& b )
      3: {
      4:     int tmp = a;
      5:     a = b;
      6:     b = tmp;
      7:     int ignored =
      8:         a + b;
      9: }

Line 1 shows a topmost-intro since it is the first line that introduces a top-level construct.  Line 2 is a continuation of the top-level construct introduction so it has the syntax topmost-intro-cont.  Line 3 shows a defun-open since it is the brace that opens a top-level function definition.  Line 9 is the corresponding defun-close since it contains the brace that closes the top-level function definition.  Line 4 is a defun-block-intro, i.e., it is the first line of a brace-block, enclosed in a top-level function definition.

Lines 5, 6, and 7 are all given statement syntax since there isn't much special about them.  Note however that line 8 is given statement-cont syntax since it continues the statement begun on the previous line.

Here's another example, which illustrates some C++ class syntactic symbols:

      1: class Bass
      2:     : public Guitar,
      3:       public Amplifiable
      4: {
      5: public:
      6:     Bass()
      7:         : eString( new BassString( 0.105 )),
      8:           aString( new BassString( 0.085 )),
      9:           dString( new BassString( 0.065 )),
     10:           gString( new BassString( 0.045 ))
     11:     {
     12:         eString.tune( 'E' );
     13:         aString.tune( 'A' );
     14:         dString.tune( 'D' );
     15:         gString.tune( 'G' );
     16:     }
     17:     friend class Luthier;
     18: };

As in the previous example, line 1 has the topmost-intro syntax. Here however, the brace that opens a C++ class definition on line 4 is assigned the class-open syntax.  Note that in C++, classes, structs, and unions are essentially equivalent syntactically (and are very similar semantically), so replacing the class keyword in the example above with struct or union would still result in a syntax of class-open for line 4  (This is the case even for C and Objective-C.  For consistency, structs in all supported languages are syntactically equivalent to classes.  Note however that the keyword class is meaningless in C and Objective-C.). Similarly, line 18 is assigned class-close syntax.

Line 2 introduces the inheritance list for the class so it is assigned the inher-intro syntax, and line 3, which continues the inheritance list is given inher-cont syntax.

Hitting C-c C-s on line 5 shows the following analysis:

     ((inclass 58) (access-label 58))

The primary syntactic symbol for this line is access-label as this a label keyword that specifies access protection in C++.  However, because this line is also a top-level construct inside a class definition, the analysis actually shows two syntactic symbols.  The other syntactic symbol assigned to this line is inclass. Similarly, line 6 is given both inclass and topmost-intro syntax:

     ((inclass 58) (topmost-intro 60))

Line 7 introduces a C++ member initialization list and as such is given member-init-intro syntax.  Note that in this case it is not assigned inclass since this is not considered a top-level construct.  Lines 8 through 10 are all assigned member-init-cont since they continue the member initialization list started on line 7.

Line 11's analysis is a bit more complicated:

     ((inclass 58) (inline-open))

This line is assigned a syntax of both inline-open and inclass because it opens an in-class C++ inline method definition.  This is distinct from, but related to, the C++ notion of an inline function in that its definition occurs inside an enclosing class definition, which in C++ implies that the function should be inlined. However, if the definition of the Bass constructor appeared outside the class definition, the construct would be given the defun-open syntax, even if the keyword inline appeared before the method name, as in:

      1: class Bass
      2:     : public Guitar,
      3:       public Amplifiable
      4: {
      5: public:
      6:     Bass();
      7: };
      8:
      9: inline
     10: Bass::Bass()
     11:     : eString( new BassString( 0.105 )),
     12:       aString( new BassString( 0.085 )),
     13:       dString( new BassString( 0.065 )),
     14:       gString( new BassString( 0.045 ))
     15: {
     16:     eString.tune( 'E' );
     17:     aString.tune( 'A' );
     18:     dString.tune( 'D' );
     19:     gString.tune( 'G' );
     20: }

Returning to the previous example, line 16 is given inline-close syntax, while line 12 is given defun-block-open syntax, and lines 13 through 15 are all given statement syntax.  Line 17 is interesting in that its syntactic analysis list contains three elements:

     ((inclass 58) (topmost-intro 380) (friend))

The friend syntactic symbol is a modifier that typically does not have a relative buffer position.

Template definitions introduce yet another syntactic symbol:

      1: ThingManager <int,
      2:    Framework::Callback *,
      3:    Mutex> framework_callbacks;

Here, line 1 is analyzed as a topmost-intro, but lines 2 and 3 are both analyzed as template-args-cont lines.

Here is another (totally contrived) example which illustrates how syntax is assigned to various conditional constructs:

      1: void spam( int index )
      2: {
      3:     for( int i=0; i<index; i++ )
      4:     {
      5:         if( i == 10 )
      6:             do_something_special();
      7:         else
      8:           silly_label:
      9:             do_something( i );
     10:     }
     11:     do {
     12:         another_thing( i-- );
     13:     }
     14:     while( i > 0 );
     15: }

Only the lines that illustrate new syntactic symbols will be discussed.

Line 4 has a brace which opens a conditional's substatement block.  It is thus assigned substatement-open syntax, and since line 5 is the first line in the substatement block, it is assigned substatement-block-intro syntax.  Line 10 contains the brace that closes the inner substatement block, and is therefore given the syntax block-close.  Line 13 is treated the same way.

Lines 6 and 9 are also substatements of conditionals, but since they don't start blocks they are given substatement syntax instead of substatement-open.

Line 8 contains a label, which is normally given label syntax. This one is however a bit special since it's between a conditional and its substatement.  It's analyzed as substatement-label to let you handle this rather odd case differently from normal labels.

Line 7 start with an else that matches the if statement on line 5.  It is therefore given the else-clause syntax and is anchored on the matching if.  The try-catch constructs in C++ and Java are treated this way too, except that catch and (in Java) finally, are marked with catch-clause.

The while construct on line 14 that closes a do conditional is given the special syntax do-while-closure if it appears on a line by itself.  Note that if the while appeared on the same line as the preceding close brace, that line would still have block-close syntax.

Switch statements have their own set of syntactic symbols.  Here's an example:

      1: void spam( enum Ingredient i )
      2: {
      3:     switch( i ) {
      4:     case Ham:
      5:         be_a_pig();
      6:         break;
      7:     case Salt:
      8:         drink_some_water();
      9:         break;
     10:     default:
     11:         {
     12:             what_is_it();
     13:             break;
     14:         }
     15:     }
     14: }

Here, lines 4, 7, and 10 are all assigned case-label syntax, while lines 5 and 8 are assigned statement-case-intro.  Line 11 is treated slightly differently since it contains a brace that opens a block --- it is given statement-case-open syntax.

There are a set of syntactic symbols that are used to recognize constructs inside of brace lists.  A brace list is defined as an enum or aggregate initializer list, such as might statically initialize an array of structs.  The three special aggregate constructs in Pike, ({ }), ([ ]) and (< >), are treated as brace lists too.  An example:

      1: static char* ingredients[] =
      2: {
      3:     "Ham",
      4:     "Salt",
      5:     NULL
      6: };

Following convention, line 2 in this example is assigned brace-list-open syntax, and line 3 is assigned brace-list-intro syntax.  Likewise, line 6 is assigned brace-list-close syntax.  Lines 4 and 5 however, are assigned brace-list-entry syntax, as would all subsequent lines in this initializer list.

Your static initializer might be initializing nested structures, for example:

      1: struct intpairs[] =
      2: {
      3:     { 1, 2 },
      4:     {
      5:         3,
      6:         4
      7:     }
      8:     { 1,
      9:       2 },
     10:     { 3, 4 }
     11: };

Here, you've already seen the analysis of lines 1, 2, 3, and 11.  On line 4, things get interesting; this line is assigned brace-entry-open syntactic symbol because it's a bracelist entry line that starts with an open brace.  Lines 5 and 6 (and line 9) are pretty standard, and line 7 is a brace-list-close as you'd expect.  Once again, line 8 is assigned as brace-entry-open as is line 10.

External language definition blocks also have their own syntactic symbols.  In this example:

      1: extern "C"
      2: {
      3:     int thing_one( int );
      4:     int thing_two( double );
      5: }

line 2 is given the extern-lang-open syntax, while line 5 is given the extern-lang-close syntax.  The analysis for line 3 yields:

     ((inextern-lang) (topmost-intro 14))

where inextern-lang is a modifier similar in purpose to inclass.

There are various other top level blocks like extern, and they are all treated in the same way except that the symbols are named after the keyword that introduces the block.  e.g., C++ namespace blocks get the three symbols namespace-open, namespace-close and innamespace.  The currently recognized top level blocks are:

extern-lang-open, extern-lang-close, inextern-lang
     extern blocks in C and C++. (These should logically be named extern-open, extern-close and inextern, but that isn't the case for historical reasons.)

namespace-open, namespace-close, innamespace
     namespace blocks in C++.

module-open, module-close, inmodule
     module blocks in CORBA IDL.

composition-open, composition-close, incomposition
     composition blocks in CORBA CIDL.

A number of syntactic symbols are associated with parenthesis lists, a.k.a argument lists, as found in function declarations and function calls.  This example illustrates these:

      1: void a_function( int line1,
      2:                  int line2 );
      3:
      4: void a_longer_function(
      5:     int line1,
      6:     int line2
      7:     );
      8:
      9: void call_them( int line1, int line2 )
     10: {
     11:     a_function(
     12:         line1,
     13:         line2
     14:         );
     15:
     16:     a_longer_function( line1,
     17:                        line2 );
     18: }

Lines 5 and 12 are assigned arglist-intro syntax since they are the first line following the open parenthesis, and lines 7 and 14 are assigned arglist-close syntax since they contain the parenthesis that closes the argument list.

Lines that continue argument lists can be assigned one of two syntactic symbols.  For example, Lines 2 and 17 are assigned arglist-cont-nonempty syntax.  What this means is that they continue an argument list, but that the line containing the parenthesis that opens the list is not empty following the open parenthesis.  Contrast this against lines 6 and 13 which are assigned arglist-cont syntax.  This is because the parenthesis that opens their argument lists is the last character on that line.

Note that there is no arglist-open syntax.  This is because any parenthesis that opens an argument list, appearing on a separate line, is assigned the statement-cont syntax instead.

A few miscellaneous syntactic symbols that haven't been previously covered are illustrated by this C++ example:

      1: void Bass::play( int volume )
      2: const
      3: {
      4:     /* this line starts a multiline
      5:      * comment.  This line should get `c' syntax */
      6:
      7:     char* a_multiline_string = "This line starts a multiline \
      8: string.  This line should get `string' syntax.";
      9:
     10:   note:
     11:     {
     12: #ifdef LOCK
     13:         Lock acquire();
     14: #endif // LOCK
     15:         slap_pop();
     16:         cout << "I played "
     17:              << "a note\n";
     18:     }
     19: }

The lines to note in this example include:

  * Line 2 is assigned the func-decl-cont syntax.

  * Line 4 is assigned both defun-block-intro and comment-intro syntax.

  * Line 5 is assigned c syntax.

  * Line 6 which, even though it contains nothing but whitespace, is assigned defun-block-intro.  Note that the appearance of the comment on lines 4 and 5 do not cause line 6 to be assigned statement syntax because comments are considered to be syntactic whitespace, which are ignored when analyzing code.

  * Line 8 is assigned string syntax.

  * Line 10 is assigned label syntax.

  * Line 11 is assigned block-open syntax.

  * Lines 12 and 14 are assigned cpp-macro syntax in addition to the normal syntactic symbols (statement-block-intro and statement, respectively).  Normally cpp-macro is configured to cancel out the normal syntactic context to make all preprocessor directives stick to the first column, but that's easily changed if you want preprocessor directives to be indented like the rest of the code.

  * Line 17 is assigned stream-op syntax.

Multiline preprocessor macro definitions are normally handled just like other code, i.e., the lines inside them are indented according to the syntactic analysis of the preceding lines inside the macro.  The first line inside a macro definition (i.e., the line after the starting line of the cpp directive itself) gets cpp-define-intro.  In this example:

      1: #define LIST_LOOP(cons, listp)                         \
      2:   for (cons = listp; !NILP (cons); cons = XCDR (cons)) \
      3:     if (!CONSP (cons))                                 \
      4:       signal_error ("Invalid list format", listp);     \
      5:     else

line 1 is given the syntactic symbol cpp-macro.  The first line of a cpp directive is always given that symbol.  Line 2 is given cpp-define-intro, so that you can give the macro body as a whole some extra indentation.  Lines 3 through 5 are then analyzed as normal code, i.e., substatement on lines 3 and 4, and else-clause on line 5.

The syntactic analysis inside macros can be turned off with c-syntactic-indentation-in-macros.  In that case, lines 2 through 5 would all be given cpp-macro-cont with a relative buffer position pointing to the # which starts the cpp directive (This is how CC Mode 5.28 and earlier analyzed
macros.).

See Macro Handling, for more info about the treatment of macros.

In Objective-C buffers, there are three additional syntactic symbols assigned to various message calling constructs.  Here's an example illustrating these:

      1: - (void)setDelegate:anObject
      2:           withStuff:stuff
      3: {
      4:     [delegate masterWillRebind:self
      5:               toDelegate:anObject
      6:               withExtraStuff:stuff];
      7: }

Here, line 1 is assigned objc-method-intro syntax, and line 2 is assigned objc-method-args-cont syntax.  Lines 5 and 6 are both assigned objc-method-call-cont syntax.

Java has a concept of anonymous classes, which may look something like this:

      1: public void watch(Observable o) {
      2:     o.addObserver(new Observer() {
      3:             public void update(Observable o, Object arg) {
      4:                 history.addElement(arg);
      5:             }
      6:         });
      7: }

The brace following the new operator opens the anonymous class. Lines 3 and 6 are assigned the inexpr-class syntax, besides the inclass symbol used in normal classes.  Thus, the class will be indented just like a normal class, with the added indentation given to inexpr-class.

There are a few occasions where a statement block may be used inside an expression.  One is in C or C++ code using the gcc extension for this, e.g:

      1: int res = ({
      2:         int y = foo (); int z;
      3:         if (y > 0) z = y; else z = - y;
      4:         z;
      5:     });

Lines 2 and 5 get the inexpr-statement syntax, besides the symbols they'd get in a normal block.  Therefore, the indentation put on inexpr-statement is added to the normal statement block indentation.

In Pike code, there are a few other situations where blocks occur inside statements, as illustrated here:

      1: array itgob()
      2: {
      3:     string s = map (backtrace()[-2][3..],
      4:                     lambda
      5:                         (mixed arg)
      6:                     {
      7:                         return sprintf ("%t", arg);
      8:                     }) * ", " + "\n";
      9:     return catch {
     10:             write (s + "\n");
     11:         };
     12: }

Lines 4 through 8 contain a lambda function, which CC Mode recognizes by the lambda keyword.  If the function argument list is put on a line of its own, as in line 5, it gets the lambda-intro-cont syntax.  The function body is handled as an inline method body, with the addition of the inlambda syntactic symbol.  This means that line 6 gets inlambda and inline-open, and line 8 gets inline-close (You might wonder why it doesn't get inlambda too.  It's because the closing brace is relative to the opening brace, which stands on its own line in this example.  If the opening brace was hanging on the previous line, then the closing brace would get the inlambda syntax too to be indented correctly.).

On line 9, catch is a special function taking a statement block as its argument.  The block is handled as an in-expression statement with the inexpr-statement syntax, just like the gcc extended C example above.  The other similar special function, gauge, is handled like this too.

Two other syntactic symbols can appear in old style, non-prototyped C code  (a.k.a. K&R C, or Kernighan & Ritchie C):

      1: int add_three_integers(a, b, c)
      2:      int a;
      3:      int b;
      4:      int c;
      5: {
      6:     return a + b + c;
      7: }

Here, line 2 is the first line in an argument declaration list and so is given the knr-argdecl-intro syntactic symbol.  Subsequent lines (i.e., lines 3 and 4 in this example), are given knr-argdecl syntax.

Indentation Functions
*********************

Often there are cases when a simple offset setting on a syntactic symbol isn't enough to get the desired indentation.  Therefore, it's also possible to use an indentation function (a.k.a. line-up function) for a syntactic symbol.

CC Mode comes with many predefined indentation functions for common situations.  If none of these does what you want, you can write your own, see Custom Indentation Functions.  If you do, it's probably a good idea to start working from one of these predefined functions, they can be found in the file cc-align.el.

For every function below there is a ``works with'' list that indicates which syntactic symbols the function is intended to be used with.

 -- Function: c-indent-one-line-block
     Indent a one line block c-basic-offset extra.  E.g:

          if (n > 0)
              {m+=n; n=0;}      <- c-indent-one-line-block
          <--> c-basic-offset

     and

          if (n > 0)
          {                     <- c-indent-one-line-block
              m+=n; n=0;
          }

     The block may be surrounded by any kind of parenthesis characters. nil is returned if the line doesn't start with a one line block, which makes the function usable in list expressions.

     Works with: Almost all syntactic symbols, but most useful on the -open symbols.

 -- Function: c-indent-multi-line-block
     Indent a multiline block c-basic-offset extra.  E.g:

          int *foo[] = {
              NULL,
              {17},             <- c-indent-multi-line-block

     and

          int *foo[] = {
              NULL,
                  {             <- c-indent-multi-line-block
                  17
                  },
              <--> c-basic-offset

     The block may be surrounded by any kind of parenthesis characters. nil is returned if the line doesn't start with a multiline block, which makes the function usable in list expressions.

     Works with: Almost all syntactic symbols, but most useful on the -open symbols.

 -- Function: c-lineup-argcont
     Line up a continued argument.  E.g:

          foo (xyz, aaa + bbb + ccc
                    + ddd + eee + fff);  <- c-lineup-argcont

     Only continuation lines like this are touched, nil is returned on lines which are the start of an argument.

     Within a gcc asm block, : is recognised as an argument separator, but of course only between operand specifications, not in the expressions for the operands.

     Works with: arglist-cont, arglist-cont-nonempty.

 -- Function: c-lineup-arglist
     Line up the current argument line under the first argument.

     As a special case, if an argument on the same line as the open parenthesis starts with a brace block opener, the indentation is c-basic-offset only.  This is intended as a ``DWIM'' measure in cases like macros that contains statement blocks, e.g:

          A_VERY_LONG_MACRO_NAME ({
                  some (code, with + long, lines * in[it]);
              });
          <--> c-basic-offset

     This is motivated partly because it's more in line with how code blocks are handled, and partly since it approximates the behavior of earlier CC Mode versions, which due to inaccurate analysis tended to indent such cases this way.

     Works with: arglist-cont-nonempty, arglist-close.

 -- Function: c-lineup-arglist-intro-after-paren
     Line up a line to just after the open paren of the surrounding paren or brace block.

     Works with: defun-block-intro, brace-list-intro, statement-block-intro, statement-case-intro, arglist-intro.

 -- Function: c-lineup-arglist-close-under-paren
     Set your arglist-close syntactic symbol to this line-up function so that parentheses that close argument lists will line up under the parenthesis that opened the argument list.  It can also be used with arglist-cont and arglist-cont-nonempty to line up all lines inside a parenthesis under the open paren.

     As a special case, if a brace block is opened at the same line as the open parenthesis of the argument list, the indentation is c-basic-offset only.  See c-lineup-arglist for further discussion of this ``DWIM'' measure.

     Works with: Almost all symbols, but are typically most useful on arglist-close, brace-list-close, arglist-cont and arglist-cont-nonempty.

 -- Function: c-lineup-arglist-operators
     Line up lines starting with an infix operator under the open paren. Return nil on lines that don't start with an operator, to leave those cases to other lineup functions.  Example:

          if (  x < 10
             || at_limit (x,     <- c-lineup-arglist-operators
                          list)  <- c-lineup-arglist-operators returns nil
             )

     Since this function doesn't do anything for lines without an infix operator you typically want to use it together with some other lineup settings, e.g., as follows (the arglist-close setting is just a suggestion to get a consistent style):

          (c-set-offset 'arglist-cont
                        '(c-lineup-arglist-operators 0))
          (c-set-offset 'arglist-cont-nonempty
                        '(c-lineup-arglist-operators c-lineup-arglist))
          (c-set-offset 'arglist-close
                        '(c-lineup-arglist-close-under-paren))

     Works with: arglist-cont, arglist-cont-nonempty.

 -- Function: c-lineup-C-comments
     Line up C block comment continuation lines.  Various heuristics are used to handle most of the common comment styles.  Some examples:

          /*                 /**               /*
           * text             * text             text
           */                 */               */

          /* text            /*                /**
             text            ** text            ** text
          */                 */                 */

          /**************************************************
           * text
           *************************************************/

          /**************************************************
              Free form text comments:
           In comments with a long delimiter line at the
           start, the indentation is kept unchanged for lines
           that start with an empty comment line prefix.  The
           delimiter line is whatever matches the
           comment-start-skip regexp.
          **************************************************/

     The style variable c-comment-prefix-regexp is used to recognize the comment line prefix, e.g., the * that usually starts every line inside a comment.

     Works with: The c syntactic symbol.

 -- Function: c-lineup-cascaded-calls
     Line up ``cascaded calls'' under each other.  If the line begins with -> or . and the preceding line ends with one or more function calls preceded by the same token, then the arrow is lined up with the first of those tokens.  E.g:

          r = proc->add(17)->add(18)
                  ->add(19) +         <- c-lineup-cascaded-calls
            offset;                   <- c-lineup-cascaded-calls (inactive)

     In any other situation nil is returned to allow use in list expressions.

     Works with: topmost-intro-cont, statement-cont, arglist-cont, arglist-cont-nonempty.

 -- Function: c-lineup-close-paren
     Line up the closing paren under its corresponding open paren if the open paren is followed by code.  If the open paren ends its line, no indentation is added.  E.g:

          main (int,
                char **
               )                <- c-lineup-close-paren

     and

          main (
              int, char **
          )                     <- c-lineup-close-paren

     As a special case, if a brace block is opened at the same line as the open parenthesis of the argument list, the indentation is c-basic-offset instead of the open paren column.  See c-lineup-arglist for further discussion of this ``DWIM'' measure.

     Works with: All *-close symbols.

 -- Function: c-lineup-comment
     Line up a comment-only line according to the style variable c-comment-only-line-offset.  If the comment is lined up with a comment starter on the previous line, that alignment is preserved.

      -- User Option: c-comment-only-line-offset
          This style variable specifies the extra offset for the line.  It can contain an integer or a cons cell of the form

               (NON-ANCHORED-OFFSET . ANCHORED-OFFSET)

          where NON-ANCHORED-OFFSET is the amount of offset given to non-column-zero anchored lines, and ANCHORED-OFFSET is the amount of offset to give column-zero anchored lines.  Just an integer as value is equivalent to (VALUE . -1000).

     Works with: comment-intro.

 -- Function: c-lineup-cpp-define
     Line up macro continuation lines according to the indentation of the construct preceding the macro.  E.g:

          const char msg[] =    <- The beginning of the preceding construct.
            \"Some text.\";

          #define X(A, B)  \
          do {             \    <- c-lineup-cpp-define
            printf (A, B); \
          } while (0)

     and:

          int dribble() {
            if (!running)       <- The beginning of the preceding construct.
              error(\"Not running!\");

          #define X(A, B)    \
            do {             \  <- c-lineup-cpp-define
              printf (A, B); \
            } while (0)

     If c-syntactic-indentation-in-macros is non-nil, the function returns the relative indentation to the macro start line to allow accumulation with other offsets.  e.g., in the following cases, cpp-define-intro is combined with the statement-block-intro that comes from the do { that hangs on the #define line:

          const char msg[] =
            \"Some text.\";

          #define X(A, B) do { \
            printf (A, B);     \  <- c-lineup-cpp-define
            this->refs++;      \
          } while (0)             <- c-lineup-cpp-define

     and:

          int dribble() {
            if (!running)
              error(\"Not running!\");

          #define X(A, B) do { \
              printf (A, B);   \  <- c-lineup-cpp-define
              this->refs++;    \
            } while (0)           <- c-lineup-cpp-define

     The relative indentation returned by c-lineup-cpp-define is zero and two, respectively, on the two lines in each of these examples.  They are then added to the two column indentation that statement-block-intro gives in both cases here.

     If the relative indentation is zero, then nil is returned instead.  That is useful in a list expression to specify the default indentation on the top level.

     If c-syntactic-indentation-in-macros is nil then this function keeps the current indentation, except for empty lines (ignoring the ending backslash) where it takes the indentation from the closest preceding nonempty line in the macro.  If there's no such line in the macro then the indentation is taken from the construct preceding it, as described above.

     Works with: cpp-define-intro.

 -- Function: c-lineup-dont-change
     This lineup function makes the line stay at whatever indentation it already has; think of it as an identity function for lineups.

     Works with: Any syntactic symbol.

 -- Function: c-lineup-gcc-asm-reg
     Line up a gcc asm register under one on a previous line.

              asm ("foo %1, %0\n"
                   "bar %0, %1"
                   : "=r" (w),
                     "=r" (x)
                   :  "0" (y),
                      "1" (z));

     The x line is aligned to the text after the : on the w line, and similarly z under y.

     This is done only in an asm or __asm__ block, and only to those lines mentioned.  Anywhere else nil is returned.  The usual arrangement is to have this routine as an extra feature at the start of arglist lineups, e.g.

          (c-lineup-gcc-asm-reg c-lineup-arglist)

     Works with: arglist-cont, arglist-cont-nonempty.

 -- Function: c-lineup-inexpr-block
     This can be used with the in-expression block symbols to indent the whole block to the column where the construct is started.  e.g., for Java anonymous classes, this lines up the class under the new keyword, and in Pike it lines up the lambda function body under the lambda keyword.  Returns nil if the block isn't part of such a construct.

     Works with: inlambda, inexpr-statement, inexpr-class.

 -- Function: c-lineup-java-inher
     Line up Java implements and extends declarations.  If class names follow on the same line as the implements/extends keyword, they are lined up under each other.  Otherwise, they are indented by adding c-basic-offset to the column of the keyword. E.g:

          class Foo
              extends
                  Bar           <- c-lineup-java-inher
              <--> c-basic-offset

     and

          class Foo
              extends Cyphr,
                      Bar       <- c-lineup-java-inher

     Works with: inher-cont.

 -- Function: c-lineup-java-throws
     Line up Java throws declarations.  If exception names follow on the same line as the throws keyword, they are lined up under each other. Otherwise, they are indented by adding c-basic-offset to the column of the throws keyword.  The throws keyword itself is also indented by c-basic-offset from the function declaration start if it doesn't hang.  E.g:

          int foo()
              throws            <- c-lineup-java-throws
                  Bar           <- c-lineup-java-throws
          <--><--> c-basic-offset

     and

          int foo() throws Cyphr,
                           Bar,    <- c-lineup-java-throws
                           Vlod    <- c-lineup-java-throws

     Works with: func-decl-cont.

 -- Function: c-lineup-knr-region-comment
     Line up a comment in the ``K&R region'' with the declaration.  That is the region between the function or class header and the beginning of the block.  E.g:

          int main()
          /* Called at startup. */  <- c-lineup-knr-region-comment
          {
            return 0;
          }

     Return nil if called in any other situation, to be useful in list expressions.

     Works with: comment-intro.

 -- Function: c-lineup-math
     Line up the current line to after the equal sign on the first line in the statement.  If there isn't any, indent with c-basic-offset.  If the current line contains an equal sign too, try to align it with the first one.

     Works with: topmost-intro-cont, statement-cont, arglist-cont, arglist-cont-nonempty.

 -- Function: c-lineup-multi-inher
     Line up the classes in C++ multiple inheritance clauses and member initializers under each other.  E.g:

          Foo::Foo (int a, int b):
              Cyphr (a),
              Bar (b)           <- c-lineup-multi-inher

     and

          class Foo
              : public Cyphr,
                public Bar      <- c-lineup-multi-inher

     and

          Foo::Foo (int a, int b)
              : Cyphr (a)
              , Bar (b)         <- c-lineup-multi-inher

     Works with: inher-cont, member-init-cont.

 -- Function: c-lineup-ObjC-method-call
     For Objective-C code, line up selector args as Emacs Lisp mode does with function args: go to the position right after the message receiver, and if you are at the end of the line, indent the current line c-basic-offset columns from the opening bracket; otherwise you are looking at the first character of the first method call argument, so lineup the current line with it.

     Works with: objc-method-call-cont.

 -- Function: c-lineup-ObjC-method-args
     For Objective-C code, line up the colons that separate args.  The colon on the current line is aligned with the one on the first line.

     Works with: objc-method-args-cont.

 -- Function: c-lineup-ObjC-method-args-2
     Similar to c-lineup-ObjC-method-args but lines up the colon on the current line with the colon on the previous line.

     Works with: objc-method-args-cont.

 -- Function: c-lineup-runin-statements
     Line up statements for coding standards which place the first statement in a block on the same line as the block opening brace (Run-in style doesn't really work too well.  You might need to write your own custom indentation functions to better support this style.).  E.g:

          int main()
          { puts ("Hello!");
            return 0;           <- c-lineup-runin-statements
          }

     If there is no statement after the opening brace to align with, nil is returned.  This makes the function usable in list expressions.

     Works with: The statement syntactic symbol.

 -- Function: c-lineup-streamop
     Line up C++ stream operators (i.e., << and >>).

     Works with: stream-op.

 -- Function: c-lineup-string-cont
     Line up a continued string under the one it continues.  A continued string in this sense is where a string literal follows directly after another one.  E.g:

          result = prefix + "A message "
                            "string.";    <- c-lineup-string-cont

     nil is returned in other situations, to allow stacking with other lineup functions.

     Works with: topmost-intro-cont, statement-cont, arglist-cont, arglist-cont-nonempty.

 -- Function: c-lineup-template-args
     Line up the arguments of a template argument list under each other, but only in the case where the first argument is on the same line as the opening <.

     To allow this function to be used in a list expression, nil is returned if there's no template argument on the first line.

     Works with: template-args-cont.

 -- Function: c-lineup-topmost-intro-cont
     Line up declaration continuation lines zero or one indentation step (This function is mainly provided to mimic the behavior of CC Mode 5.28 and earlier where this case wasn't handled consistently so that those lines could be analyzed as either topmost-intro-cont or statement-cont.  It's used for topmost-intro-cont by default, but you might consider using + instead.).  For lines preceding a definition, zero is used.  For other lines, c-basic-offset is added to the indentation.  E.g:

          int
          neg (int i)           <- c-lineup-topmost-intro-cont
          {
              return -i;
          }

     and

          struct
          larch                 <- c-lineup-topmost-intro-cont
          {
              double height;
          }
              the_larch,        <- c-lineup-topmost-intro-cont
              another_larch;    <- c-lineup-topmost-intro-cont
          <--> c-basic-offset

     and

          struct larch
          the_larch,            <- c-lineup-topmost-intro-cont
              another_larch;    <- c-lineup-topmost-intro-cont

     Works with: topmost-intro-cont.

 -- Function: c-lineup-whitesmith-in-block
     Line up lines inside a block in Whitesmith style.  It's done in a way that works both when the opening brace hangs and when it doesn't.  E.g:

          something
              {
              foo;              <- c-lineup-whitesmith-in-block
              }

     and

          something {
              foo;              <- c-lineup-whitesmith-in-block
              }
          <--> c-basic-offset

     In the first case the indentation is kept unchanged, in the second c-basic-offset is added.

     Works with: defun-close, defun-block-intro, block-close, brace-list-close, brace-list-intro, statement-block-intro and all in* symbols, e.g., inclass and inextern-lang.

Status of AWK Mode
******************

AWK mode existed until recently in the file awk-mode.el as a mode derived from c-mode.  It had not been actively maintained to keep pace with the newer CC Mode, and its indentation mechanism no longer worked satisfactorally.

The current AWK mode is based around the GNU implementation, GAWK version 3.1.0, though it should work pretty well with any AWK.  It has now been updated and integrated into CC Mode to a substantial extent, though as yet not all the features of CC Mode have been adapted to support it.

If your (X)Emacs is set up to use the old file awk-mode.elc (which will usually be the case if you have obtained this CC Mode independently of (X)Emacs itself), or if you are not sure, insert the following form into your .emacs or init.el so that the new AWK mode will be used instead:

     (autoload 'awk-mode "cc-mode" nil t)

You can check which AWK mode you are running by displaying the mode documentation string with C-h m from an AWK buffer.  The newer mode's doc string contains To submit a problem report, enter `C-c C-b' near the top of the doc string where the older mode has This is much like C mode except .....

Since this newer AWK mode makes essential use of a relatively new Emacs Lisp feature (Specifically, the syntax-table text property.), you need either GNU Emacs 20.1 (or later) or XEmacs 21.4 (or later) to use it.  If your Emacs version is earlier than one of these, the older awk-mode.el will get loaded and run in place of the AWK mode described here, even when you have put the above autoload form into your .emacs or init.el. Upgrading your (X)Emacs is strongly recommended if this is the case.

Here is an overview of which CC Mode features currently work with AWK mode and which don't:

Indentation Engine
     The CC Mode indentation engine fully supports AWK mode. See Indentation Engine.

     AWK mode handles code formatted in the conventional AWK fashion: {s which start actions, user-defined functions, or compound statements are placed on the same line as the associated construct; the matching }s are normally placed under the start of the respective pattern, function definition, or structured statement.

     The predefined indentation functions (see Indentation Functions) haven't yet been adapted for AWK mode, though some of them may work serendipitously.  There shouldn't be any problems writing custom indentation functions for AWK mode.

     The command C-c C-q (c-indent-defun) hasn't yet been adapted for AWK, though in practice it works properly nearly all the time.  Should it fail, explicitly set the region around the function (using C-u C-SPC: C-M-h probably won't work either) then do C-M-\ (indent-region).

Font Locking
     There is a single level of font locking in AWK mode, rather than the three distinct levels the other modes have.  There are several idiosyncrasies in AWK mode's font-locking due to the peculiarities of the AWK language itself.  See AWK Mode Font Locking.

Comment Commands
     M-; (indent-for-comment) works fine.  None of the other CC Mode comment formatting commands have yet been adapted for AWK mode.  See Text Filling and Line Breaking.

Movement Commands
     Most of the movement commands work in AWK mode.  The most important exceptions are M-a (c-beginning-of-statement) and M-e (c-end-of-statement) which haven't yet been adapted.

     The notion of defun has been augmented to include pattern-action pairs.  See AWK Mode Defuns for a description of commands which work on AWK ``defuns''.

     Since there is no preprocessor in AWK, the commands which move to preprocessor directives (e.g., c-up-conditional) are meaningless in AWK mode and are not bound in the AWK mode keymap.

Auto-newline Insertion and Clean-ups
     Auto-newline insertion hasn't yet been adapted for AWK.  Some of the clean-ups can actually convert good AWK code into syntactically invalid code.

     If auto-newline or its associated clean-ups are enabled generally for the modes in CC Mode, you are strongly recommended to disable them in the AWK Mode hook.  See Initialising AWK Mode.

     The clean-up space-before-funcall, which is independent of auto-newline, should never be active in AWK mode (since inserting a space between a user function's name and its opening ( makes the call syntactically invalid).  If necessary, this should be disabled in the AWK Mode hook.  See Initialising AWK Mode.

AWK mode - What to put in your .emacs or init.el
================================================

Much of the AWK mode initialization can, of course, be done by the CC Mode general initialization procedure.  You may want to use certain CC Mode features such as auto-newline and clean-ups in the other modes, and you might thus have enabled them in a c-mode-common-hook function, as described in Sample .emacs File. These features have not yet been amended for AWK mode, and far from being useful, can be irritating in AWK mode or actually make AWK code syntactically invalid.  Adding the following code to your .emacs or init.el file will disable them for AWK mode.

     (defun my-awk-mode-hook ()
       "Disable certain CC Mode features which could impair AWK mode."
       (c-toggle-auto-state -1)       ; disable automatic insertions of newlines
       (if (memq 'space-before-funcall c-cleanup-list)
           (setq c-cleanup-list ; don't automatically insert a space into "foo("
                 (remove 'space-before-funcall c-cleanup-list))))
     (add-hook 'awk-mode-hook 'my-awk-mode-hook)

Naturally you can add your own AWK-specific customizations to this function.  See Hooks.

AWK Mode Font Locking
=====================

The general appearance of font-locking in AWK mode is much like in any other programming mode.  See Faces For Font Lock (elisp).

The following faces are, however, used in a non-standard fashion in AWK mode:

font-lock-variable-name-face
     This face was intended for variable declarations.  Since variables are not declared in AWK, this face is used instead for AWK system variables (such as NF) and ``Special File Names'' (such as "/dev/stderr").

font-lock-builtin-face (Emacs)/font-lock-preprocessor-face (XEmacs)
     This face is normally used for preprocessor directives in CC Mode. There are no such things in AWK, so this face is used instead for standard functions (such as match).

font-lock-string-face
     As well as being used for strings, including localizable strings, (delimited by " and _"), this face is also used for AWK regular expressions (delimited by /).

font-lock-warning-face (Emacs)/c-invalid-face (XEmacs)
     This face highlights the following syntactically invalid AWK constructs:

       * An unterminated string or regular expression.  Here the opening delimiter (" or / or _") is displayed in font-lock-warning-face.  This is most noticeable when typing in a new string/regular expression into a buffer, when the warning-face serves as a continual reminder to terminate the construct.

          AWK mode fontifies unterminated strings/regular expressions differently from other modes: Only the text up to the end of the line is fontified as a string (escaped newlines being handled correctly), rather than the text up to the next string quote.

       * A space between the function name and opening parenthesis when calling a user function.  The last character of the function name and the opening parenthesis are highlighted.  This font-locking rule will spuriously highlight a valid concatenation expression where an identifier precedes a parenthesised expression.  Unfortunately.

       * Whitespace following the \ in what otherwise looks like an escaped newline.  The \ is highlighted.

AWK Mode Defuns
===============

In AWK mode, defun means either a user-defined function or a pattern-action pair.  Either the pattern or the action may be implicit.

The beginning of a defun is recognised heuristically as, more or less, code which begins in column zero.  Having the { in column zero, as is suggested for some modes, is neither necessary nor helpful in AWK mode.

More precisely, the beginning of a defun is code which begins in column zero, and which isn't a closing brace, a comment, or a continuation of the previous line.  Code is the continuation of the previous line when that line is syntactically incomplete, for example when it ends with { or an escaped newline.

The end of a defun is the } which matches the { (if any) at the beginning of the action or function body, or the EOL or ; which marks an implicit action.  Although this } is usually placed in column zero, AWK mode doesn't need it to be placed there.

C-M-a c-awk-beginning-of-defun
C-M-e c-awk-end-of-defun
     Move point back to the beginning or forward to the end of the current AWK defun.  These functions can take prefix-arguments, their functionality being entirely equivalent to beginning-of-defun and end-of-defun.  See Moving by Defuns (emacs).

C-M-h c-mark-function
     This works fine with AWK defuns.  See Indentation Commands.

Odds and Ends
*************

The stuff that didn't fit in anywhere else is documented here.

 -- User Option: c-require-final-newline
     Controls whether a final newline is ensured when the file is saved.  The value is an association list that for each language mode specifies the value to give to require-final-newline at mode initialization; see that variable for details about the value.  If a language isn't present on the association list, CC Mode won't touch require-final-newline in buffers for that language.

     The default is to set require-final-newline to t in the languages that mandates that source files should end with newlines, i.e., C, C++ and Objective-C.

 -- User Option: c-echo-syntactic-information-p
     If non-nil, the syntactic analysis for the current line is shown in the echo area when it's indented (unless c-syntactic-indentation is nil).  That's useful when finding out which syntactic symbols to modify to get the indentation you want.

 -- User Option: c-report-syntactic-errors
     If non-nil, certain syntactic errors are reported with a ding and a message, for example when an else is indented for which there is no corresponding if.

     Note however that CC Mode doesn't make any special effort to check for syntactic errors; that's the job of the compiler.  The reason it can report cases like the one above is that it can't find the correct anchoring position to indent the line in that case.

Performance Issues
******************

C and its derivative languages are highly complex creatures.  Often, ambiguous code situations arise that require CC Mode to scan large portions of the buffer to determine syntactic context.  Such pathological code can cause CC Mode to perform fairly badly.  This section gives some insight in how CC Mode operates, how that interacts with some coding styles, and what you can use to improve performance.

The overall goal is that CC Mode shouldn't be overly slow (i.e., take more than a fraction of a second) in any interactive operation. i.e., it's tuned to limit the maximum response time in single operations, which sometimes is at the expense of batch-like operations like reindenting whole blocks.  If you find that CC Mode gradually gets slower and slower in certain situations, perhaps as the file grows in size or as the macro or comment you're editing gets bigger, then chances are that something isn't working right.  You should consider reporting it, unless it's something that's mentioned in this section.

Because CC Mode has to scan the buffer backwards from the current insertion point, and because C's syntax is fairly difficult to parse in the backwards direction, CC Mode often tries to find the nearest position higher up in the buffer from which to begin a forward scan (it's typically an opening or closing parethesis of some kind).  The farther this position is from the current insertion point, the slower it gets.

One of the simplest things you can do to reduce scan time, is make sure any brace that opens a top-level construct (e.g., a function in C, or outermost class definition in C++ or Java.) always appears in the leftmost column.  This is actually an Emacs constraint, as embodied in the beginning-of-defun function which CC Mode uses heavily.  If you hang top-level open braces on the right side of the line, then you might want to set the variable defun-prompt-regexp to something reasonable, however that ``something reasonable'' is difficult to define, so CC Mode doesn't do it for you.

A special note about defun-prompt-regexp in Java mode: The common style is to hang the opening braces of functions and classes on the right side of the line, and that doesn't work well with the Emacs approach.  CC Mode comes with a variable c-Java-defun-prompt-regexp which tries to define a regular expression usable for this style, but there are problems with it.  In some cases it can cause beginning-of-defun to hang (This has been observed in Emacs 19.34 and XEmacs 19.15.).  For this reason, it is not used by default, but if you feel adventurous, you can set defun-prompt-regexp to it in your mode hook.  In any event, setting and relying on defun-prompt-regexp will definitely slow things down because (X)Emacs will be doing regular expression searches a lot, so you'll probably be taking a hit either way!

CC Mode maintains a cache of the opening parentheses of the blocks surrounding the point, and it adapts that cache as the point is moved around.  That means that in bad cases it can take noticeable time to indent a line in a new surrounding, but after that it gets fast as long as the point isn't moved far off.  The farther the point is moved, the less useful is the cache.  Since editing typically is done in ``chunks'' rather than on single lines far apart from each other, the cache typically gives good performance even when the code doesn't fit the Emacs approach to finding the defun starts.

XEmacs users can set the variable c-enable-xemacs-performance-kludge-p to non-nil.  This tells CC Mode to use XEmacs-specific built-in functions which, in some circumstances, can locate the top-most opening brace much more quickly than beginning-of-defun.  Preliminary testing has shown that for styles where these braces are hung (e.g., most JDK-derived Java styles), this hack can improve performance of the core syntax parsing routines from 3 to 60 times.  However, for styles which do conform to Emacs' recommended style of putting top-level braces in column zero, this hack can degrade performance by about as much.  Thus this variable is set to nil by default, since the Emacs-friendly styles should be more common (and encouraged!).  Note that this variable has no effect in Emacs since the necessary built-in functions don't exist (in Emacs 21.3 as of this writing in May 2003).

Text properties are used to speed up skipping over syntactic whitespace, i.e., comments and preprocessor directives.  Indenting a line after a huge macro definition can be slow the first time, but after that the text properties are in place and it should be fast (even after you've edited other parts of the file and then moved back).

Font locking can be a CPU hog, especially the font locking done on decoration level 3 which tries to be very accurate.  Note that that level is designed to be used with a font lock support mode that only fontifies the text that's actually shown, i.e., Lazy Lock or Just-in-time Lock mode, so make sure you use one of them.  Fontification of a whole buffer with some thousand lines can often take over a minute.  That is a known weakness; the idea is that it never should happen.

The most effective way to speed up font locking is to reduce the decoration level to 2 by setting font-lock-maximum-decoration appropriately.  That level is designed to be as pretty as possible without sacrificing performance.  See Font Locking Preliminaries, for more info.

Limitations and Known Bugs
**************************

  * There is no way to apply auto newline settings (see Auto-newline Insertion) on already typed lines.  That's only a feature to ease interactive editing.

     To generalize this issue a bit: CC Mode is not intended to be used as a reformatter for old code in some more or less batch-like way.  With the exception of some functions like c-indent-region, it's only geared to be used interactively to edit new code.  There's currently no intention to change this goal.

     If you want to reformat old code, you're probably better off using some other tool instead, e.g., GNU indent (The `indent' Manual), which has more powerful reformatting capabilities than CC Mode.

  * XEmacs has a variable called signal-error-on-buffer-boundary. It's used as a solution to user interface problems associated with buffer movement and the zmacs-region deactivation on errors. However, setting this variable to a non-default value in XEmacs 19 and 20 had the deleterious side effect of breaking many built-in primitive functions.  Do not set this variable to nil in XEmacs
     19 and 20; you will cause serious problems in CC Mode and probably other XEmacs packages!  In XEmacs 21 the effects of the variable is limited to some functions that are only used interactively, so it's not a problem there.

Frequently Asked Questions
**************************

  * How do I reindent the whole file?

     Visit the file and hit C-x h to mark the whole buffer. Then hit C-M-\.

  * How do I reindent the current block?

     First move to the brace which opens the block with C-M-u, then reindent that expression with C-M-q.

  * Why doesn't the RET key indent the new line?

     Emacs' convention is that RET just adds a newline, and that C-j adds a newline and indents it.  You can make RET do this too by adding this to your c-mode-common-hook:

          (define-key c-mode-base-map "\C-m" 'c-context-line-break)

     This is a very common question.  If you want this to be the default behavior, don't lobby me, lobby RMS!  :-)

  * I put (c-set-offset 'substatement-open 0) in my .emacs file but I get an error saying that c-set-offset's function definition is void.  What's wrong?

     This means that CC Mode wasn't loaded into your Emacs session by the time the c-set-offset call was reached, most likely because CC Mode is being autoloaded.  Instead of putting the c-set-offset line in your top-level .emacs file, put it in your c-mode-common-hook, or simply modify c-offsets-alist directly:

          (setq c-offsets-alist '((substatement-open . 0)))

  * M-a and M-e used to move over entire balanced brace lists, but now they move into blocks.  How do I get the old behavior back?

     Use C-M-f and C-M-b to move over balanced brace blocks.  Use M-a and M-e to move by statements, which will also move into blocks.

  * Whenever I try to indent a line or type an ``electric'' key such as ;, {, or }, I get an error that look like this: Invalid function: (macro . #[.... What gives?

     This is a common error when CC Mode hasn't been compiled correctly, especially under Emacs 19.34 (Technically, it's because some macro wasn't defined during the compilation, so the byte compiler put in function calls instead of the macro expansions. Later, when the interpreter tries to call the macro as a function, it shows this (somewhat cryptic) error message.). If you are using the standalone CC Mode distribution, try recompiling it according to the instructions in the README file.

  * I have an open paren character at column zero inside a comment or multiline string literal, and it causes the fontification and/or indentation to go haywire.  What gives?

     It's due to the ad-hoc rule in (X)Emacs that such open parens always start defuns (which translates to functions, classes, namespaces or any other top-level block constructs in the CC Mode languages). See Left Margin Paren (The Emacs Editor), for details (see Defuns (The Emacs Editor), in the Emacs 20 manual).

     This heuristic is built into the core syntax analysis routines in (X)Emacs, so it's not really a CC Mode issue.  However, in Emacs 22.1 it has become possible to turn it off (Using the variable
     open-paren-in-column-0-is-defun-start.) and CC Mode does so there since it got its own system to keep track of blocks.

Getting the Latest CC Mode Release
**********************************

CC Mode has been standard with all versions of Emacs since 19.34 and of XEmacs since 19.16.

Due to release schedule skew, it is likely that all of these Emacsen have old versions of CC Mode and so should be upgraded.  Access to the CC Mode source code, as well as more detailed information on Emacsen compatibility, etc. are all available on the web site:

     http://cc-mode.sourceforge.net/

Mailing Lists and Submitting Bug Reports
****************************************

To report bugs, use the C-c C-b (bound to c-submit-bug-report) command.  This provides vital information we need to reproduce your problem.  Make sure you include a concise, but complete code example.  Please try to boil your example down to just the essential code needed to reproduce the problem, and include an exact recipe of steps needed to expose the bug.  Be especially sure to include any code that appears before your bug example, if you think it might affect our ability to reproduce it.

Please try to produce the problem in an Emacs instance without any customizations loaded (i.e., start it with the -q --no-site-file arguments).  If it works correctly there, the problem might be caused by faulty customizations in either your own or your site configuration.  In that case, we'd appreciate if you isolate the Emacs Lisp code that trigs the bug and include it in your report.

Bug reports are sent to bug-cc-mode@gnu.org.  You can also send other questions and suggestions (kudos? ;-) to that address.  It's a mailing list which you can join or browse an archive of; see the web site at http://cc-mode.sourceforge.net/ for further details.

If you want to get announcements of new CC Mode releases, send the word subscribe in the body of a message to cc-mode-announce-request@lists.sourceforge.net.  It's possible to subscribe from the web site too.  Announcements will also be posted to the Usenet newsgroups gnu.emacs.sources, comp.emacs and comp.emacs.xemacs.

Sample .emacs file
******************

     ;; Here's a sample .emacs file that might help you along the way.
     ;; Just copy this region and paste it into your .emacs file.  You may
     ;; want to change some of the actual values.

     (defconst my-c-style
       '((c-tab-always-indent        . t)
         (c-comment-only-line-offset . 4)
         (c-hanging-braces-alist     . ((substatement-open after)
                                        (brace-list-open)))
         (c-hanging-colons-alist     . ((member-init-intro before)
                                        (inher-intro)
                                        (case-label after)
                                        (label after)
                                        (access-label after)))
         (c-cleanup-list             . (scope-operator
                                        empty-defun-braces
                                        defun-close-semi))
         (c-offsets-alist            . ((arglist-close . c-lineup-arglist)
                                        (substatement-open . 0)
                                        (case-label        . 4)
                                        (block-open        . 0)
                                        (knr-argdecl-intro . -)))
         (c-echo-syntactic-information-p . t))
       "My C Programming Style")

     ;; offset customizations not in my-c-style
     (setq c-offsets-alist '((member-init-intro . ++)))

     ;; Customizations for all modes in CC Mode.
     (defun my-c-mode-common-hook ()
       ;; add my personal style and set it for the current buffer
       (c-add-style "PERSONAL" my-c-style t)
       ;; other customizations
       (setq tab-width 8
             ;; this will make sure spaces are used instead of tabs
             indent-tabs-mode nil)
       ;; we like auto-newline and hungry-delete
       (c-toggle-auto-hungry-state 1)
       ;; key bindings for all supported languages.  We can put these in
       ;; c-mode-base-map because c-mode-map, c++-mode-map, objc-mode-map,
       ;; java-mode-map, idl-mode-map, and pike-mode-map inherit from it.
       (define-key c-mode-base-map "\C-m" 'c-context-line-break))

     (add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

Command and Function Index
**************************

Since most CC Mode commands are prepended with the string c-, each appears under its c-THING name and its THING (c-) name.

Variable Index
**************

Since most CC Mode variables are prepended with the string c-, each appears under its c-THING name and its THING (c-) name.