GNU Emacs Manual. Node: Syntactic Analysis

prev UPCustom C Indent NEXTIndentation Calculation

20.5.5.1: Step 1---Syntactic Analysis

In the first step, the C indentation mechanism looks at the line before the one you are currently indenting and determines the syntactic components of the construct on that line. It builds a list of these syntactic components, each of which contains a syntactic symbol and sometimes also a buffer position. Some syntactic symbols describe grammatical elements, for example statement and substatement; others describe locations amidst grammatical elements, for example class-open and knr-argdecl.

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 buffer positions in the syntactic component list.

Here is an example. Suppose we have the following code in a C++ mode buffer (the line numbers don't actually appear in the buffer):

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

If you type C-c C-s (which runs the command c-show-syntactic-information) on line 4, it shows the result of the indentation mechanism for that line:

((statement . 32))

This indicates that the line is a statement and it is indented relative to buffer position 32, which happens to be the `i' in int on line 3. If you move the cursor to line 3 and type C-c C-s, it displays this:

((defun-block-intro . 28))

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

Here is 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: }

Typing C-c C-s on line 4 displays this:

((substatement-open . 43))

This says that the brace opens a substatement block. By the way, a substatement indicates the line after an if, else, while, do, switch, for, try, catch, finally, or synchronized statement.

Within the C indentation commands, after a line has been analyzed syntactically for indentation, the variable c-syntactic-context contains a list that describes the results. Each element in this list is a syntactic component: a cons cell containing a syntactic symbol and (optionally) its corresponding buffer position. There may be several elements in a component list; typically only one element has a buffer position.

prev UPCustom C Indent NEXTIndentation Calculation