[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11. Customizing Indentation

The principal variable for customizing indentation is the style variable c-offsets-alist, which gives an offset (an indentation rule) for each syntactic symbol. Its structure and semantics are completely described in c-offsets-alist. The various ways you can set the variable, including the use of the CC Mode style system, are described in Configuration Basics and its sections, in particular Style Variables.

The simplest and most used kind of “offset” setting in c-offsets-alist is in terms of multiples of c-basic-offset:

User Option: c-basic-offset

This style variable holds the basic offset between indentation levels. It’s factory default is 4, but all the built-in styles set it themselves, to some value between 2 (for gnu style) and 8 (for bsd, linux, and python styles).

The most flexible “offset” setting you can make in c-offsets-alist is a line-up function (or even a list of them), either one supplied by CC Mode (see section Line-Up Functions) or one you write yourself (see section Custom Line-Up Functions).

Finally, in Other Special Indentations you’ll find the tool of last resort: a hook which is called after a line has been indented. You can install functions here to make ad-hoc adjustments to any line’s indentation.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.1 c-offsets-alist

This section explains the structure and semantics of the style variable c-offsets-alist, the principal variable for configuring indentation. Details of how to set it up, and its relationship to CC Mode’s style system are given in Style Variables.

User Option: c-offsets-alist

This is an alist which associates an offset with each syntactic symbol. This offset is a rule specifying how to indent a line whose syntactic context matches the symbol. See section Syntactic Analysis.

Note that the buffer-local binding of this alist in a CC Mode buffer contains an entry for every syntactic symbol. Its global binding and its settings within style specifications usually contain only a few entries. See section Style Variables.

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

Here is an example fragment of a c-offsets-alist, showing some of these kinds of offsets:

 
((statement . 0)
 (substatement . +)
 (cpp-macro . [0])
 (topmost-intro-cont . c-lineup-topmost-intro-cont)
 (statement-block-intro . (add c-lineup-whitesmith-in-block
                               c-indent-multi-line-block))
 …

)
Command: c-set-offset (C-c C-o)

This command changes the entry for a syntactic symbol in the current binding of c-offsets-alist, or it inserts a new entry if there isn’t already one for that syntactic symbol.

You can use c-set-offset interactively within a CC Mode buffer to make experimental changes to your indentation settings. C-c C-o prompts you for the syntactic symbol to change (defaulting to that of the current line) and the new offset (defaulting to the current offset).

c-set-offset takes two arguments when used programmatically: symbol, the syntactic element symbol to change and offset, the new offset for that syntactic element. You can call the command in your ‘.emacs’ to change the global binding of c-offsets-alist (see section Style Variables); you can use it in a hook function to make changes from the current style. CC Mode itself uses this function when initializing styles.

The “offset specifications” in c-offsets-alist can be any of the following:

An integer

The integer specifies a relative offset. All relative offsets(46) will be added together and used to calculate the indentation relative to an anchor position earlier in the buffer. See section Indentation Calculation, for details. Most of the time, it’s probably better to use one of the special symbols like + than an integer (apart from zero).

One of the symbols +, -, ++, --, *, or /

These special symbols describe a relative offset in multiples of c-basic-offset:

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

A vector

The first element of the vector, an integer, sets the absolute indentation column. This will override any previously calculated indentation, but won’t override relative indentation calculated from syntactic elements later on in the syntactic context of the line being indented. See section Indentation Calculation. Any elements in the vector beyond the first will be ignored.

A function or lambda expression

The function will be called and its return value will in turn be evaluated as an offset specification. Functions are useful when more context than just the syntactic symbol is needed to get the desired indentation. See section Line-Up Functions, and Custom Line-Up Functions, for details about them.

Another syntactic symbol

The offset of that other syntactic symbol will be used. This is useful for making sure that two distinct syntactic symbols cause the same indentation. By default, enum-open has the value class-open.

A symbol with a variable binding

If the symbol also has a function binding, the function takes precedence over the variable. Otherwise the value of the variable is used. It must be an integer (which is used as relative offset) or a vector (an absolute offset).

A list

The offset can also be a list containing several offset specifications; these are evaluated recursively and combined. A list is typically only useful when some of the offsets are line-up functions. A common strategy is calling a sequence of functions in turn until one of them recognizes that it is appropriate for the source line and returns a non-nil value.

nil values are always ignored when the offsets are combined. The first element of the list specifies the method of combining the non-nil offsets from the remaining elements:

first

Use the first offset that doesn’t evaluate to nil. Subsequent elements of the list don’t get evaluated.

min

Use the minimum of all the offsets. All must be either relative or absolute - they can’t be mixed.

max

Use the maximum of all the offsets. All must be either relative or absolute - they can’t be mixed.

add

Add all the evaluated offsets together. Exactly one of them may be absolute, in which case the result is absolute. Any relative offsets that preceded the absolute one in the list will be ignored in that case.

As a compatibility measure, if the first element is none of the above then it too will be taken as an offset specification and the whole list will be combined according to the method first.

If an offset specification evaluates to nil, then a relative offset of 0 (zero) is used(47).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.2 Interactive Customization

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

 
 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 symbols 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 might 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.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3 Line-Up Functions

Often there are cases when a simple offset setting on a syntactic symbol isn’t enough to get the desired indentation—for example, you might want to line up a closing parenthesis with the matching opening one rather than indenting relative to its “anchor point”. CC Mode provides this flexibility with line-up functions.

The way you associate a line-up function with a syntactic symbol is described in c-offsets-alist. CC Mode comes with many predefined line-up functions for common situations. If none of these does what you want, you can write your own. See section Custom Line-Up Functions. Sometimes, it is easier to tweak the standard indentation by adding a function to c-special-indent-hook (see section Other Special Indentations).

The line-up functions haven’t been adapted for AWK buffers or tested with them. Some of them might work serendipitously. There shouldn’t be any problems writing custom line-up functions for AWK mode.

The calling convention for line-up functions is described fully in Custom Line-Up Functions. Roughly speaking, the return value is either an offset itself (such as + or [0]), another line-up function, or it’s nil, meaning “this function is inappropriate in this case - try a different one”. See section c-offsets-alist.

The subsections below describe all the standard line-up functions, categorized by the sort of token the lining-up centers around. For each of these functions there is a “works with” list that indicates which syntactic symbols the function is intended to be used with.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3.1 Brace and Parenthesis Line-Up Functions

The line-up functions here calculate the indentation for braces, parentheses and statements within brace blocks.

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-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, enum-close, arglist-cont and arglist-cont-nonempty.

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-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(49). 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-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-after-whitesmith-blocks

Compensate for Whitesmith style indentation of blocks. Due to the way CC Mode calculates anchor positions for normal lines inside blocks, this function is necessary for those lines to get correct Whitesmith style indentation. Consider the following examples:

 
int foo()
    {
    a;
    x;                 <- c-lineup-after-whitesmith-blocks
 
int foo()
    {
        {
        a;
        }
    x;                 <- c-lineup-after-whitesmith-blocks

The fact that the line with x is preceded by a Whitesmith style indented block in the latter case and not the first should not affect its indentation. But since CC Mode in cases like this uses the indentation of the preceding statement as anchor position, the x would in the second case be indented too much if the offset for statement was set simply to zero.

This lineup function corrects for this situation by detecting if the anchor position is at an open paren character. In that case, it instead indents relative to the surrounding block just like c-lineup-whitesmith-in-block.

Works with:  brace-list-entry, brace-entry-open, enum-entry, statement, arglist-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, inline-close, block-close, brace-list-close, brace-list-intro, enum-close, enum-intro, statement-block-intro, arglist-intro, arglist-cont-nonempty, arglist-close, and all in* symbols, e.g. inclass and inextern-lang.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3.2 List Line-Up Functions

The line-up functions here calculate the indentation for lines which form lists of items, usually separated by commas.

The function c-lineup-arglist-close-under-paren, which is mainly for indenting a close parenthesis, is also useful for the lines contained within parentheses.

Function: c-lineup-arglist

Line up the current argument line under the first argument.

If there are any comments at the start of the line, this function will attempt to line up the argument correctly, with the comment appearing to the left of that 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 contain 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-cont

Line up an arglist-cont line under the previous argument.

If there are any comments at the start of the line, this function will attempt to line up the argument correctly, with the comment appearing to the left of that argument.

 
int foobar (
    /* a */ int a,
  /* baz */ int b,              <- c-lineup-arglist-cont
            /* empty */         <- c-lineup-arglist-cont
            int c);             <- c-lineup-arglist-cont

Works with:  arglist-cont.

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, enum-intro, statement-block-intro, statement-case-intro, arglist-intro.

Function: c-lineup-2nd-brace-entry-in-arglist

Line up the second entry of a brace block under the first, when the first line is also contained in an arglist or an enclosing brace on that line.

I.e. handle something like the following:

 
set_line (line_t {point_t{0.4, 0.2},
                  point_t{0.2, 0.5},       <- brace-list-intro
                  .....});
         ^ enclosing parenthesis.

The middle line of that example will have a syntactic context with three syntactic symbols, arglist-cont-nonempty, brace-list-intro, and brace-list-entry (see section Brace List Symbols).

This function is intended for use in a list. If the construct being analyzed isn’t like the preceding, the function returns nil. Otherwise it returns the function c-lineup-arglist-intro-after-paren, which the caller then uses to perform indentation.

Works with:  brace-list-intro.

Function: c-lineup-item-after-paren-at-boi

Line up under the first entry on the same line as an open parenthesis when that parenthesis is the lefmost non-space character in its line. For example:

 
template <typename T>
requires
    ( requires (T t) { ++t; }
      && Baz<T>)      <- constraint-cont
int foo();

This function is intended for use in a list. If the construct being analyzed doesn’t conform to the above description, the function returns nil. Otherwise it returns a vector containing the indentation.

Works with:  brace-list-intro, enum-intro, constraint-cont.

Function: c-lineup-class-decl-init-+

Line up the second entry of a class (etc.) initializer c-basic-offset characters in from the identifier when:

  1. The type is a class, struct, union, etc. (but not an enum);
  2. There is a brace block in the type declaration, specifying it; and
  3. The first element of the initializer is on the same line as its opening brace.

I.e. we have a construct like this:

 
struct STR {
    int i; float f;
} str_1 = {1, 1.7},
    str_2 = {2,
         3.1          <- brace-list-intro
    };
    <--> c-basic-offset

Note that the syntactic context of the brace-list-intro line also has a syntactic element with the symbol brace-list-entry (see section Brace List Symbols).

This function is intended for use in a list. If the above structure isn’t present, the function returns nil, allowing a different offset specification to indent the line.

Works with:  brace-list-intro.

Function: c-lineup-class-decl-init-after-brace

Line up the second entry of a class (etc.) initializer after its opening brace when:

  1. The type is a class, struct, union, etc. (but not an enum);
  2. There is a brace block in the type declaration, specifying it; and
  3. The first element of the initializer is on the same line as its opening brace.

I.e. we have a construct like this:

 
struct STR {
    int i; float f;
} str_1 = {1, 1.7},
    str_2 = {2,
             3.1      <- brace-list-intro
    };

Note that the syntactic context of the brace-list-intro line also has a syntactic element with the symbol brace-list-entry (see section Brace List Symbols). Also note that this function works by returning the symbol c-lineup-arglist-intro-after-paren, which the caller then uses to perform the indentation.

This function is intended for use in a list. If the above structure isn’t present, the function returns nil, allowing a different offset specification to indent the line.

Works with:  brace-list-intro.

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-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-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-template-args-indented-from-margin

Indent a template argument line ‘c-basic-offset’ from the left-hand margin of the line with the containing <.

Works with:  template-args-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.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3.3 Operator Line-Up Functions

The line-up functions here calculate the indentation for lines which start with an operator, by lining it up with something on the previous line.

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 recognized 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-argcont-+

Indent a continued argument c-basic-offset spaces from the start of the first argument at the current level of nesting on a previous line.

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

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

Within a gcc asm block, : is recognized 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-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 line-up 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-assignments

Line up the current line after the assignment operator on the first line in the statement. If there isn’t any, return nil to allow stacking with other line-up functions. If the current line contains an assignment operator too, try to align it with the first one.

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

Function: c-lineup-math

Like c-lineup-assignments but indent with c-basic-offset if no assignment operator was found on the first line. I.e. this function is the same as specifying a list (c-lineup-assignments +). It’s provided for compatibility with old configurations.

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

Function: c-lineup-ternary-bodies

Line up true and false branches of a ternary operator (i.e. ?:). More precisely, if the line starts with a colon which is a part of a said operator, align it with the corresponding question mark. For example:

 
return arg % 2 == 0 ? arg / 2
                    : (3 * arg + 1);    <- c-lineup-ternary-bodies

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

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


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3.4 Comment Line-Up Functions

The lineup functions here calculate the indentation for several types of comment structure.

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


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.3.5 Miscellaneous Line-Up Functions

The line-up functions here are the odds and ends which didn’t fit into any earlier category.

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-under-anchor

Line up a line directly underneath its anchor point. This is like ‘0’, except any previously calculated offset contributions are disregarded.

Works with:  Any syntactic symbol which has an anchor point.

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-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-topmost-intro-cont

Line up declaration continuation lines zero or one indentation step(50). 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-class-field-cont

Indent continutation lines zero or one c-basic-offset steps. This is intended for continuation lines within a class/struct etc. construct. For a declaration following a template specification, zero steps are used. Other constructs are indented one step.

Works with:  class-field-cont.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.4 Custom Line-Up Functions

The most flexible way to customize indentation is by writing custom line-up functions, and associating them with specific syntactic symbols (see section c-offsets-alist). Depending on the effect you want, it might be better to write a c-special-indent-hook function rather than a line-up function (see section Other Special Indentations).

CC Mode comes with an extensive set of predefined line-up functions, not all of which are used by the default styles. So there’s a good chance the function you want already exists. See section Line-Up Functions, for a list of them. If you write your own line-up function, it’s probably a good idea to start working from one of these predefined functions, which can be found in the file ‘cc-align.el’. If you have written a line-up function that you think is generally useful, you’re very welcome to contribute it; please contact bug-cc-mode@gnu.org.

Line-up functions are passed a single argument, the syntactic element (see below). At the time of the call, point will be somewhere on the line being indented. The return value is a c-offsets-alist offset specification: for example, an integer, a symbol such as +, a vector, nil(51), or even another line-up function. Full details of these are in c-offsets-alist.

Line-up functions must not move point or change the content of the buffer (except temporarily). They are however allowed to do hidden buffer changes, i.e. setting text properties for caching purposes etc. Buffer undo recording is disabled while they run.

The syntactic element passed as the parameter to a line-up function is a cons cell of the form

 
(syntactic-symbol . anchor-position)

where syntactic-symbol is the symbol that the function was called for, and anchor-position is the anchor position (if any) for the construct that triggered the syntactic symbol (see section Syntactic Analysis). This cons cell is how the syntactic element of a line used to be represented in CC Mode 5.28 and earlier. Line-up functions are still passed this cons cell, so as to preserve compatibility with older configurations. In the future, we may decide to convert to using the full list format—you can prepare your setup for this by using the access functions (c-langelem-sym, etc.) described below.

Some syntactic symbols, e.g. arglist-cont-nonempty, have more info in the syntactic element - typically other positions that can be interesting besides the anchor position. That info can’t be accessed through the passed argument, which is a cons cell. Instead, you can get this information from the variable c-syntactic-element, which is dynamically bound to the complete syntactic element. The variable c-syntactic-context might also be useful - it gets dynamically bound to the complete syntactic context. See section Custom Brace Hanging.

CC Mode provides a few functions to access parts of syntactic elements in a more abstract way. Besides making the code easier to read, they also hide the difference between the old cons cell form used in the line-up function argument and the new list form used in c-syntactic-element and everywhere else. The functions are:

Function: c-langelem-sym langelem

Return the syntactic symbol in langelem.

Function: c-langelem-pos langelem

Return the anchor position in langelem, or nil if there is none.

Function: c-langelem-col langelem &optional preserve-point

Return the column of the anchor position in langelem. Also move the point to that position unless preserve-point is non-nil.

Function: c-langelem-2nd-pos langelem

Return the secondary position in langelem, or nil if there is none.

Note that the return value of this function is always nil if langelem is in the old cons cell form. Thus this function is only meaningful when used on syntactic elements taken from c-syntactic-element or c-syntactic-context.

Sometimes you may need to use the syntactic context of a line other than the one being indented. You can determine this by (temporarily) moving point onto this line and calling c-guess-basic-syntax (see section Syntactic Analysis).

Custom line-up 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 line-up function associated with it.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

11.5 Other Special Indentations

To configure macros which you invoke without a terminating ‘;’, see See section Macros with semicolons.

Here are the remaining odds and ends regarding indentation:

User Option: c-label-minimum-indentation

In ‘gnu’ style (see section Built-in Styles), a minimum indentation is imposed on lines inside code blocks. This minimum indentation is controlled by this style variable. The default value is 1.

It’s the function c-gnu-impose-minimum that enforces this minimum indentation. It must be present on c-special-indent-hook to work.

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. It is called only if c-syntactic-indentation is non-nil (which it is by default (see section Indentation Engine Basics)). You can put a function on this hook to do any special indentation or ad hoc line adjustments your style dictates, such as adding extra indentation to constructors or destructor declarations in a class definition, etc. Sometimes it is better to write a custom Line-up Function instead (see section Custom Line-Up Functions).

The indentation engine calls each function on this hook with no parameters, with point somewhere on the pertinent line, and with the variable c-syntactic-context bound to the current syntactic context (i.e. what you would get by typing C-c C-s on the source line. See section Custom Brace Hanging.). Note that you should not change c-syntactic-context or point or mark inside a c-special-indent-hook function; thus you’ll probably want to wrap your function in a save-excursion(52).

Setting c-special-indent-hook in style definitions is handled slightly differently from other variables—A style can only add functions to this hook, not remove them. See section Style Variables.


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated on September 26, 2026 using texi2html 1.82.