home
***
CD-ROM
|
disk
|
FTP
|
other
***
search
/
Dream 49
/
Amiga_Dream_49.iso
/
beos
/
emacs
/
emacs-19.34-bin
/
emacs-19
/
info
/
ccmode-1
(
.txt
)
< prev
next >
Wrap
GNU Info File
|
1997-09-17
|
47KB
|
906 lines
This is Info file ../info/ccmode, produced by Makeinfo-1.63 from the
input file cc-mode.texi.
Copyright (C) 1995 Free Software Foundation, Inc.
File: ccmode, Node: Top, Next: Introduction, Prev: (dir), Up: (dir)
* Menu:
* Introduction::
* Getting Connected::
* New Indentation Engine::
* Minor Modes::
* Indentation Commands::
* Customizing Indentation::
* Syntactic Symbols::
* Performance Issues::
* Frequently Asked Questions::
* Getting the latest cc-mode release::
* Sample .emacs File::
* Requirements::
* Limitations and Known Bugs::
* Mailing Lists and Submitting Bug Reports::
* Concept Index::
* Command Index:: Command Index
* Key Index:: Key Index
* Variable Index:: Variable Index
File: ccmode, Node: Introduction, Next: Getting Connected, Prev: Top, Up: Top
Introduction
************
Welcome to `cc-mode', version 4. This is a GNU Emacs mode for
editing files containing C, C++, Objective-C, and Java code. This
incarnation of the mode is descendant from `c-mode.el' (also called
"Boring Old C Mode" or BOCM `:-)', and `c++-mode.el' version 2, which I
have been maintaining since 1992. `cc-mode' represents a significant
milestone in the mode's life. It has been fully merged back with Emacs
19's `c-mode.el'. Also a new, more intuitive and flexible mechanism for
controlling indentation has been developed.
`cc-mode' version 4 supports the editing of K&R and ANSI C, "ARM"
(1) C++, Objective-C, and Java files. In this way, you can easily set
up consistent coding styles for use in editing all C, C++, Objective-C,
and Java programs.
This manual will describe the following:
* How to get started using `cc-mode'.
* How the new indentation engine works.
* How to customize the new indentation engine.
Note that the name of this file is `cc-mode.el', and I'll often
refer to the package as `cc-mode', but there really is no top level
`cc-mode' entry point. I call it `cc-mode' simply to differentiate it
from `c-mode.el'. All of the variables, commands, and functions in
`cc-mode' are prefixed with `c-<thing>', and `c-mode', `c++-mode',
`objc-mode', and `java-mode' entry points are provided. This file is
intended to be a replacement for `c-mode.el' and `c++-mode.el'.
The major version number was incremented to 4 with the addition of
`objc-mode'. To find the minor revision number of this release, use
`M-x c-version RET'. Work has already begun on `cc-mode' version 5, in
which Emacs 18 will not be supported.
As of this writing (19-Jan-1996), both Emacs 19.30 and XEmacs 19.13
are distributed with `cc-mode'. Emacs 19.31 and XEmacs 19.14 will both
contain the latest version of cc-mode when it is released. If you are
running older versions of these Emacsen, you may want to upgrade your
copy of `cc-mode'. See *Note Getting the latest cc-mode release::.
This distribution also contains a file called `cc-compat.el' which
should ease your transition from BOCM to `cc-mode'. It currently comes
unguaranteed and unsupported, but this may change for future versions.
A special word of thanks goes to Krishna Padmasola for his work in
converting the original `README' file to texinfo format. `cc-mode'
users have been clamoring for a manual for a long time, and thanks to
Krishna, it is now available <clap> <clap> <clap>! `:-)'
---------- Footnotes ----------
(1) i.e. "The Annotated C++ Reference Manual", by Ellis and
Stroustrup.
File: ccmode, Node: Getting Connected, Next: New Indentation Engine, Prev: Introduction, Up: Top
Getting Connected
*****************
`cc-mode.el' works well with the 2 main branches of Emacs 19: XEmacs
and the Emacs 19 maintained by the FSF. Emacs 19 users will want to
use Emacs version 19.21 or better, XEmacs users will want 19.6 or
better. Earlier versions of these Emacsen have deficiencies and/or bugs
which will adversely affect the performance and usability of `cc-mode'.
Similarly if you use the `cc-mode-18.el' compatibility file,
`cc-mode.el' will work with Emacs 18, but only moderately well. A word
of warning though, *Emacs 18 lacks some fundamental functionality and
that ultimately means using Emacs 18 is a losing battle*. Hence
`cc-mode' under Emacs 18 is no longer supported and it is highly
recommended that you upgrade to Emacs 19. If you use `cc-mode' under
Emacs 18, you're on your own. With `cc-mode' version 5, Emacs 18
support will be dropped altogether.
Note that as of XEmacs 19.13 and Emacs 19.30, your Emacs already
comes with `cc-mode' version 4 preconfigured for your use. You should
be able to safely skip the rest of the setup information in this
chapter.
The first thing you will want to do is put `cc-mode.el' somewhere on
your `load-path' so Emacs can find it. Do a `C-h v load-path RET' to
see all the directories Emacs looks at when loading a file. If none of
these directories are appropriate, create a new directory and add it to
your `load-path':
*[in the shell]*
% cd
% mkdir mylisp
% mv cc-mode.el mylisp
% cd mylisp
*[in your .emacs file add]*
(setq load-path (cons "~/mylisp" load-path))
Next you want to "byte compile" `cc-mode.el'. The mode uses a lot
of macros so if you don't byte compile it, things will be unbearably
slow. *You can ignore all byte-compiler warnings!* They are the
result of the supporting different versions of Emacs, and none of the
warnings have any effect on operation. Let me say this again: *You
really can ignore all byte-compiler warnings!*
Here's what to do to byte-compile the file [in emacs]:
M-x byte-compile-file RET ~/mylisp/cc-mode.el RET
If you are running a version of Emacs or XEmacs that comes with
`cc-mode' by default, you can simply add the following to your `.emacs'
file in order to upgrade to the latest version of `cc-mode':
(load "cc-mode")
Users of even older versions of Emacs 19, Emacs 18, or of the older
Lucid Emacs will probably be running an Emacs that has BOCM `c-mode.el'
and possible `c++-mode.el' pre-dumped. If your Emacs is dumped with
either of these files you first need to make Emacs "forget" about those
older modes.
If you can do a `C-h v c-mode-map RET' without getting an error, you
need to add these lines at the top of your `.emacs' file:
(fmakunbound 'c-mode)
(makunbound 'c-mode-map)
(fmakunbound 'c++-mode)
(makunbound 'c++-mode-map)
(makunbound 'c-style-alist)
After those lines you will want to add the following autoloads to
your `.emacs' file so that `cc-mode' gets loaded at the right time:
(autoload 'c++-mode "cc-mode" "C++ Editing Mode" t)
(autoload 'c-mode "cc-mode" "C Editing Mode" t)
(autoload 'objc-mode "cc-mode" "Objective-C Editing Mode" t)
(autoload 'java-mode "cc-mode" "Java Editing Mode" t)
Alternatively, if you want to make sure `cc-mode' is loaded when
Emacs starts up, you could use this line instead of the three autoloads
above:
(require 'cc-mode)
Next, you will want to set up Emacs so that it edits C files in
`c-mode', C++ files in `c++-mode', and Objective-C files in
`objc-mode'. All users should add the following to their `.emacs' file.
Note that this assumes you'll be editing `.h' and `.c' files as C,
`.hh', `.cc', `.H', and `.C' files as C++, `.m' files as Objective-C,
and `.java' files as Java code. YMMV:
(setq auto-mode-alist
(append
'(("\\.C$" . c++-mode)
("\\.H$" . c++-mode)
("\\.cc$" . c++-mode)
("\\.hh$" . c++-mode)
("\\.c$" . c-mode)
("\\.h$" . c-mode)
("\\.m$" . objc-mode)
("\\.java$" . java-mode)
) auto-mode-alist))
You may already have some or all of these settings on your
`auto-mode-alist', but it won't hurt to put them on there again.
That's all you need - I know, I know, it sounds like a lot `:-)',
but after you've done all this, you should only need to quit and restart
Emacs. The next time you visit a C, C++, Objective-C, or Java file you
should be using `cc-mode'. You can check this easily by hitting `M-x
c-version RET' in the `c-mode', `c++-mode', or `objc-mode' buffer. You
should see this message in the echo area:
Using `cc-mode' version 4.XXX
Where XXX is the latest release minor number.
* Menu:
* Syntactic Analysis::
* Indentation Calculation::
File: ccmode, Node: New Indentation Engine, Next: Minor Modes, Prev: Getting Connected, Up: Top
New Indentation Engine
**********************
`cc-mode' has a new indentation engine, providing a simplified, yet
flexible and general mechanism for customizing indentation. It breaks
indentation calculation into two steps. First for the line of code being
indented, `cc-mode' analyzes what kind of language construct it's
looking at, then it applies user defined offsets to the current line
based on this analysis.
This section will briefly cover how indentation is calculated in
`cc-mode'. It is important to understand the indentation model being
used so that you will know how to customize `cc-mode' for your personal
coding style.
* Menu:
* Syntactic Analysis::
* Indentation Calculation::
File: ccmode, Node: Syntactic Analysis, Next: Indentation Calculation, Up: New Indentation Engine
Syntactic Analysis
==================
The first thing `cc-mode' does when indenting a line of code, is to
analyze the line, determining the "syntactic component list" of the
construct on that line. A "syntactic component" consists of a pair of
information (in lisp parlance, a *cons cell*), where the first part is
a "syntactic symbol", and the second part is a "relative buffer
position". Syntactic symbols describe elements of C code (1), e.g.
`statement', `substatement', `class-open', `class-close', etc. *Note
Syntactic Symbols::, for a complete list of currently recognized
syntactic symbols and their semantics. The variable `c-offsets-alist'
also contains the list of currently supported syntactic symbols.
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 relative buffer position in the syntactic component.
It might help to see an example. Suppose we had the following code as
the only thing in a `c++-mode' buffer (2):
1: void swap( int& a, int& b )
2: {
3: int tmp = a;
4: a = b;
5: b = tmp;
6: }
We can use the command `C-c C-s' (`c-show-syntactic-information') to
simply report what the syntactic analysis is for the current line.
Running this command on line 4 this example, we'd see in the echo area:
((statement . 35))
This tells us that the line is a statement and it is indented
relative to buffer position 35, which happens to be the `i' in `int' on
line 3. If you were to move point to line 3 and hit `C-c C-s', you
would see:
((defun-block-intro . 29))
This indicates that the `int' line is the first statement in a top
level function block, and is indented relative to buffer position 29,
which is the brace just after the function header.
Here's 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: }
Hitting `C-c C-s' on line 4 gives us:
((substatement-open . 46))
which tells us that this is a brace that *opens* a substatement block.
Syntactic component lists can contain more than one component, and
individual syntactic components need not have relative buffer positions.
The most common example of this is a line that contains a "comment only
line".
1: void draw_list( List<Drawables>& drawables )
2: {
3: // call the virtual draw() method on each element in list
4: for( int i=0; i < drawables.count(), ++i )
5: {
6: drawables[i].draw();
7: }
8: }
Hitting `C-c C-s' on line 3 of example 3 gives us:
((comment-intro) (defun-block-intro . 46))
so you can see that the syntactic component list contains two syntactic
components. Also notice that the first component, `(comment-intro)'
has no relative buffer position.
---------- Footnotes ----------
(1) or C++, Objective-C, or Java code. In general, for the rest of
this manual I'll use the term "C code" to refer to all the C-like
dialects, unless otherwise noted.
(2) The line numbers in this and future examples don't actually
appear in the buffer, of course!
(3) A "substatement" indicates the line after an `if', `else',
`while', `do', `switch', or `for' statement, and a "substatement block"
is a brace block following one of those constructs.
File: ccmode, Node: Indentation Calculation, Prev: Syntactic Analysis, Up: New Indentation Engine
Indentation Calculation
=======================
Indentation for the current line is calculated using the syntactic
component list derived in step 1 above (see *Note Syntactic Analysis::).
Each component contributes to the final total indentation of the line in
two ways.
First, the syntactic symbols are looked up in the `c-offsets-alist'
variable, which is an association list of syntactic symbols and the
offsets to apply for those symbols. These offsets are added to the
running total.
Second, if the component has a relative buffer position, `cc-mode'
adds the column number of that position to the running total. By adding
up the offsets and columns for every syntactic component on the list,
the final total indentation for the current line is computed.
Let's use our two code examples above to see how this works. Here is
our first example again:
1: void swap( int& a, int& b )
2: {
3: int tmp = a;
4: a = b;
5: b = tmp;
6: }
Let's say point is on line 3 and we hit the TAB key to re-indent the
line. Remember that the syntactic component list for that line is:
((defun-block-intro . 29))
`cc-mode' looks up `defun-block-intro' in the `c-offsets-alist'
variable. Let's say it finds the value `4'; it adds this to the
running total (initialized to zero), yielding a running total
indentation of 4 spaces.
Next `cc-mode' goes to buffer position 29 and asks for the current
column. Since the brace at buffer position 29 is in column zero, it
adds `0' to the running total. Since there is only one syntactic
component on the list for this line, indentation calculation is
complete, and the total indentation for the line is 4 spaces.
Here's 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: }
If we were to hit `TAB' on line 4 in the above example, the same
basic process is performed, despite the differences in the syntactic
component list. Remember that the list for this line is:
((substatement-open . 46))
Here, `cc-mode' first looks up the `substatement-open' symbol in
`c-offsets-alist'. Let's say it finds the value `4'. This yields a
running total of 4. `cc-mode' then goes to buffer position 46, which
is the `i' in `if' on line 3. This character is in the fourth column
on that line so adding this to the running total yields an indentation
for the line of 8 spaces.
Simple, huh?
Actually, the mode usually just does The Right Thing without you
having to think about it in this much detail. But when customizing
indentation, it's helpful to understand the general indentation model
being used.
To help you configure `cc-mode', you can set the variable
`c-echo-syntactic-information-p' to non-`nil' so that the syntactic
component list and calculated offset will always be echoed in the
minibuffer when you hit `TAB'.
File: ccmode, Node: Minor Modes, Next: Indentation Commands, Prev: New Indentation Engine, Up: Top
Minor Modes
***********
`cc-mode' contains two minor-mode-like features that you should find
useful while you enter new C code. The first is called "auto-newline"
mode, and the second is called "hungry-delete" mode. These minor modes
can be toggled on and off independently, and `cc-mode' can be
configured so that it comes up with any combination of these minor
modes. By default, both of these minor modes are turned off.
The state of the minor modes is always reflected in the minor mode
list on the modeline of the `cc-mode' buffer. When auto-newline mode is
enabled, you will see `C/a' on the mode line (1). When hungry delete
mode is enabled you would see `C/h' and when both modes are enabled,
you'd see `C/ah'.
`cc-mode' provides keybindings which allow you to toggle the minor
modes while editing code on the fly. To toggle just the auto-newline
state, hit `C-c C-a' (`c-toggle-auto-state'). When you do this, you
should see the `a' indicator either appear or disappear on the
modeline. Similarly, to toggle just the hungry-delete state, use `C-c
C-d' (`c-toggle-hungry-state'), and to toggle both states together, use
`C-c C-t' (`c-toggle-auto-hungry-state').
To set up the auto-newline and hungry-delete states to your preferred
values, you would need to add some lisp to your `.emacs' file that
called one of the `c-toggle-*-state' functions directly. When called
programmatically, each function takes a numeric value, where a positive
number enables the minor mode, a negative number disables the mode, and
zero toggles the current state of the mode.
So for example, if you wanted to enable both auto-newline and
hungry-delete for all your C file editing, you could add the following
to your `.emacs' file:
(add-hook 'c-mode-common-hook '(lambda () (c-toggle-auto-hungry-state 1)))
* Menu:
* Auto-newline insertion::
* Hungry-deletion of whitespace::
---------- Footnotes ----------
(1) Remember that the `C' would be replaced with `C++' or `ObjC' if
you were editing C++ or Objective-C code.
File: ccmode, Node: Auto-newline insertion, Next: Hungry-deletion of whitespace, Up: Minor Modes
Auto-newline insertion
======================
Auto-newline minor mode works by enabling certain "electric
commands". Electric commands are typically bound to special characters
such as the left and right braces, colons, semi-colons, etc., which when
typed, perform some magic formatting in addition to inserting the typed
character. As a general rule, electric commands are only electric when
the following conditions apply:
* Auto-newline minor mode is enabled, as evidenced by a `C/a' or
`C/ah' indicator on the modeline.
* The character was not typed inside of a literal (1).
* No numeric argument was supplied to the command (i.e. it was typed
as normal, with no `C-u' prefix).
Certain other conditions may apply on a language specific basis. For
example, the second slash (`/') of a C++ style line comment is electric
in `c++-mode', `objc-mode', and `java-mode', but not in `c-mode'.
* Menu:
* Hanging Braces::
* Hanging Colons::
* Hanging Semi-colons and commas::
* Other electric commands::
* Clean-ups::
---------- Footnotes ----------
(1) A "literal" is defined in `cc-mode' as any comment, string, or
cpp macro definition. These constructs are also known as "syntactic
whitespace" since they are usually ignored when scanning C code.
File: ccmode, Node: Hanging Braces, Next: Hanging Colons, Up: Auto-newline insertion
Hanging Braces
--------------
When you type either an open or close brace (i.e. `{' or `}'), the
electric command `c-electric-brace' gets run. This command has two
electric formatting behaviors. First, it will perform some
re-indentation of the line the brace was typed on, and second, it will
add various newlines before and/or after the typed brace.
Re-indentation occurs automatically whenever the electric behavior is
enabled. If the brace ends up on a line other than the one it was typed
on, then that line is on is also indented according to
`c-offsets-alist'.
The insertion of newlines is controlled by the
`c-hanging-braces-alist' variable. This variable contains a mapping
between syntactic symbols related to braces, and a list of places to
insert a newline. The syntactic symbols that are useful for this list
are: `class-open', `class-close', `defun-open', `defun-close',
`inline-open', `inline-close', `brace-list-open', `brace-list-close',
`brace-list-intro', `brace-list-entry', `block-open', `block-close',
`substatement-open', and `statement-case-open'. *Note Syntactic
Symbols:: for a more detailed description of these syntactic symbols.
The value associated with each syntactic symbol in this association
list is called an ACTION which can be either a function or a list.
*Note Custom Brace and Colon Hanging:: for a more detailed discussion of
using a function as a brace hanging ACTION.
When ACTION is a list, it can contain any combination of the symbols
`before' or `after', directing `cc-mode' where to put newlines in
relationship to the brace being inserted. Thus, if the list contains
only the symbol `after', then the brace is said to "hang" on the right
side of the line, as in:
// here, open braces always `hang'
void spam( int i ) {
if( i == 7 ) {
dosomething(i);
}
}
When the list contains both `after' and `before', the braces will
appear on a line by themselves, as shown by the close braces in the
above example. The list can also be empty, in which case no newlines
are added either before or after the brace.
For example, the default value of `c-hanging-braces-alist' is:
(defvar c-hanging-braces-alist '((brace-list-open)
(substatement-open after)
(block-close . c-snug-do-while)))
which says that `brace-list-open' braces should both hang on the right
side, and allow subsequent text to follow on the same line as the
brace. Also, `substatement-open' braces should hang on the right side,
but subsequent text should follow on the next line. Here, in the
`block-close' entry, you also see an example of using a function as an
ACTION.
File: ccmode, Node: Hanging Colons, Next: Hanging Semi-colons and commas, Prev: Hanging Braces, Up: Auto-newline insertion
Hanging Colons
--------------
Using a mechanism similar to brace hanging (see *Note Hanging
Braces::), colons can also be made to hang using the variable
`c-hanging-colons-alist'. The syntactic symbols appropriate for this
association list are: `case-label', `label', `access-label',
`member-init-intro', and `inher-intro'. *Note Hanging Braces:: and
*Note Custom Brace and Colon Hanging:: for details. Note however, that
`c-hanging-colons-alist' does not implement functions as ACTIONs.
In C++, double-colons are used as a scope operator but because these
colons always appear right next to each other, newlines before and after
them are controlled by a different mechanism, called "clean-ups" in
`cc-mode'. *Note Clean-ups:: for details.
File: ccmode, Node: Hanging Semi-colons and commas, Next: Other electric commands, Prev: Hanging Colons, Up: Auto-newline insertion
Hanging Semi-colons and commas
------------------------------
Semicolons and commas are also electric in `cc-mode', but since
these characters do not correspond directly to syntactic symbols, a
different mechanism is used to determine whether newlines should be
automatically inserted after these characters. *Note Customizing
Semi-colons and Commas:: for details.
File: ccmode, Node: Other electric commands, Next: Clean-ups, Prev: Hanging Semi-colons and commas, Up: Auto-newline insertion
Other electric commands
-----------------------
A few other keys also provide electric behavior. For example the
`#' key (`c-electric-pound') is electric when it is typed as the first
non-whitespace character on a line. In this case, the variable
`c-electric-pound-behavior' is consulted for the electric behavior.
This variable takes a list value, although the only element currently
defined is `alignleft', which tells this command to force the `#'
character into column zero. This is useful for entering cpp macro
definitions.
Stars and slashes (i.e. `*' and `/') are also electric under certain
circumstances. If a star is inserted as the second character of a C
style block comment on a "comment-only" line, then the comment
delimiter is indented as defined by `c-offsets-alist'. A comment-only
line is defined as a line which contains only a comment, as in:
void spam( int i )
{
// this is a comment-only line...
if( i == 7 ) // but this is not
{
dosomething(i);
}
}
Likewise, if a slash is inserted as the second slash in a C++ style
line comment (also only on a comment-only line), then the line is
indented as defined by `c-offsets-alist'.
File: ccmode, Node: Clean-ups, Prev: Other electric commands, Up: Auto-newline insertion
Clean-ups
---------
"Clean-ups" are a mechanism complementary to colon and brace
hanging. On the surface, it would seem that clean-ups overlap the
functionality provided by the `c-hanging-*-alist' variables, and
similarly, clean-ups are only enabled when auto-newline minor mode is
enabled. Clean-ups are used however to adjust code "after-the-fact",
i.e. to eliminate some whitespace that isn't inserted by electric
commands, or whitespace that contains intervening constructs.
You can configure `cc-mode''s clean-ups by setting the variable
`c-cleanup-list', which is a list of clean-up symbols. By default,
`cc-mode' cleans up only the `scope-operator' construct, which is
necessary for proper C++ support. Note that clean-ups are only
performed when the construct does not occur within a literal (see *Note
Auto-newline insertion::), and when there is nothing but whitespace
appearing between the individual components of the construct.
There are currently only five specific constructs that `cc-mode' can
clean up, as indicated by these symbols:
* `brace-else-brace' - cleans up `} else {' constructs by placing
the entire construct on a single line. Clean-up occurs when the
open brace after the `else' is typed. So for example, this:
void spam(int i)
{
if( i==7 )
{
dosomething();
}
else
{
appears like this after the open brace is typed:
void spam(int i)
{
if( i==7 ) {
dosomething();
} else {
* `empty-defun-braces' - cleans up braces following a top-level
function or class definition that contains no body. Clean up
occurs when the closing brace is typed. Thus the following:
class Spam
{
}
is transformed into this when the close brace is typed:
class Spam
{}
* `defun-close-semi' - cleans up the terminating semi-colon on
top-level function or class definitions when they follow a close
brace. Clean up occurs when the semi-colon is typed. So for
example, the following:
class Spam
{
}
;
is transformed into this when the semi-colon is typed:
class Spam
{
};
* `list-close-comma' - cleans up commas following braces in array
and aggregate initializers. Clean up occurs when the comma is
typed.
* `scope-operator' - cleans up double colons which may designate a
C++ scope operator split across multiple lines(1). Clean up
occurs when the second colon is typed. You will always want
`scope-operator' in the `c-cleanup-list' when you are editing C++
code.
---------- Footnotes ----------
(1) Certain C++ constructs introduce ambiguous situations, so
`scope-operator' clean-ups may not always be correct. This usually
only occurs when scoped identifiers appear in switch label tags.
File: ccmode, Node: Hungry-deletion of whitespace, Prev: Auto-newline insertion, Up: Minor Modes
Hungry-deletion of whitespace
=============================
Hungry deletion of whitespace, or as it more commonly called,
"hungry-delete mode", is a simple feature that some people find
extremely useful. In fact, you might find yourself wanting
hungry-delete in *all* your editing modes!
In a nutshell, when hungry-delete mode is enabled, hitting the `DEL'
character will consume all preceding whitespace, including newlines and
tabs. This can really cut down on the number of `DEL''s you have to
type if, for example you made a mistake on the preceding line.
By default, `cc-mode' actually runs the command `c-electric-delete'
when you hit `DEL'. When this command is used to delete a single
character (i.e. when it is called interactively with no numeric
argument), it really runs the function contained in the variable
`c-delete-function'. This function is called with a single argument,
which is the number of characters to delete. `c-delete-function' is
also called when the `DEL' key is typed inside a literal (see *Note
Auto-newline insertion::. Inside a literal, `c-electric-delete' is not
electric, which is typical of all the so-called electric commands.
File: ccmode, Node: Indentation Commands, Next: Customizing Indentation, Prev: Minor Modes, Up: Top
Indentation Commands
********************
Various commands are provided which allow you to conveniently
re-indent C constructs, and these are outlined below. There are
several things to note about these indentation commands. First, when
you change your programming style, either though `c-set-style' or some
other means, your file does *not* automatically get re-indented. When
you change style parameters, you will typically need to reformat the
line, expression, or buffer to see the effects of your changes.
Second, changing some variables have no effect on existing code, even
when you do re-indent. For example, the `c-hanging-*' variables and
`c-cleanup-list' only affect newly entered code. So for example,
changing `c-hanging-braces-alist' and re-indenting the buffer will not
adjust placement of braces already in the file.
Third, re-indenting large portions of code is currently rather
inefficient. Improvements have been made since previous releases of
`cc-mode', and much more radical improvements will be made for the next
release, but for now you need to be aware of this (1). Some provision
has been made to at least inform you as to the progress of your large
re-indentation command. The variable `c-progress-interval' controls
how often a progress message is displayed. Set this variable to `nil'
to inhibit progress messages. Note that this feature only works with
Emacs 19.
Also, except as noted below, re-indentation is always driven by the
same mechanisms that control on-the-fly indentation of code. *Note New
Indentation Engine:: for details.
To indent a single line of code, use `TAB' (`c-indent-command').
The behavior of this command is controlled by the variable
`c-tab-always-indent'. When this variable is `t', `TAB' always just
indents the current line. When `nil', the line is indented only if
point is at the left margin, or on or before the first non-whitespace
character on the line, otherwise a real tab character is inserted. If
this variable's value is something other that `t' or `nil' (e.g.
`'other'), then a real tab character is inserted only when point is
inside a literal (see *Note Auto-newline insertion::), otherwise the
line is indented.
To indent an entire balanced brace or parenthesis expression, use
`M-C-q' (`c-indent-exp'). Note that point should be on the opening
brace or parenthesis of the expression you want to indent.
Another very convenient keystroke is `C-c C-q' (`c-indent-defun')
when re-indents the entire top-level function or class definition that
encompasses point. It leaves point at the same position within the
buffer.
To indent any arbitrary region of code, use `M-C-\'
(`indent-region'). This is a standard Emacs command, specially
tailored for C code in a `cc-mode' buffer. Note that of course, point
and mark must delineate the region you want to indent.
While not strictly an indentation function, `M-C-h'
(`c-mark-function') is useful for marking the current top-level
function or class definition as the current region.
---------- Footnotes ----------
(1) In particular, I have had people complain about the speed that
`cc-mode' re-indents `lex(1)' output. Lex, yacc, and other code
generators usually output some pretty perverse code. *Don't* try to
indent this stuff with `cc-mode'!
File: ccmode, Node: Customizing Indentation, Next: Syntactic Symbols, Prev: Indentation Commands, Up: Top
Customizing Indentation
***********************
The `c-offsets-alist' variable is where you customize all your
indentations. You simply need to decide what additional offset you want
to add for every syntactic symbol. You can use the command `C-c C-o'
(`c-set-offset') as the way to set offsets, both interactively and from
your mode hook. Also, you can set up *styles* of indentation just like
in BOCM. Most likely, you'll find one of the pre-defined styles will
suit your needs, but if not, this section will describe how to set up
basic editing configurations. *Note Styles:: for an explanation of how
to set up named styles.
As mentioned previously, the variable `c-offsets-alist' is an
association list between syntactic symbols and the offsets to be applied
for those symbols. In fact, these offset values can be an integer, a
function or variable name, or one of the following symbols: `+', `-',
`++', `--', `*', or `/'. These symbols describe offset in multiples of
the value of the variable `c-basic-offset'. By defining a style's
indentation in terms of this fundamental variable, you can change the
amount of whitespace given to an indentation level while leaving the
same relationship between levels. Here are multiples of
`c-basic-offset' that the special symbols correspond to:
* `+ ' = `c-basic-offset' times 1
* `- ' = `c-basic-offset' times -1
* `++' = `c-basic-offset' times 2
* `--' = `c-basic-offset' times -2
* `* ' = `c-basic-offset' times 0.5
* `/ ' = `c-basic-offset' times -0.5
So, for example, because most of the default offsets are defined in
terms of `+', `-', and `0', if you like the general indentation style,
but you use 4 spaces instead of 2 spaces per level, you can probably
achieve your style just by changing `c-basic-offset' like so (in your
`.emacs' file)(1):
(setq-default c-basic-offset 4)
This would change
int add( int val, int incr, int doit )
{
if( doit )
{
return( val + incr );
}
return( val );
}
int add( int val, int incr, int doit )
{
if( doit )
{
return( val + incr );
}
return( val );
}
To change indentation styles more radically, you will want to change
the value associated with the syntactic symbols in the
`c-offsets-alist' variable. First, I'll show you how to do that
interactively, then I'll describe how to make changes to your `.emacs'
file so that your changes are more permanent.
* Menu:
* Interactive Customization::
* Permanent Customization::
* Styles::
* Advanced Customizations::
---------- Footnotes ----------
(1) The reason you need to use `setq-default' instead of `setq' is
that `c-basic-offset' is a buffer local variable, as are most of the
`cc-mode' configuration variables. If you were to put this code in,
e.g. your `c-mode-common-hook' function, you could use `setq'.
File: ccmode, Node: Interactive Customization, Next: Permanent Customization, Up: Customizing Indentation
Interactive Customization
=========================
As an example of how to customize indentation, let's change the
style of example 2 above from:
1: int add( int val, int incr, int doit )
2: {
3: if( doit )
4: {
5: return( val + incr );
6: }
7: return( val );
8: }
1: int add( int val, int incr, int doit )
2: {
3: if( doit )
4: {
5: return( val + incr );
6: }
7: return( val );
8: }
In other words, we want to change the indentation of braces that
open a block following a condition so that the braces line up under the
conditional, instead of being indented. Notice that the construct we
want to change starts on line 4. To change the indentation of a line,
we need to see which syntactic component affect the offset calculations
for that line. Hitting `C-c C-s' on line 4 yields:
((substatement-open . 46))
so we know that to change the offset of the open brace, we need to
change the indentation for the `substatement-open' syntactic symbol.
To do this interactively, just hit `C-c C-o' (`c-set-offset'). This
prompts you for the syntactic symbol to change, providing a reasonable
default. In this case, the default is `substatement-open', which is
just the syntactic symbol we want to change!
After you hit return, `cc-mode' will then prompt you for the new
offset value, with the old value as the default. The default in this
case is `+', so hit backspace to delete the `+', then hit `0' and
`RET'. This will associate the offset 0 with the syntactic symbol
`substatement-open' in the `c-offsets-alist' variable.
To check your changes quickly, just hit `C-c C-q' (`c-indent-defun')
to reindent the entire function. The example should now look like:
1: int add( int val, int incr, int doit )
2: {
3: if( doit )
4: {
5: return( val + incr );
6: }
7: return( val );
8: }
Notice how just changing the open brace offset on line 4 is all we
needed to do. Since the other affected lines are indented relative to
line 4, they are automatically indented the way you'd expect. For more
complicated examples, this may not always work. The general approach to
take is to always start adjusting offsets for lines higher up in the
file, then re-indent and see if any following lines need further
adjustments.
File: ccmode, Node: Permanent Customization, Next: Styles, Prev: Interactive Customization, Up: Customizing Indentation
Permanent Indentation
=====================
To make this change permanent, you need to add some lisp code to your
`.emacs' file. `cc-mode' provides four hooks that you can use to
customize your language editing styles. Four language specific hooks
are provided, according to Emacs major mode conventions: `c-mode-hook',
`c++-mode-hook', `objc-mode-hook', and `java-mode-hook'. These get run
as the last thing when you enter `c-mode', `c++-mode', `objc-mode', or
`java-mode-hook' respectively. `cc-mode' also provides a hook called
`c-mode-common-hook' which is run by all three modes *before* the
language specific hook. Thus, to make changes consistently across all
supported `cc-mode' modes, use `c-mode-common-hook'. Most of the
examples in this section will assume you are using the common hook.
Here's a simplified example of what you can add to your `.emacs'
file to make the changes described in the previous section (*Note
Interactive Customization::) more permanent. See the Emacs manuals for
more information on customizing Emacs via hooks. *Note Sample .emacs
File:: for a more complete sample `.emacs' file. (1)
(defun my-c-mode-common-hook ()
;; my customizations for all of c-mode, c++-mode, objc-mode, java-mode
(c-set-offset 'substatement-open 0)
;; other customizations can go here
)
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
For complex customizations, you will probably want to set up a
*style* that groups all your customizations under a single name.
The offset value can also be a function, and this is how power users
gain enormous flexibility in customizing indentation. *Note Advanced
Customizations:: for details.
---------- Footnotes ----------
(1) The use of `add-hook' in this example only works for Emacs 19.
Workarounds are available if you are using Emacs 18.
File: ccmode, Node: Styles, Next: Advanced Customizations, Prev: Permanent Customization, Up: Customizing Indentation
Styles
======
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 on C code. Some shops are more lenient, allowing some
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. This
chapter describes how to set up styles and how to edit your C code
using styles.
* Menu:
* Built-in Styles::
* Adding Styles::
* File Styles::
File: ccmode, Node: Built-in Styles, Next: Adding Styles, Up: Styles
Built-in Styles
---------------
If you're lucky, one of `cc-mode''s built-in styles might be just
what you're looking for. Some of the most common C and C++ styles are
already built-in. These include:
* `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' - *<TBD> Anybody know anything about the history of this
style?*
* `stroustrup' - The classic Stroustrup style for C++ code.
* `whitesmith' - *<TBD> Anybody know anything about the history of
this style?*
* `ellemtel' - Popular C++ coding standards as defined by
"Programming in C++, Rules and Recommendations", Erik Nyquist and
Mats Henricson, Ellemtel (1).
* `java' - The style for editing Java code. Note that this style is
automatically installed when you enter `java-mode'.
* `CC-MODE' - Style that encapsulates the default values of the
`cc-mode' variables. See below for details.
If you'd like to experiment with these built-in styles you can simply
type the following in a `cc-mode' buffer:
`M-x c-set-style RET STYLE-NAME RET'
Note that all style names are case insensitive, even the ones you
define.
Setting a style in this way does *not* automatically re-indent your
file. For commands that you can use to view the effect of your changes,
see *Note Indentation Commands::.
Once you find a built-in style you like, you can make the change
permanent by adding a call to your `.emacs' file. Let's say for
example that you want to use the `ellemtel' style in all your files.
You would add this:
(defun my-c-mode-common-hook ()
;; use Ellemtel style for all C, C++, and Objective-C code
(c-set-style "ellemtel")
;; other customizations can go here
)
(add-hook 'c-mode-common-hook 'my-c-mode-common-hook)
There is one other special style you can use, called `CC-MODE'.
This is a style that is calculated by `cc-mode' when it starts up. The
`CC-MODE' style is also special because all other styles implicitly
inherit from it; in other words, whenever you set a style, `cc-mode'
first re-instates the `CC-MODE' style, then applies your new style
configurations.
The `CC-MODE' style exists because once `cc-mode' initializes, it
institutes the `gnu' style for compatibility with BOCM's defaults. Any
customizations you make in mode hooks will be based on the `gnu' style,
unless you first do a `c-set-style' to `CC-MODE' or some other built-in
style.
---------- Footnotes ----------
(1) This document is ftp'able from `euagate.eua.ericsson.se'
File: ccmode, Node: Adding Styles, Next: File Styles, Prev: Built-in Styles, Up: Styles
Adding Styles
-------------
If none of the built-in styles is appropriate, you'll probably want
to add a new style definition. Styles are kept in the `c-style-alist'
variable, but you probably won't want to modify this variable directly.
`cc-mode' provides a function, called `c-add-style', that you can use
to easily add new styles or update existing styles. This function
takes two arguments, a STYLENAME string, and an association list
DESCRIPTION of style customizations. If STYLENAME is not already in
`c-style-alist', the new style is added, otherwise the style already
associated with STYLENAME is changed to the new DESCRIPTION. This
function also takes an optional third argument, which if non-`nil',
automatically institutes the new style in the current buffer.
The sample `.emacs' file provides a concrete example of how a new
style can be added and automatically set. *Note Sample .emacs File::.
File: ccmode, Node: File Styles, Prev: Adding Styles, Up: Styles
File Styles
-----------
The Emacs manual describes how you can customize certain variables
on a per-file basis by including a "Local Variable" block at the end of
the file. So far, you've only seen a functional interface to
`cc-mode', which is highly inconvenient for use in a Local Variable
block. `cc-mode' provides two variables that make it easier for you to
customize your style on a per-file basis.
The variable `c-file-style' can be set to a style name string as
described in *Note Built-in Styles::. When the file is visited,
`cc-mode' will automatically set the file's style to this style using
`c-set-style'.
Another variable, `c-file-offsets', takes an association list
similar to what is allowed in `c-offsets-alist'. When the file is
visited, `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').
File: ccmode, Node: Advanced Customizations, Prev: Styles, Up: Customizing Indentation
Advanced Customizations
=======================
For most users, `cc-mode' will support their coding styles with very
little need for customizations. Usually, one of the standard styles
defined in `c-style-alist' will do the trick. At most, perhaps one of
the syntactic symbol offsets will need to be tweaked slightly, or maybe
`c-basic-offset' will need to be changed. However, some styles require
a more advanced ability for customization, and one of the real
strengths of `cc-mode' is that the syntactic analysis model provides a
very flexible framework for customizing indentation. This allows you to
perform special indentation calculations for situations not handled by
the mode directly.
* Menu:
* Custom Indentation Functions::
* Custom Brace and Colon Hanging::
* Customizing Semi-colons and Commas::
* Other Special Indentations::