ccmode-2   [plain text]


This is ../info/ccmode, produced by makeinfo version 4.0 from
cc-mode.texi.

INFO-DIR-SECTION Emacs
START-INFO-DIR-ENTRY
* CC Mode: (ccmode).   Emacs mode for editing C, C++, Objective-C,
                          Java, Pike, and IDL code.
END-INFO-DIR-ENTRY

   Copyright (C) 1995, 96, 97, 98, 99, 2000, 2001 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.


File: ccmode,  Node: Movement Commands,  Next: Other Commands,  Prev: Indentation Commands,  Up: Commands

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

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

`M-x c-beginning-of-defun'
     Moves 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.

`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
     `beginning-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.

`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 `M-C-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 `M-C-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.


File: ccmode,  Node: Other Commands,  Prev: Movement Commands,  Up: Commands

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

   CC Mode contains a few other useful commands:

`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.

`C-c C-\' (`c-backslash-region')
     This function is handy when editing macros split over several
     lines by ending each line with a backslash.  It inserts and
     aligns, or deletes these end-of-line backslashes in the current
     region.

     With no prefix argument, it inserts any missing backslashes and
     aligns them to the column specified by the `c-backslash-column'
     style variable.  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.


File: ccmode,  Node: Customizing Indentation,  Next: Syntactic Symbols,  Prev: Commands,  Up: Top

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

   The style variable `c-offsets-alist' 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 pre-defined styles will suit
your needs.  *Note 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(1) 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.

   You can use the command `C-c C-o' (`c-set-offset') as the way to set
offsets, both interactively and from your mode hook(2).

   The offset associated with any particular syntactic symbol can be
any of an integer, a function or lambda expression, a variable name, a
vector, a list, or one of the following symbols: `+', `-', `++', `--',
`*', or `/'.

   Those last special symbols describe an offset in multiples of the
value of the style variable `c-basic-offset'.  By defining a style's
indentation in terms of this fundamental variable, 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.  *Note
Indentation Functions::, and *Note 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 relative indentation.

   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(3).

   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(4):

     _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.

* Menu:

* Interactive Customization::
* Permanent Customization::
* Hooks::
* Styles::
* Advanced Customizations::

   ---------- Footnotes ----------

   (1) Available in Emacs 20 and later, and XEmacs 19.15 and later.

   (2) Obviously, you use the key binding interactively, and the
function call programmatically!

   (3) There is however a variable `c-strict-syntax-p' that, when set
to non-`nil', will cause an error to be signalled 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'.

   (4) You can try this interactively in a C buffer by typing the text
that appears in italics.


File: ccmode,  Node: Interactive Customization,  Next: Permanent Customization,  Up: Customizing Indentation

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

   As an example of how to customize indentation, let's change the
style of this example(1):

     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 re-indent and see if any following lines need further
adjustments.

   ---------- Footnotes ----------

   (1) In this an subsequent examples, the original code is formatted
using the `gnu' style unless otherwise indicated.  *Note Styles::.


File: ccmode,  Node: Permanent Customization,  Next: Hooks,  Prev: Interactive Customization,  Up: Customizing Indentation

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 the setting of `substatement-open' permanent, add this to the
`.emacs' file:

     (require 'cc-mode)
     (c-set-offset 'substatement-open 0)

   The `require' line is only needed once in the beginning to make sure
CC Mode is loaded so that the `c-set-offset' function is defined.

   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-basic-offset', that you don't set this way
get their value from the style system (*note 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, global variable settings isn't enough.
For that you can use the language hooks, see *Note Hooks::, and/or the
style system, see *Note Styles::.

   By default, all style variables are global, so that every buffer will
share the same style settings.  This is fine if you primarily edit one
style of code, but if you edit several languages and want to use
different styles for them, you need finer control by making the style
variables buffer local.  The recommended way to do this is to set the
variable `c-style-variables-are-local-p' to `t'.  The variables will be
made buffer local when CC Mode is activated in a buffer for the first
time in the Emacs session.  Note that once the style variables are made
buffer local, they cannot be made global again, without restarting
Emacs.


File: ccmode,  Node: Hooks,  Next: Styles,  Prev: Permanent Customization,  Up: Customizing Indentation

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:

   * `c-mode-hook' -- For C buffers only.

   * `c++-mode-hook' -- For C++ buffers only.

   * `objc-mode-hook' -- For Objective-C buffers only.

   * `java-mode-hook' -- For Java buffers only.

   * `idl-mode-hook' -- For CORBA IDL buffers only.

   * `pike-mode-hook' -- For Pike buffers only.

   * `c-mode-common-hook' -- Common across all languages.

   * `c-initialization-hook' -- Hook run only once per Emacs session,
     when CC Mode is initialized.


   The language hooks get run as the last thing when you enter that
language mode.  The `c-mode-common-hook' is run by all supported modes
_before_ the language specific hook, and thus can contain
customizations that are common across all languages.  Most of the
examples in this section will assume you are using the common hook.

   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.
*Note 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)


File: ccmode,  Node: Styles,  Next: Advanced Customizations,  Prev: Hooks,  Up: Customizing Indentation

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 global variables, i.e. they have
     the same value in all Emacs buffers.  However, they can instead be
     made always buffer local by setting
     `c-style-variables-are-local-p' to non-`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(1).

     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(2).

   * The global settings of style variables get captured in the special
     `user' style, which is used as the base for all the other styles.
     *Note 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-special-indent-hook',
`c-label-minimum-indentation', and `c-offsets-alist'.

* Menu:

* Built-in Styles::
* Adding Styles::
* File Styles::

   ---------- Footnotes ----------

   (1) 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'.

   (2) This did not change in version 5.26.


File: ccmode,  Node: Built-in Styles,  Next: Adding Styles,  Up: Styles

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(1).

   * `linux' -- C coding standard for Linux (the kernel).

   * `python' -- C coding standard for Python extension modules(2).

   * `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' (*note
     Adding Styles::) you need only define the differences between your
     new style and `user' style.


   The default style in all newly created buffers is `gnu', but you can
change this by setting variable `c-default-style'.  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 these settings.

   `c-default-style' takes either a style name string, or an
association list of major mode symbols to style names.  Thus you can
control exactly which default style is used for which CC Mode language
mode.  Here are the rules:

  1. When `c-default-style' is a string, it must be an existing style
     name as found in `c-style-alist'.  This style is then used for all
     modes.

  2. When `c-default-style' is an association list, the current major
     mode is looked up to find a style name string.  In this case, this
     style is always used exactly as specified and an error will occur
     if the named style does not exist.

  3. If `c-default-style' is an association list, but the current major
     mode isn't found, then the special symbol `other' is looked up.  If
     this value is found, 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'.


   If you'd like to experiment with these built-in styles you can simply
type the following in a CC Mode buffer:

     C-c . STYLE-NAME RET

`C-c .' runs the command `c-set-style'.  Note that all style names are
case insensitive, even the ones you define.

   Setting a style in this way does _not_ automatically re-indent your
file.  For commands that you can use to view the effect of your changes,
see *Note Commands::.

   Note that for BOCM compatibility, `gnu' is the default style, and
any non-style based customizations you make (i.e. in
`c-mode-common-hook' in your `.emacs' file) will be based on `gnu'
style unless you set `c-default-style' or do a `c-set-style' as the
first thing in your hook.  The variable `c-indentation-style' always
contains the buffer's current style name, as a string.

   ---------- Footnotes ----------

   (1) This document is available at
`http://www.doc.ic.ac.uk/lab/cplus/c++.rules/' among other places.

   (2) Python is a high level scripting language with a C/C++ foreign
function interface.  For more information, see `http://www.python.org/'.


File: ccmode,  Node: Adding Styles,  Next: File Styles,  Prev: Built-in Styles,  Up: Styles

Adding Styles
-------------

   If none of the built-in styles is appropriate, you'll probably want
to add a new "style definition".  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' that
you can use to easily add new styles or change existing styles.  This
function takes two arguments, a STYLENAME string, and an association
list DESCRIPTION of style customizations.  If STYLENAME is not already
in `c-style-alist', the new style is added, otherwise the style is
changed to the new DESCRIPTION.  This function also takes an optional
third argument, which if non-`nil', automatically applies the new style
to the current buffer.

   The sample `.emacs' file provides a concrete example of how a new
style can be added and automatically set.  *Note Sample .emacs File::.


File: ccmode,  Node: File Styles,  Prev: Adding Styles,  Up: Styles

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

   The Emacs manual describes how you can customize certain variables
on a per-file basis by including a "Local Variable" block at the end of
the file.  So far, you've only seen a functional interface to CC Mode
customization, which is highly inconvenient for use in a Local Variable
block.  CC Mode provides two variables that make it easier for you to
customize your style on a per-file basis.

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

   Another variable, `c-file-offsets', 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.


File: ccmode,  Node: Advanced Customizations,  Prev: Styles,  Up: Customizing Indentation

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 defined in `c-style-alist' 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.

* Menu:

* Custom Indentation Functions::
* Custom Brace and Colon Hanging::
* Customizing Semi-colons and Commas::
* Other Special Indentations::


File: ccmode,  Node: Custom Indentation Functions,  Next: Custom Brace and Colon Hanging,  Up: Advanced Customizations

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

   The most flexible way to customize CC Mode is by writing custom
indentation functions, and associating them with specific syntactic
symbols (*note 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 first stream operator on
the first line of the statement.  Here is sample lisp code implementing
this:

     (defun c-lineup-streamop (langelem)
       ;; lineup stream operators
       (save-excursion
         (let* ((relpos (cdr langelem))
                (curcol (progn (goto-char relpos)
                               (current-column))))
           (re-search-forward "<<\\|>>" (c-point 'eol) 'move)
           (goto-char (match-beginning 0))
           (- (current-column) curcol))))

Indentation functions take a single argument, which is a syntactic
component cons cell (*note Syntactic Analysis::).  The function returns
an integer offset value that will be added to the running total
indentation for the line.  Note that what actually gets returned is the
difference between the column that the first stream operator is on, and
the column of the buffer relative position passed in the function's
argument.  Remember that CC Mode automatically adds in the column of
the component's relative buffer position and we don't the column offset
added in twice.

   The function should return `nil' if it's used in a situation where
it doesn't want to do any decision.  If the function is used in a list
expression (*note 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'(1):

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

   Now the function looks like this after re-indenting (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.  *Note 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>.

   ---------- Footnotes ----------

   (1) 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++.


File: ccmode,  Node: Custom Brace and Colon Hanging,  Next: Customizing Semi-colons and Commas,  Prev: Custom Indentation Functions,  Up: Advanced Customizations

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' (*note 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.
     Using this function, `while' clauses that end a `do-while' block will
     remain on the same line as the brace that closes that block.
     
     See `c-hanging-braces-alist' for how to utilize this function as an
     ACTION associated with `block-close' syntax."
       (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.

   During the call to the brace hanging ACTION function, the variable
`c-syntactic-context' 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-colon-alist'
style variable.  Since no use has actually been found for this feature,
it isn't currently implemented!


File: ccmode,  Node: Customizing Semi-colons and Commas,  Next: Other Special Indentations,  Prev: Custom Brace and Colon Hanging,  Up: Advanced Customizations

Customizing Semi-colons and Commas
----------------------------------

   You can also customize the insertion of newlines after semi-colons
and commas, when the auto-newline minor mode is enabled (*note Minor
Modes::).  This is controlled by the style variable
`c-hanging-semi&comma-criteria', which contains a list of functions
that are called in the order they appear.  Each function is called with
zero arguments, and is expected to return one of the following values:

   * non-`nil' -- 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
semi-colons which do not appear inside parenthesis lists (i.e. those
that separate `for'-clause statements).

   Here's an example of a criteria function, provided by CC Mode, that
will prevent newlines from being inserted after semicolons when there is
a non-blank following line.  Otherwise, it makes no determination.  To
use, add this 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)))

   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
(i.e. in C++ or Java).


File: ccmode,  Node: Other Special Indentations,  Prev: Customizing Semi-colons and Commas,  Up: Advanced Customizations

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

   In `gnu' style (*note Built-in Styles::), a minimum indentation is
imposed on lines inside top-level constructs.  This minimum indentation
is controlled by the style variable `c-label-minimum-indentation'.  The
default value for this variable is 1.

   One other customization variable is available in CC Mode: The style
variable `c-special-indent-hook'.  This 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 however, 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.

   Normally, the standard Emacs command `M-;' (`indent-for-comment')
will indent comment only lines to `comment-column'.  Some users
however, prefer that `M-;' act just like `TAB' for purposes of
indenting comment-only lines; i.e. they want the comments to always
indent as they would for normal code, regardless of whether `TAB' or
`M-;' were used.  This behavior is controlled by the variable
`c-indent-comments-syntactically-p'.  When `nil' (the default), `M-;'
indents comment-only lines to `comment-column', otherwise, they are
indented just as they would be if `TAB' were typed.

   Note that this has no effect for comment lines that are inserted with
`M-;' at the end of regular code lines.  These comments will always
start at `comment-column'.