Making Emacs set the indentation style per file
Working with mixed C code bases I often run into problems with different coding styles being used at the same time in the same project. Different open source components use different philosophies, and there may even be different styles inside the same subsystem depending on the individuals that wrote the code etc.
The .emacs config file is suitable to use for setting your personal default style preferences, and it can be used to set styles per directory using matching logic etc.
There are a few C indentation styles built in into Emacs: “gnu”, “k&r”, “bsd”, “whitesmith”, “stroustrup”, “ellemtel” and “linux”. Keep to one of these to be compatible with stock Emacs installations.
In addition to this you also need to set the indentation depth and mode to use the TAB character or some specific amount of spaces.
There are two ways to set the c-style per file using special comment sections in the source code, a compact way and a more verbose variant.
The compact way requires that you make a special comment as the first line in the C source code. To set the "linux" style and the TAB character, use this as the first line:
/* -*- c-file-style: "linux"; indent-tabs-mode: t; -*- */
Another example with "ellemtel" and 3 space indentation depth:
/* -*- c-file-style: "ellemtel"; indent-tabs-mode: nil; c-basic-offset: 3; -*- */
The verbose way makes it possible to put a comment block somewhere in the source code, it does not have to be first in the file. I prefer putting it at the end of the file. Example:
/* Local Variables: */ /* c-file-style: "linux"; */ /* indent-tabs-mode: t; */ /* End: */
It is also allowed to use fancier comment formatting like this:
/** * Local Variables: * c-file-style: "ellemtel"; * indent-tabs-mode: nil; * c-basic-offset: 3; * End: */
Note that you need to reload the source file when you have added this kind of comment to actually make Emacs activate the settings for the buffer. You can use "M-x M-v" followed by ENTER to reload the current file.
The GNU Emacs manuals has a section about Specifying File Variables.