27.3.2 Indenting Several Lines

Sometimes, you may want to reindent several lines of code at a time. One way to do this is to use the mark; when the mark is active and the region is non-empty, TAB indents every line in the region. Alternatively, the command C-M-\ (indent-region) indents every line in the region, whether or not the mark is active (see Indentation Commands).

In addition, Emacs provides the following commands for indenting large chunks of code:

C-M-q

Reindent all the lines within one parenthetical grouping.

C-u TAB

Shift an entire parenthetical grouping rigidly sideways so that its first line is properly indented.

M-x indent-code-rigidly

Shift all the lines in the region rigidly sideways, but do not alter lines that start inside comments and strings.

To reindent the contents of a single parenthetical grouping, position point before the beginning of the grouping and type C-M-q. This changes the relative indentation within the grouping, without affecting its overall indentation (i.e., the indentation of the line where the grouping starts). The function that C-M-q runs depends on the major mode; it is indent-pp-sexp in Lisp mode, c-indent-exp in C mode, etc. To correct the overall indentation as well, type TAB first.

If you like the relative indentation within a grouping but not the indentation of its first line, move point to that first line and type C-u TAB. In Lisp, C, and some other major modes, TAB with a numeric argument reindents the current line as usual, then reindents by the same amount all the lines in the parenthetical grouping starting on the current line. It is clever, though, and does not alter lines that start inside strings. Neither does it alter C preprocessor lines when in C mode, but it does reindent any continuation lines that may be attached to them.

The command M-x indent-code-rigidly rigidly shifts all the lines in the region sideways, like indent-rigidly does (see Indentation Commands). It doesn’t alter the indentation of lines that start inside a string, unless the region also starts inside that string. The prefix arg specifies the number of columns to indent.