Customizing Indentation
Permanent 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
(c-set-offset
). 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
in the c-offsets-alist
variable.
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.
[1] In this an subsequent examples, the original code is formatted using the `gnu
' style unless otherwise indicated. See Styles.