11.2 Interactive Customization

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

 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.


Footnotes

(46)

In this and subsequent examples, the original code is formatted using the ‘gnu’ style unless otherwise indicated. See Styles.