[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6. Configuration Basics

You configure CC Mode by setting Lisp variables and calling (and perhaps writing) Lisp functions(15), which is usually done by adding code to an Emacs initialization file. This file might be ‘site-start.el’ or ‘.emacs’ or ‘init.el’ or ‘default.el’ or perhaps some other file. See (emacs)Init File section ‘Init File’ in GNU Emacs Manual. For the sake of conciseness, we just call this file “your ‘.emacs’” throughout the rest of the manual.

Several of these variables (currently 16), are known collectively as style variables. CC Mode provides a special mechanism, known as styles to make it easier to set these variables as a group, to “inherit” settings from one style into another, and so on. Style variables remain ordinary Lisp variables, whose values can be read and changed independently of the style system. See section Style Variables.

There are several ways you can write the code, depending on the precise effect you want—they are described further down on this page. If you are new to CC Mode, we suggest you begin with the simplest method, “Top-level commands or the customization interface”.

If you make conflicting settings in several of these ways, the way that takes precedence is the one that appears latest in this list:

Here is a summary of the different ways of writing your configuration settings:

Top-level commands or the “customization interface”

Most simply, you can write setq and similar commands at the top level of your ‘.emacs’ file. When you load a CC Mode buffer, it initializes its configuration from these global values (at least, for those settings you have given values to), so it makes sense to have these setq commands run before CC Mode is first initialized—in particular, before any call to desktop-read (see (emacs)Saving Emacs Sessions section ‘Saving Emacs Sessions’ in GNU Emacs Manual). For example, you might set c-basic-offset thus:

 
(setq c-basic-offset 4)

You can use the more user friendly Customization interface instead, but this manual does not cover in detail how that works. To do this, start by typing M-x customize-group <RET> c <RET>. See (emacs)Easy Customization section ‘Easy Customization’ in GNU Emacs Manual. Emacs normally writes the customizations at the end of your ‘.emacs’ file. If you use desktop-read, you should edit your ‘.emacs’ to place the call to desktop-read after the customizations.

The first initialization of CC Mode puts a snapshot of the configuration settings into the special style user. See section Built-in Styles.

For basic use of Emacs, either of these ways of configuring is adequate. However, the settings are then the same in all CC Mode buffers and it can be clumsy to communicate them between programmers. For more flexibility, you’ll want to use one (or both) of CC Mode’s more sophisticated facilities, hooks and styles.

Hooks

An Emacs hook is a place to put Lisp functions that you want Emacs to execute later in specific circumstances. See (elisp)Hooks section ‘Hooks’ in GNU Emacs Lisp Reference Manual. CC Mode supplies a main hook and a language-specific hook for each language it supports - any functions you put onto these hooks get executed as the last part of a buffer’s initialization. Typically you put most of your customization within the main hook, and use the language-specific hooks to vary the customization settings between language modes. For example, if you wanted different (non-standard) values of c-basic-offset in C Mode and Java Mode buffers, you could do it like this:

 
(defun my-c-mode-hook ()
  (setq c-basic-offset 3))
(add-hook 'c-mode-hook 'my-c-mode-hook)

(defun my-java-mode-hook ()
  (setq c-basic-offset 6))
(add-hook 'java-mode-hook 'my-java-mode-hook)

See Hooks for more details on the use of CC Mode hooks.

Styles

A CC Mode style is a coherent collection of customizations with a name. At any time, exactly one style is active in each CC Mode buffer, either the one you have selected or a default. CC Mode is delivered with several existing styles. Additionally, you can create your own styles, possibly based on these existing styles. If you worked in a programming team called the “Free Group”, which had its own coding standards, you might well have this in your ‘.emacs’ file:

 
(setq c-default-style '((java-mode . "java")
                        (awk-mode . "awk")
                        (other . "free-group-style")))

See Styles for fuller details on using CC Mode styles and how to create them.

File Local Variable setting

A file local variable setting is a setting which applies to an individual source file. You put this in a local variables list, a special block at the end of the source file (see (emacs)Specifying File Variables).

File Styles

A file style is a rarely used variant of the “style” mechanism described above, which applies to an individual source file. See section File Styles. You use this by setting certain special variables in a local variables list (see (emacs)Specifying File Variables).

Hooks with Styles

For ultimate flexibility, you can use hooks and styles together. For example, if your team were developing a product which required a Linux driver, you’d probably want to use the “linux” style for the driver, and your own team’s style for the rest of the code. You could achieve this with code like this in your ‘.emacs’:

 
(defun my-c-mode-hook ()
  (c-set-style
   (if (and (buffer-file-name)
            (string-match "/usr/src/linux" (buffer-file-name)))
       "linux"
     "free-group-style")))
(add-hook 'c-mode-hook 'my-c-mode-hook)

In a programming team, a hook is a also a good place for each member to put his own personal preferences. For example, you might be the only person in your team who likes Auto-newline minor mode. You could have it enabled by default by placing the following in your ‘.emacs’:

 
(defun my-turn-on-auto-newline ()
  (c-toggle-auto-newline 1))
(add-hook 'c-mode-common-hook 'my-turn-on-auto-newline)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.1 Hooks

CC Mode provides several hooks that you can use to customize the mode for your coding style. The main hook is c-mode-common-hook; typically, you’ll put the bulk of your customizations here. In addition, each language mode has its own hook, allowing you to fine tune your settings individually for the different CC Mode languages, and there is a package initialization hook. Finally, there is c-special-indent-hook, which enables you to solve anomalous indentation problems. It is described in Other Special Indentations, not here. All these hooks adhere to the standard Emacs conventions.

When you open a buffer, CC Mode first initializes it with the currently active style (see section Styles). Then it calls c-mode-common-hook, and finally it calls the language-specific hook. Thus, any style settings done in these hooks will override those set by c-default-style.

Variable: c-initialization-hook

Hook run only once per Emacs session, when CC Mode is initialized. This is a good place to change key bindings (or add new ones) in any of the CC Mode key maps. See section Sample .emacs File.

Variable: c-mode-common-hook

Common hook across all languages. It’s run immediately before the language specific hook.

Variable: c-mode-hook
Variable: c++-mode-hook
Variable: objc-mode-hook
Variable: java-mode-hook
Variable: idl-mode-hook
Variable: pike-mode-hook
Variable: awk-mode-hook

The language specific mode hooks. The appropriate one is run as the last thing when you enter that language mode.

Although these hooks are variables defined in CC Mode, you can give them values before CC Mode’s code is loaded—indeed, this is the only way to use c-initialization-hook. Their values aren’t overwritten when CC Mode gets loaded.

Here’s a simplified example of what you can add to your ‘.emacs’ file to do things whenever any CC Mode language is edited. See the Emacs manuals for more information on customizing Emacs via hooks. See section Sample .emacs File, for a more complete sample ‘.emacs’ file.

 
(defun my-c-mode-common-hook ()
  ;; my customizations for all of c-mode and related modes
  (no-case-fold-search)
  )
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)

[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.2 Style Variables

The variables that CC Mode’s style system control are called style variables. Note that style variables are ordinary Lisp variables, which the style system initializes; you can change their values at any time (e.g. in a hook function). The style system can also set other variables, to some extent. See section Styles.

Style variables are handled specially in several ways:

The style variables are:
c-indent-comment-alist, c-indent-comments-syntactically-p (see section Indentation Commands);
c-doc-comment-style (see section Documentation Comments);
c-block-comment-prefix, c-comment-prefix-regexp (see section Customizing Filling and Line Breaking);
c-hanging-braces-alist (see section Hanging Braces);
c-hanging-colons-alist (see section Hanging Colons);
c-hanging-semi&comma-criteria (see section Hanging Semicolons and Commas);
c-cleanup-list (see section Clean-ups);
c-basic-offset (see section Customizing Indentation);
c-offsets-alist (see section c-offsets-alist);
c-comment-only-line-offset (see section Comment Line-Up Functions);
c-special-indent-hook, c-label-minimum-indentation (see section Other Special Indentations);
c-backslash-column, c-backslash-max-column (see section Customizing Macros).


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3 Styles

By style we mean the layout of the code—things like how many columns to indent a block of code, whether an opening brace gets indented to the level of the code it encloses, or of the construct that introduces it, or “hangs” at the end of a line.

Most people only need to edit code formatted in just a few well-defined and consistent styles. For example, their organization might impose a “blessed” style that all its programmers must conform to. Similarly, people who work on GNU software will have to use the GNU coding style. Some shops are more lenient, allowing a variety of coding styles, and as programmers come and go, there could be a number of styles in use. For this reason, CC Mode makes it convenient for you to set up logical groupings of customizations called styles, associate a single name for any particular style, and pretty easily start editing new or existing code using these styles.

As an alternative to writing a style definition yourself, you can have CC Mode guess (at least part of) your style by looking at an already formatted piece of your code, Guessing the Style.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.1 Built-in Styles

If you’re lucky, one of CC Mode’s built-in styles might be just what you’re looking for. These are:

gnu

Coding style blessed by the Free Software Foundation for C code in GNU programs.

k&r

The classic Kernighan and Ritchie style for C code.

bsd

Also known as “Allman style” after Eric Allman.

whitesmith

Popularized by the examples that came with Whitesmiths C, an early commercial C compiler.

stroustrup

The classic Stroustrup style for C++ code.

ellemtel

Popular C++ coding standards as defined by “Programming in C++, Rules and Recommendations,” Erik Nyquist and Mats Henricson, Ellemtel(19).

linux

C coding standard for Linux (the kernel).

python

C coding standard for Python extension modules(20).

java

The style for editing Java code. Note that the default value for c-default-style installs this style when you enter java-mode.

awk

The style for editing AWK code. Note that the default value for c-default-style installs this style when you enter awk-mode.

user

This is a special style created by you. It consists of the factory defaults for all the style variables as modified by the customizations you do either with the Customization interface or by writing setqs and c-set-offsets at the top level of your ‘.emacs’ file (see section Configuration Basics). The style system creates this style as part of its initialization and doesn’t modify it afterwards.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.2 Choosing a Style

When you create a new buffer, its style will be set from c-default-style. The factory default is the style gnu, except in Java and AWK modes where it’s java and awk.

Remember that if you set a style variable with the Customization interface or at the top level of your ‘.emacs’ file before the style system is initialized (see section Configuration Basics), this setting will override the one that the style system would have given the variable.

To set a buffer’s style interactively, use the command C-c . (see section Other Commands). To set it from a file’s local variable list, File Styles.

User Option: c-default-style

This variable specifies which style to install by default in new buffers. It takes either a style name string, or an association list of major mode symbols to style names:

  1. When c-default-style is a string, it must be an existing style name. This style is then used for all modes.
  2. When c-default-style is an association list, the mode language is looked up to find a style name string.
  3. If c-default-style is an association list where the mode language mode isn’t found then the special symbol ‘other’ is looked up. If it’s found then the associated style is used.
  4. If ‘other’ is not found then the ‘gnu’ style is used.

In all cases, the style described in c-default-style is installed before the language hooks are run, so you can always override this setting by including an explicit call to c-set-style in your language mode hook, or in c-mode-common-hook.

The standard value of c-default-style is ((java-mode . "java") (awk-mode . "awk") (other . "gnu")).

Variable: c-indentation-style

This variable always contains the buffer’s current style name, as a string.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.3 Adding and Amending Styles

If none of the built-in styles is appropriate, you’ll probably want to create a new style definition, possibly based on an existing style. To do this, put the new style’s settings into a list with the following format - the list can then be passed as an argument to the function c-add-style. You can see an example of a style definition in Sample .emacs File.

Structure of a Style Definition List

([base-style] [(variable . value) …])

Optional base-style, if present, must be a string which is the name of the base style from which this style inherits. At most one base-style is allowed in a style definition. If base-style is not specified, the style inherits from the table of factory default values(21) instead. All styles eventually inherit from this internal table. Style loops generate errors. The list of pre-existing styles can be seen in Built-in Styles.

The dotted pairs (variable . value) each consist of a variable and the value it is to be set to when the style is later activated.(22) The variable can be either a CC Mode style variable or an arbitrary Emacs variable. In the latter case, it is not made buffer-local by the CC Mode style system.

Two variables are treated specially in the dotted pair list:

c-offsets-alist

The value is in turn a list of dotted pairs of the form

 
(syntactic-symbol . offset)

as described in c-offsets-alist. These are passed to c-set-offset so there is no need to set every syntactic symbol in your style, only those that are different from the inherited style.

c-special-indent-hook

The value is added to c-special-indent-hook using add-hook, so any functions already on it are kept. If the value is a list, each element of the list is added with add-hook.

Styles are kept in the c-style-alist variable, but you should never modify this variable directly. Instead, CC Mode provides the function c-add-style for this purpose.

Function: c-add-style stylename description &optional set-p

Add or update a style called stylename, a string. description is the new style definition in the form described above. If stylename already exists in c-style-alist then it is replaced by description. (Note, this replacement is total. The old style is not merged into the new one.) Otherwise, a new style is added.

If the optional set-p is non-nil then the new style is applied to the current buffer as well. The use of this facility is deprecated and it might be removed from CC Mode in a future release. You should use c-set-style instead.

The sample ‘.emacs’ file provides a concrete example of how a new style can be added and automatically set. See section Sample .emacs File.

Variable: c-style-alist

This is the variable that holds the definitions for the styles. It should not be changed directly; use c-add-style instead.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.4 Guessing the Style

Instead of specifying a style, you can get CC Mode to guess your style by examining an already formatted code buffer. CC Mode then determines the “most frequent” offset (see section c-offsets-alist) for each of the syntactic symbols (see section Indentation Engine Basics) encountered in the buffer, and the “most frequent” value of c-basic-offset (see section Customizing Indentation), then merges the current style with these “guesses” to form a new style. This combined style is known as the guessed style.

To do this, call c-guess (or one of the other 5 guessing commands) on your sample buffer. The analysis of your code may take some time.

You can then set the guessed style in any CC Mode buffer with c-guess-install. You can display the style with c-guess-view, and preserve it by copying it into your ‘.emacs’ for future use, preferably after editing it.

M-x c-guess-no-install
M-x c-guess-buffer-no-install
M-x c-guess-region-no-install

These commands analyze a part of the current buffer and guess the style from it.

The part of the buffer examined is either the region (c-guess-region-no-install), the entire buffer (c-guess-buffer-no-install), or the first c-guess-region-max bytes (c-guess-no-install).

Each of these commands can be given an optional prefix argument. This instructs CC Mode to combine the new guesses with the current guesses before forming the guessed style.

M-x c-guess
M-x c-guess-buffer
M-x c-guess-region

These commands analyze a part of the current buffer, guess the style from it, then install the guessed style on the buffer. The guessed style is given a name based on the buffer’s absolute file name, and you can then set this style on any CC Mode buffer with C-c ..

The part of the buffer examined is either the region (c-guess-region), the entire buffer (c-guess-buffer), or the first c-guess-region-max bytes (c-guess).

Each of these commands can be given an optional prefix argument. This instructs CC Mode to combine the new guesses with the current guesses before forming the guessed style.

User Option: c-guess-region-max

This variable, default 50000, is the size in bytes of the buffer portion examined by c-guess and c-guess-no-install. If set to nil, the entire buffer is examined.

User Option: c-guess-offset-threshold

This variable, default 10, is the maximum offset, either outwards or inwards, which will be taken into account by the analysis process. Any offset bigger than this will be ignored. For no limit, set this variable to a large number.

M-x c-guess-install

Set the current buffer’s style to the guessed style. This prompts you to enter an optional new style name to give to the guessed style. By default, this name is based on the buffer’s absolute file name. You can then use this style like any other.

M-x c-guess-view

Display the most recently guessed style in a temporary buffer. This display is in the form of a c-add-style form (see section Adding and Amending Styles) which can be easily copied to your ‘.emacs’. You will probably want to edit it first.

The display of the guessed style contains these elements:

Placeholder Name

You should replace this with a style name of your own.

Parent Style

The style current when the guessing began, from which the guessed style inherits (see section Configuration Basics) the settings which weren’t guessed.

Guessed Offsets

These are the core result of the guessing process. Each of them is marked by a comment.

Inherited Offsets

These are syntactic offsets which have been taken over from the parent style. To avoid possible future conflicts, you should remove either these offsets or the parent style name.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

6.3.5 File Styles

The Emacs manual describes how you can customize certain variables on a per-file basis by including a file local variable block at the end of the file (see (emacs)File Variables section ‘Local Variables in Files’ in GNU Emacs Manual).

So far, you’ve only seen a functional interface for setting styles in CC Mode, and this can’t be used here. CC Mode fills the gap by providing two variables for use in a file’s local variable list. Don’t use them anywhere else! These allow you to customize the style on a per-file basis:

Variable: c-file-style

Set this variable to a style name string in the Local Variables list. From now on, when you visit the file, CC Mode will automatically set the file’s style to this one using c-set-style.

Variable: c-file-offsets

Set this variable (in the Local Variables list) to an association list of the same format as c-offsets-alist. From now on, when you visit the file, CC Mode will automatically institute these offsets using c-set-offset.

Note that file style settings (i.e. c-file-style) are applied before file offset settings (i.e. c-file-offsets)(23).

If you set any variable by the file local variables mechanism, that setting takes priority over all other settings, even those in your mode hooks (see section Hooks). Any individual setting of a variable will override one made through c-file-style or c-file-offsets.


[ << ] [ >> ]           [Top] [Contents] [Index] [ ? ]

This document was generated on September 26, 2026 using texi2html 1.82.