Next: Horizontal scrolling, Previous: Indenting switch statements, Up: Common requests [Contents][Index]

### 5.21 How to customize indentation in C, C`++`, and Java buffers?

The Emacs `cc-mode` features an interactive procedure for customizing the indentation style, which is fully explained in the CC Mode manual that is part of the Emacs distribution, see Customization Indentation in The CC Mode Manual. Here’s a short summary of the procedure:

1. Go to the beginning of the first line where you don’t like the indentation and type `C-c C-o`. Emacs will prompt you for the syntactic symbol; type `RET` to accept the default it suggests.
2. Emacs now prompts for the offset of this syntactic symbol, showing the default (the current definition) inside parentheses. You can choose one of these:
   `0`

     No extra indentation.

   `+`

     Indent one basic offset.

   `-`

     Outdent one basic offset.

   `++`

     Indent two basic offsets

   `--`

     Outdent two basic offsets.

   `*`

     Indent half basic offset.

   `/`

     Outdent half basic offset.

3. After choosing one of these symbols, type `C-c C-q` to reindent the line or the block according to what you just specified.
4. If you don’t like the result, go back to step 1. Otherwise, add the following line to your `.emacs`:

       (c-set-offset 'syntactic-symbol offset)

   where syntactic-symbol is the name Emacs shows in the minibuffer when you type `C-c C-o` at the beginning of the line, and offset is one of the indentation symbols listed above (`+`, `/`, `0`, etc.) that you’ve chosen during the interactive procedure.

5. Go to the next line whose indentation is not to your liking and repeat the process there.

It is recommended to put all the resulting `(c-set-offset ...)` customizations inside a C mode hook, like this:

    (defun my-c-mode-hook ()
      (c-set-offset ...)
      (c-set-offset ...))
    (add-hook 'c-mode-hook 'my-c-mode-hook)

Using `c-mode-hook` avoids the need to put a `(require 'cc-mode)` into your `.emacs` file, because `c-set-offset` might be unavailable when `cc-mode` is not loaded.

Note that `c-mode-hook` runs for C source files only; use `c++-mode-hook` for C`++` sources, `java-mode-hook` for Java sources, etc. If you want the same customizations to be in effect in all languages supported by `cc-mode`, use `c-mode-common-hook`.

Next: Horizontal scrolling, Previous: Indenting switch statements, Up: Common requests [Contents][Index]