Go to the first, previous, next, last section, table of contents.

Your `.emacs' File

"You don't have to like Emacs to like it" -- this seemingly paradoxical statement is the secret of GNU Emacs. The plain, `out of the box' Emacs is a generic tool. Most people who use it, customize it to suit themselves.

GNU Emacs is mostly written in Emacs Lisp; this means that by writing expressions in Emacs Lisp you can change or extend Emacs.

There are those who appreciate Emacs's default configuration. After all, Emacs starts you in C mode when you edit a C file, starts you in Fortran mode when you edit a Fortran file, and starts you in Fundamental mode when you edit an unadorned file. This all makes sense, if you do not know who is going to use Emacs. Who knows what a person hopes to do with an unadorned file? Fundamental mode is the right default for such a file, just as C mode is the right default for editing C code. But when you do know who is going to use Emacs--you, yourself--then it makes sense to customize Emacs.

For example, I seldom want Fundamental mode when I edit an otherwise undistinguished file; I want Text mode. This is why I customize Emacs: so it suits me.

You can customize and extend Emacs by writing or adapting a `~/.emacs' file. This is your personal initialization file; its contents, written in Emacs Lisp, tell Emacs what to do.

This chapter describes a simple `.emacs' file; for more information, see section `The Init File' in The GNU Emacs Manual, and section `The Init File' in The GNU Emacs Lisp Reference Manual.

Site-wide Initialization Files

In addition to your personal initialization file, Emacs automatically loads various site-wide initialization files, if they exist. These have the same form as your `.emacs' file, but are loaded by everyone.

Two site-wide initialization files, `site-load.el' and `site-init.el', are loaded into Emacs and then `dumped' if a `dumped' version of Emacs is created, as is most common. (Dumped copies of Emacs load more quickly. However, once a file is loaded and dumped, a change to it does not lead to a change in Emacs unless you load it yourself or re-dump Emacs. See section `Building Emacs' in The GNU Emacs Lisp Reference Manual, and the `INSTALL' file.)

Three other site-wide initialization files are loaded automatically each time you start Emacs, if they exist. These are `site-start.el', which is loaded before your `.emacs' file, and `default.el', and the terminal type file, which are both loaded after your `.emacs' file.

Settings and definitions in your `.emacs' file will overwrite conflicting settings and definitions in a `site-start.el' file, if it exists; but the settings and definitions in a `default.el' or terminal type file will overwrite those in your `.emacs' file. (You can prevent interference from a terminal type file by setting term-file-prefix to nil. See section A Simple Extension: line-to-top-of-window.)

The `INSTALL' file that comes in the distribution contains descriptions of the `site-init.el' and `site-load.el' files.

The `loadup.el', `startup.el', and `loaddefs.el' files control loading. These files are in the `lisp' directory of the Emacs distribution and are worth perusing.

The `loaddefs.el' file contains a good many suggestions as to what to put into your own `.emacs' file, or into a site-wide initialization file.

Setting Variables for One Session

My copy of Emacs version 19.23 has 392 options that you can set with the edit-options command. These `options' are no more than variables such as we have seen earlier and defined using defvar.

Emacs determines whether a variable is intended to be easily settable by looking at the first character in its documentation string; if the first character is an asterisk, `*', the variable is a user-settable option. (See section Initializing a Variable with defvar.)

The edit-options command lists all the variables in Emacs that the people who wrote the Emacs Lisp libraries think ought to be readily settable. It provides an easy-to-use interface for resetting these variables.

On the other hand, options set using edit-options are set only for the duration of your editing session. The new values are not saved between sessions. Each time Emacs starts, it reads the original defvar value in its source code. To carry a changed setting from one session to the next, you need to use a setq expression within a `.emacs' file or other file that you load every time you start a session.

For me, the major use of the edit-options command is to suggest variables I might want to set in my `.emacs' file. I urge you to look through the list.

See section `Editing Variable Values' in The GNU Emacs Manual, for more information.

Beginning a `.emacs' File

When you start Emacs, it loads your `.emacs' file unless you tell it not to by specifying `-q' on the command line. (The emacs -q command gives you a plain, out-of-the-box Emacs.)

A `.emacs' file contains Lisp expressions. Often, these are no more than expressions to set values; sometimes they are function definitions.

See section `The Init File `~/.emacs'' in The GNU Emacs Manual, for a short description of initialization files.

This chapter goes over some of the same ground, but is a walk among extracts from a complete, long-used `.emacs' file--my own.

The first part of the file consists of comments: reminders to myself. By now, of course, I remember these things, but when I started, I did not.

;;;; Bob's .emacs file
; Robert J. Chassell
; 26 September 1985 

Look at that date! I started this file a long time ago. I have been adding to it ever since.

; Each section in this file is introduced by a
; line beginning with four semicolons; and each
; entry is introduced by a line beginning with
; three semicolons.

This describes the usual conventions for comments in Emacs Lisp. Everything on a line that follows a semicolon is a comment. Two, three, and four semicolons are used as section and subsection markers. (See section `Comments' in The GNU Emacs Lisp Reference Manual, for more about comments.)

;;;; The Help Key
; Control-h is the help key; 
; after typing control-h, type a letter to
; indicate the subject about which you want help.
; For an explanation of the help facility, 
; type control-h three times in a row.

Just remember: type C-h three times for help.

; To find out about any mode, type control-h m
; while in that mode.  For example, to find out
; about mail mode, enter mail mode and then type
; control-h m.

`Mode help', as I call this, is very helpful. Usually, it tells you all you need to know.

Of course, you don't need to include comments like these in your `.emacs' file. I included them in mine because I kept forgetting about Mode help or the conventions for comments--but I was able to remember to look here to remind myself.

Text and Auto Fill Mode

Now we come to the part that `turns on' Text mode and Auto Fill mode.

;;; Text mode and Auto Fill mode
; The next two lines put Emacs into Text mode
; and Auto Fill mode, and are for writers who
; want to start writing prose rather than code.
 
(setq default-major-mode 'text-mode)
(add-hook 'text-mode-hook 'turn-on-auto-fill)

Here is the first part of this `.emacs' file that does something besides remind a forgetful human!

The first of the two lines in parentheses tells Emacs to turn on Text mode when you find a file, unless that file should go into some other mode, such as C mode.

When Emacs reads a file, it looks at the extension to the file name, if any. (The extension is the part that comes after a `.'.) If the file ends with a `.c' or `.h' extension then Emacs turns on C mode. Also, Emacs looks at first nonblank line of the file; if the line says `-*- C -*-', Emacs turns on C mode. Emacs possesses a list of extensions and specifications that it uses automatically. In addition, Emacs looks near the last page for a per-buffer, "local variables list", if any.

See sections "How Major Modes are Chosen" and "Local Variables in Files" in The GNU Emacs Manual, for information.

Now, back to the `.emacs' file.

Here is the line again; how does it work?

(setq default-major-mode 'text-mode)

This line is a short, but complete Emacs Lisp expression.

We are already familiar with setq. It sets the following variable, default-major-mode, to the subsequent value, which is text-mode. The single quote mark before text-mode tells Emacs to deal directly with the text-mode variable, not with whatever it might stand for. See section Setting the Value of a Variable, for a reminder of how setq works. The main point is that there is no difference between the procedure you use to set a value in your `.emacs' file and the procedure you use anywhere else in Emacs.

Here is the second line:

(add-hook 'text-mode-hook 'turn-on-auto-fill)

In this line, the add-hook command, adds turn-on-auto-fill to the variable called text-mode-hook. turn-on-auto-fill is the name of a program, that, you guessed it!, turns on Auto Fill mode.

Every time Emacs turns on Text mode, Emacs runs the commands `hooked' onto Text mode. So every time Emacs turns on Text mode, Emacs also turns on Auto Fill mode.

In brief, the first line causes Emacs to enter Text mode when you edit a file, unless the file name extension, first non-blank line, or local variables tell Emacs otherwise.

Text mode among other actions, sets the syntax table to work conveniently for writers. In Text mode, Emacs considers an apostrophe as part of a word like a letter; but Emacs does not consider a period or a space as part of a word. Thus, M-f moves you over `it's'. On the other hand, in C mode, M-f stops just after the `t' of `it's'.

The second line causes Emacs to turn on Auto Fill mode when it turns on Text mode. In Auto Fill mode, Emacs automatically breaks a line that is too wide and brings the excessively wide part of the line down to the next line. Emacs breaks lines between words, not within them.

When Auto Fill mode is turned off, lines continue to the right as you type them. Depending on how you set the value of truncate-lines, the words you type either disappear off the right side of the screen, or else are shown, in a rather ugly and unreadable manner, as a continuation line on the screen.

Mail Aliases

Here is a setq to `turn on' mail aliases, along with more reminders.

;;; Mail mode
; To enter mail mode, type `C-x m'
; To enter RMAIL (for reading mail), 
; type `M-x rmail'

(setq mail-aliases t)

This setq command sets the value of the variable mail-aliases to t. Since t means true, the line says, in effect, "Yes, use mail aliases."

Mail aliases are convenient short names for long email addresses or for lists of email addresses. The file where you keep your `aliases' is `~/.mailrc'. You write an alias like this:

alias geo george@foobar.wiz.edu

When you write a message to George, address it to `geo'; the mailer will automatically expand `geo' to the full address.

Indent Tabs Mode

By default, Emacs inserts tabs in place of multiple spaces when it formats a region. (For example, you might indent many lines of text all at once with the indent-region command.) Tabs look fine on a terminal or with ordinary printing, but they produce badly indented output when you use TeX or Texinfo since TeX ignores tabs.

The following turns off Indent Tabs mode:

;;; Prevent Extraneous Tabs
(setq-default indent-tabs-mode nil)

Note that this line uses setq-default rather than the setq command that we have see before. The setq-default command sets values only in buffers that do not have their own local values for the variable.

See sections "Tabs vs. Spaces" and "Local Variables in Files" in The GNU Emacs Manual.

Some Keybindings

Now for some personal keybindings:

;;; Compare windows
(global-set-key "\C-cw" 'compare-windows)

compare-windows is a nifty command that compares the text in your current window with text in the next window. It makes the comparison by starting at point in each window, moving over text in each window as far as they match. I use this command all the time.

This also shows how to set a key globally, for all modes.

The command is global-set-key. It is followed by the keybinding. In a `.emacs' file, the keybinding is written as shown: \C-c stands for `control-c', which means `press the control key and the c key at the same time'. The w means `press the w key'. The keybinding is surrounded by double quotation marks. In documentation, you would write this as C-c w. (If you were binding a META key, such as M-c, rather than a CTL key, you would write \M-c. See section `Rebinding Keys in Your Init File' in The GNU Emacs Manual, for details.)

The command invoked by the keys is compare-windows. Note that compare-windows is preceded by a single quote; otherwise, Emacs would first try to evaluate the symbol to determine its value.

These three things, the double quotation marks, the backslash before the `C', and the single quote mark are necessary parts of keybinding that I tend to forget. Fortunately, I have come to remember that I should look at my existing `.emacs' file, and adapt what is there.

As for the keybinding itself: C-c w. This combines the prefix key, C-c, with a single character, in this case, w. This set of keys, C-c followed by a single character, is strictly reserved for individuals' own use. If you ever write an extension to Emacs, please avoid taking any of these keys for public use. Create a key like C-c C-w instead. Otherwise, we will run out of `own' keys.

Here is another keybinding, with a comment:

;;; Keybinding for `occur'
; I use occur a lot, so let's bind it to a key:
(global-set-key "\C-co" 'occur)

The occur command shows all the lines in the current buffer that contain a match for a regular expression. Matching lines are shown in a buffer called `*Occur*'. That buffer serves as a menu to jump to occurrences.

Here is how to unbind a key, so it does not work:

;;; Unbind `C-x f'
(global-unset-key "\C-xf")

There is a reason for this unbinding: I found I inadvertently typed C-x f when I meant to type C-x C-f. Rather than find a file, as I intended, I accidentally set the width for filled text, almost always to a width I did not want. Since I hardly ever reset my default width, I simply unbound the key.

The following rebinds an existing key:

;;; Rebind `C-x C-b' for `buffer-menu'
(global-set-key "\C-x\C-b" 'buffer-menu)

By default, C-x C-b runs the list-buffers command. This command lists your buffers in another window. Since I almost always want to do something in that window, I prefer the buffer-menu command, which not only lists the buffers, but moves point into that window.

Loading Files

Many people in the GNU Emacs community have written extensions to Emacs. As time goes by, these extensions are often included in new releases. For example, the Calendar and Diary packages are now part of the standard Emacs version 19 distribution; they were not part of the standard Emacs version 18 distribution.

(Calc, which I consider a vital part of Emacs, would be part of the standard distribution except that it is so large it is packaged separately.)

You can use a load command to evaluate a complete file and thereby install all the functions and variables in the file into Emacs. For example:

(load "~/emacs/kfill")

This evaluates, i.e. loads, the `kfill.el' file (or if it exists, the faster, byte compiled `kfill.elc' file) from the `emacs' sub-directory of your home directory.

(`kfill.el' was adapted from Kyle E. Jones' `filladapt.el' package by Bob Weiner and "provides no muss, no fuss word wrapping and filling of paragraphs with hanging indents, included text from news and mail messages, and Lisp, C++, PostScript or shell comments." I use it all the time and hope it is incorporated into the standard distribution.)

If you load many extensions, as I do, then instead of specifying the exact location of the extension file, as shown above, you can specify that directory as part of Emacs's load-path. Then, when Emacs loads a file, it will search that directory as well as its default list of directories. (The default list is specified in `paths.h' when Emacs is built.)

The following command adds your `~/emacs' directory to the existing load path:

;;; Emacs Load Path
(setq load-path (cons "~/emacs" load-path))

Incidentally, load-library is an interactive interface to the load function. The complete function looks like this:

(defun load-library (library)
  "Load the library named LIBRARY.
This is an interface to the function `load'."
  (interactive "sLoad library: ")
  (load library))

The name of the function, load-library, comes from the use of `library' as a conventional synonym for `file'. The source for the load-library command is in the `files.el' library.

Another interactive command that does a slightly different job is load-file. See section `Libraries of Lisp Code for Emacs' in The GNU Emacs Manual, for information on the distinction between load-library and this command.

Autoloading

Instead of installing a function by loading the file that contains it, or by evaluating the function definition, you can make the function available but not actually install it until it is first called. This is called autoloading.

When you execute an autoloaded function, Emacs automatically evaluates the file that contains the definition, and then calls the function.

Emacs starts quicker with autoloaded functions, since their libraries are not loaded right away; but you need to wait a moment when you first use such a function, while its containing file is evaluated.

Rarely used functions are frequently autoloaded. The `loaddefs.el' library contains hundreds of autoloaded functions, from bookmark-set to wordstar-mode. Of course, you may come to use a `rare' function frequently. In this case, you should load that function's file with a load expression in your `.emacs' file.

In my `.emacs' file for Emacs version 19.23, I load 17 libraries that contain functions that would otherwise be autoloaded. (Actually, it would have been better to include these files in my `dumped' Emacs when I built it, but I forgot. See section `Building Emacs' in The GNU Emacs Lisp Reference Manual, and the `INSTALL' file for more about dumping.)

You may also want to include autoloaded expressions in your `.emacs' file. autoload is a built-in function that takes up to five arguments, the final three of which are optional. The first argument is the name of the function to be autoloaded; the second is the name of the file to be loaded. The third argument is documentation for the function, and the fourth tells whether the function can be called interactively. The fifth argument tells what type of object---autoload can handle a keymap or macro as well as a function (the default is a function).

Here is a typical example:

(autoload 'html-helper-mode
  "html-helper-mode" "Edit HTML documents" t)

This expression autoloads the html-helper-mode function. It takes it from the `html-helper-mode.el' file (or, if it exists, from the byte compiled file `html-helper-mode.elc'.) The file must be located in a directory specified by load-path. The documentation says that this is a mode to help you edit documents written in the HyperText Markup Language. You can call this mode interactively by typing M-x html-helper-mode. (You need to duplicate the function's regular documentation in the autoload expression because the regular function is not yet loaded, so its documentation is not available.)

See section `Autoload' in The GNU Emacs Lisp Reference Manual, for more information.

A Simple Extension: line-to-top-of-window

Here is a simple extension to Emacs that moves the line point is on to the top of the window. I use this all the time, to make text easier to read.

You can put the following code into a separate file and then load it from your `.emacs' file, or you can include it within your `.emacs' file.

Here is the definition:

;;; Line to top of window;  
;;; replace three keystroke sequence  C-u 0 C-l
(defun line-to-top-of-window ()
  "Move the line point is on to top of window."
  (interactive) 
  (recenter 0))

Now for the keybinding.

Although most of an Emacs version 18 `.emacs' file works with version 19, there are some differences (also, of course, there are new features in Emacs 19).

In version 19 Emacs, you can write a function key like this: `[f6]'. In version 18, you must specify the key strokes sent by the keyboard when you press that function key. For example, a Zenith 29 keyboard sends ESC P when I press its sixth function key; an Ann Arbor Ambassador keyboard sends ESC O F. Write these keystrokes as `\eP' and `\eOF', respectively.

In my version 18 `.emacs' file, I bind line-to-top-of-window to a key that depends on the type of terminal:

(defun z29-key-bindings () 
  "Function keybindings for Z29 terminal."
  ;; ...
  (global-set-key "\eP" 'line-to-top-of-window))

(defun aaa-key-bindings () 
  "Function keybindings for Ann Arbor Ambassador"
  ;; ...
  (global-set-key "\eOF" 'line-to-top-of-window))

(You can find out what a function key sends by typing the function key, and then typing C-h l (view-lossage) which displays the last 100 input keystrokes.)

After specifying the key bindings, I evaluate an expression that chooses among keybindings, depending on the type of terminal I am using. However, before doing that, I turn off the predefined, default terminal-specific keybindings, which overwrite bindings in the `.emacs' if they clash.

;;; Turn Off Predefined Terminal Keybindings

; The following turns off the predefined 
; terminal-specific keybindings such as the
; vt100 keybindings in lisp/term/vt100.el.  
; If there are no predefined terminal
; keybindings, or if you like them,
; comment this out.

(setq term-file-prefix nil)

Here is the selection expression itself:

(let ((term (getenv "TERM")))
  (cond 
   ((equal term "z29") (z29-key-bindings))
   ((equal term "aaa") (aaa-key-bindings))
   (t (message
       "No binding for terminal type %s."
       term))))

In Emacs version 19, function keys (as well as mouse button events and non-ASCII characters) are written within square brackets, without quotation marks. I bind line-to-top-of-window to my F6 function key like this:

(global-set-key [f6] 'line-to-top-of-window)

Much simpler!

For more information, see section `Rebinding Keys in Your Init File' in The GNU Emacs Manual.

If you run both Emacs 18 and Emacs 19, you can select which code to evaluate with the following conditional:

(if (string=
     (int-to-string 18)
     (substring (emacs-version) 10 12))
    ;; evaluate version 18 code
    (progn
       ... )
  ;; else evaluate version 19 code
  ...

Keymaps

Emacs uses keymaps to record which keys call which commands. Specific modes, such as C mode or Text mode, have their own keymaps; the mode-specific keymaps override the global map that is shared by all buffers.

The global-set-key function binds, or rebinds, the global keymap. For example, the following binds the key C-c C-l to the function line-to-top-of-window:

(global-set-key "\C-c\C-l" 'line-to-top-of-window))

Mode-specific keymaps are bound using the define-key function, which takes a specific keymap as an argument, as well as the key and the command. For example, my `.emacs' file contains the following expression to bind the texinfo-insert-@group command to C-c C-c g:

(define-key texinfo-mode-map "\C-c\C-cg"
  'texinfo-insert-@group)

The texinfo-insert-@group function itself is a little extension to Texinfo mode that inserts `@group' into a Texinfo file. I use this command all the time and prefer to type the three strokes C-c C-c g rather than the six strokes @ g r o u p. (`@group' and its matching `@end group' are commands that keep all enclosed text together on one page; many multi-line examples in this book are surrounded by `@group ... @end group'.)

Here is the texinfo-insert-@group function definition:

(defun texinfo-insert-@group ()
  "Insert the string @group in a Texinfo buffer."
  (interactive)
  (beginning-of-line)
  (insert "@group\n"))

(Of course, I could have used Abbrev mode to save typing, rather than write a function to insert a word; but I prefer key strokes consistent with other Texinfo mode key bindings.)

You will see numerous define-key expressions in `loaddefs.el' as well as in the various mode libraries, such as `c-mode.el' and `lisp-mode.el'.

See section `Customizing Key Bindings' in The GNU Emacs Manual, and section `Keymaps' in The GNU Emacs Lisp Reference Manual, for more information about keymaps.

X11 Colors

You can specify colors when you use Emacs version 19 with the MIT X Windowing system. (All the previous examples should work with both Emacs version 18 and Emacs version 19; this works only with Emacs version 19.)

I hate the default colors and specify my own.

Most of my specifications are in various X initialization files. I wrote notes to myself in my `.emacs' file to remind myself what I did:

;; I use TWM for window manager;
;; my ~/.xsession file specifies:
;    xsetroot -solid navyblue -fg white

Actually, the root of the X window is not part of Emacs at all, but I like the reminder anyhow.

;; My ~/.Xresources file specifies:
;     XTerm*Background:    sky blue
;     XTerm*Foreground:    white
;     emacs*geometry:      =80x40+100+0
;     emacs*background:    blue
;     emacs*foreground:    grey97
;     emacs*cursorColor:   white
;     emacs*pointerColor:  white

Here are the expressions in my `.emacs' file that set values:

;;; Set highlighting colors for isearch and drag
(set-face-foreground 'highlight "white" )
(set-face-background 'highlight "slate blue")
(set-face-background 'region    "slate blue")
(set-face-background
 'secondary-selection "turquoise")

;; Set calendar highlighting colors
(setq calendar-load-hook
      '(lambda () 
         (set-face-foreground 'diary-face   "skyblue")
         (set-face-background 'holiday-face "slate blue")
         (set-face-foreground 'holiday-face "white")))

The various shades of blue soothe my eye and prevent me from seeing the screen flicker.

V19 Miscellaneous

Here are a few miscellaneous settings for version 19 Emacs:

A Modified Mode Line

Finally, a feature I really like: a modified mode line.

Since I sometimes work over a network, I replaced the `Emacs: ' that is normally written on the left hand side of the mode line by the name of the system--otherwise, I forget which machine I am using. In addition, I list the default directory lest I lose track of where I am, and I specify the line point is on, with `Line' spelled out. My `.emacs' file looks like this:

(setq mode-line-system-identification  
  (substring (system-name) 0
             (string-match "\\..+" (system-name))))

(setq default-mode-line-format
      (list ""
            'mode-line-modified
            "<"
            'mode-line-system-identification
            "> "
            "%14b"
            " "
            'default-directory
            " "
            "%[(" 
            'mode-name 
            'minor-mode-alist 
            "%n" 
            'mode-line-process  
            ")%]--" 
             "Line %l--"
            '(-3 . "%P")
            "-%-"))

;; Start with new default.
(setq mode-line-format default-mode-line-format)

I set the default mode line format so as to permit various modes, such as Info, to override it. Many elements in the list are self-explanatory: mode-line-modified is a variable the tells whether the buffer has been modified, mode-name tells the name of the mode, and so on.

The `"%14b"' displays the current buffer name (using the buffer-name function with which we are familiar); the `14' specifies the maximum number of characters that will be displayed. When a name has fewer characters, whitespace is added to fill out to this number. `%[' and `%]' cause a pair of square brackets to appear for each recursive editing level. `%n' says `Narrow' when narrowing is in effect. `%P' tells you the percentage of the buffer that is above the bottom of the window, or `Top', `Bottom', or `All'. (A lower case `p' tell you the percentage above the top of the window.) `%-' inserts enough dashes to fill out the line.

In and after Emacs version 19.29, you can use frame-title-format to set the title of an Emacs frame. This variable has the same structure as mode-line-format.

Mode line formats are described in section `Mode Line Format' in The GNU Emacs Lisp Reference Manual.

Remember, "You don't have to like Emacs to like it" -- your own Emacs can have different colors, different commands, and different keys than a default Emacs.

On the other hand, if you want to bring up a plain `out of the box' Emacs, with no customization, type:

emacs -q

This will start an Emacs that does not load your `~/.emacs' initialization file. A plain, default Emacs. Nothing more.


Go to the first, previous, next, last section, table of contents.