Emacs editing environment, Part 6: Customize your Emacs world

Get going with this famous open source editor

This tutorial, the sixth in a series, walks you through some of the useful ways you can customize and configure the Emacs environment. Learn how to change everything about the Emacs environment to your liking, from the behavior of minor modes to the default key bindings. Along the way, figure out how to set variables, make all your customizations automatic with a startup file, save and recall any window and frame customizations that you make, and use the easy customizer that comes built into Emacs.

Before you start

Learn what to expect from this tutorial, and how to get the most out of it.

About this series

The Emacs editing environment is a favorite of UNIX® developers. It's known around the world as the king of editors, but many users find it has a bit of a learning curve. The Emacs environment doesn't seem intuitive at first glance, and it doesn't work like other editors and word processors. But learning Emacs doesn't have to be difficult. Once you get going, you'll see how intuitive it is and become more comfortable with it after each use. This tutorial series (see Resources) shows you the way, taking you from the basics of Emacs, such as its features, philosophy, key-command layout, and methods for editing text, through many of its powerful editing features.

After completing this series (see Resources), you'll be able to comfortably use Emacs for everyday editing, be well on your way to Emacs proficiency, and have a good feel for many of the advanced capabilities of Emacs.

About this tutorial

This is the sixth in a series of tutorials on learning Emacs. Previous tutorials in this series took you through the basics; this intermediate-level, hands-on tutorial builds on what you learned in the early tutorials, and shows readers already familiar with the rudimentary controls of Emacs how to customize and tool the system for their specific needs.

In this tutorial, you learn how to customize the system in various ways, changing its behavior and getting it to work the way you want it to. You also learn how to set and examine the Emacs variables that change the behavior of the application, change the way keys and modes work, make your customizations happen automatically with Emacs Lisp code in an init file, remember your window and frame modifications, and use the built-in customize buffer utility for an easy approach to changing and managing various Emacs settings.

Objectives

This tutorial shows you how to customize and configure your Emacs editing environment, from key bindings to the behavior of modes.

After working through this tutorial, you'll know how to change every aspect of the Emacs editing environment, and how to save your customizations so that they can be recalled later.

Prerequisites

Before working through this tutorial, you should complete the previous tutorials in this series. They lay down the basic foundation, and explain many of the Emacs concepts you use in this tutorial (see the Resources section).

The special Emacs notation for representing keystrokes, which is used in this tutorial and throughout the series, is described in the introduction of the first tutorial of the series, "Learning the Emacs editing environment, Part 1: The basics of Emacs" (see Resources).

Although this tutorial is written for all levels of UNIX expertise, it's helpful if you have at least a rudimentary understanding of the UNIX file system:

  • Files

  • Directories

  • Permissions

  • File system hierarchy

System requirements

This tutorial requires a user account on any UNIX-based system that has a recent copy of Emacs installed.

There are several varieties of Emacs; the original and most popular is GNU Emacs, which is published online by the GNU Project (see Resources).

You should have a recent copy of GNU Emacs—one that is at version 20 or greater. Versions 20 and 21 are the most commonly available, and development snapshots of version 22 are also available. This tutorial works with any of these versions for Emacs. If your system is running something older, it's time to upgrade.

To know what version of Emacs you have running, use the GNU-style --version flag:

$ emacs --version
GNU Emacs 22.0.91.1
Copyright (C) 2006 Free Software Foundation, Inc.
GNU Emacs comes with ABSOLUTELY NO WARRANTY.
You may redistribute copies of Emacs
under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.
$

Because a portion of this tutorial deals with graphical elements of the Emacs operation in the X Window System environment, you should also have an X server up and running.


Set Emacs variables

The quickest and easiest way to customize some aspect of your Emacs world is to set an Emacs variable. Variables affect the way various aspects of Emacs work; they are Emacs Lisp symbols, are referenced by their name, and usually have a default value. Some variables take numeric values or strings, whereas others are true or false: If a value of a variable is set to nil, its value is false; the value t denotes true.

You can change the value of any variable at any time in an Emacs session. Do this to set a local variable for a particular buffer, to make a change to a global variable that applies only to the current session, or to test the behaviors of different values.

For instance, in the second tutorial in this series (see Resources), you learned about the fill-paragraph function (bound to M-q), which fills the paragraph at point. The width this function fills to is contained in the fill-column variable and, like any Emacs variable, you can display its contents and change it.

To begin, start Emacs with a buffer corresponding to a new file:

$ emacs bee

Now, insert a line of text in your new buffer:

The busy bee has no time for sorrow.

Fill the current paragraph (the line you just inserted) by typing M-q to run the fill-paragraph function.

When you type this, it looks like nothing happened—that's because the default width, in characters, that Emacs uses for filling text in a buffer is longer than the paragraph you just typed. You can verify that by looking at the contents of the fill-width variable.

Display the value of a variable

Use the describe-variable function to get the value of a variable. When you run it, Emacs opens a new window that contains the given current value of the variable. A description of the variable, if available, is also provided. This function is bound to the C-h v keystroke.

Try getting the value of the fill-width variable by typing C-h v fill-width.

Once you do this, you should see a new window in your Emacs session that contains the text of Listing 1.

Listing 1. Output of Emacs describe-variable function showing the value of the fill-width variable
fill-column's value is 70

Documentation:
*Column beyond which automatic line-wrapping should happen.
Automatically becomes buffer-local when set in any fashion.

You can customize this variable.

From this output, you can tell that the fill-paragraph function won't break to a new line until 70 characters are reached, so the short paragraph you've typed isn't long enough to wrap.

Set a variable

Like any Emacs variable, you can change the value of fill-column. Use the set-variable function to do that—when you run it, it asks for the name of a variable and the value you want to give it.

Try setting the value of fill-column to 10, as in Listing 2.

Listing 2. Change the value of the fill-column variable using the Emacs set-variable function
M-x set-variable Enter
Set variable: fill-column Enter
Set fill-column to value: 10 Enter

Now, fill the paragraph again: Make sure the cursor is at the end of the line you just typed, and then type M-q to run the fill-paragraph function.

Notice how the paragraph is filled so that no lines are longer than 10 characters, as in Listing 3.

Listing 3. Sample paragraph wrapped after the fill-width variable is set to 10
The busy
bee has no
time for
sorrow.

Try it again after setting the value of fill-column to 4, using the process given in Listing 2.

After filling the paragraph with another M-q, you see that the words have wrapped differently, as in Listing 4.

Listing 4. Sample paragraph wrapped after the fill-width variable is set to 4
The
busy
bee
has
no
time
for
sorrow.

Because fill-column is a local variable, any changes you make to it apply only to the current buffer. Every buffer in an Emacs session has its own fill-column variable; each of these can be set to a different value.

Try selecting all the text you've inserted and pasting it to a new buffer:

C-space M-< M-w C-x b cee Enter C-y

Once you type this, you should have a copy of the newly filled paragraph from the bee buffer copied over to a new, unsaved buffer named cee.

Type M-q to fill it. It fills back to a single line and looks like the single line you typed at the beginning.

By asking Emacs to show you the contents of the variables, you can also verify that the values of fill-column are different in both buffers.

Type C-h v fill-column Enter to show the value of this buffer's fill-column variable, which should be 70.

After you do this, ask Emacs to show you the value of the bee buffer's fill-column variable: type C-x b Enter C-h v fill-column Enter to verify that it's still set to 4. As shown in Figure 1, the *Help* buffer that's displayed also tells you that the local value of this variable differs from its global value.

Figure 1. Showing the value of the Emacs fill-column variable after it was changed locally inside a buffer
Showing the value of the Emacs fill-column variable after it was changed locally inside a buffer

Use and know common Emacs variables

Emacs has many variables that affect and alter its behavior. Table 1 lists some of the more commonly modified variables and describes their function.

Table 1. Summary of common Emacs variables
VariableDescription
auto-mode-alistIf set to nil, automatic selection of major mode based on file name extension is turned off. Its default value is a list of file name extensions and corresponding modes.
auto-save-defaultIf not set to nil, Emacs automatically saves a changed buffer to its corresponding file at preset intervals. Its default value is t.
auto-save-intervalContains the number of character changes after which Auto-save mode, if true, is invoked; the default value is 300.
calendar-latitudeContains the latitude value for the location of the user's workstation, in degrees; the default value is nil.
calendar-longitudeContains the longitude value for the location of the user's workstation, in degrees; the default value is nil.
calendar-location-nameContains the value for the location name (such as city, state, and country) for the location of the user's workstation; the default value is nil.
colon-double-spaceIf not set to nil, commands for filling text insert two spaces after a colon instead of one. The default value is nil.
command-line-argsContains the list of arguments used in the command line that executed the current Emacs session.
command-line-default-directoryContains the path name of the directory from which the current Emacs session was executed.
compare-ignore-caseIf not set to nil, Emacs ignores differences in uppercase and lowercase letters when running the compare-windows function, as described in fifth installment of this series (see Resources). The default value is nil.
confirm-kill-emacsIf set to nil, Emacs doesn't ask for a confirmation when exiting; otherwise, the exit verification might be customized as an Emacs Lisp function such as y-or-n-p (see the Make short answers possible section). The default value is nil.
default-justificationSets the default justification style. The value can be one of left, right, center, full, or none. The default value is left.
default-major-modeSelects the default major mode for new files or buffers. The default value is fundamental-mode.
display-time-24hr-formatIf set to t, Emacs displays time in 24-hour military format, instead of the standard 12-hour format with AM or PM suffix. The default value is nil.
display-time-day-and-dateIf not set to nil, Emacs displays time with the current day of the week, current month, and current day of the month, instead of just the hour and minute. The default value is nil.
fill-columnContains the number for the column on each line where text begins to be filled to the next line. The default value is 70.
initial-major-modeSpecifies the major mode to use for the *scratch* buffer on startup. The default value is lisp-interaction-mode.
inverse-videoIf not set to nil, Emacs inverts the display colors, if possible. The default value is nil.
kill-ringContains the contents of the Emacs kill ring, as described in third installment of this series (see Resources).
kill-ring-maxSets the number of allowable entries in the Emacs kill ring. The default value is 60.
kill-whole-lineIf not set to nil, the kill-line function (bound to C-k) kills the current line and its trailing newline character, if the function is executed at the very beginning of the line. The default value is nil.
make-backup-filesIf not set to nil, Emacs saves a backup of a buffer before any changes are made to a file of the same name but with a tilde character (~) appended to the end.
mark-ringContains the contents of the current mark ring of the buffer, as described in third installment of this series (see Resources).
mark-ring-maxContains the number of allowable entries in the mark ring. The default value is 16.
mouse-avoidance-modeContains a value describing the type of mouse-avoidance mode, as described in fifth installment of this series (see Resources). The default value is nil.
next-line-add-newlineIf not set to nil, Emacs adds a new line whenever the down arrow is pressed at the end of the buffer. The default value is nil (in more recent versions of Emacs).
scroll-bar-modeContains the value for the side of the Emacs frame on which to place the scroll bar: right or left. If set to nil, the scroll bar is turned off. The default value is left.
scroll-step Contains the number of lines to move through the buffer lines with the scroll-down and scroll-up functions (which are bound to the PgDn and PgUp keys by default). If set to 0, Emacs centers point in the middle of the window when scrolling.
show-trailing-whitespaceIf not set to nil, Emacs makes any whitespace at the end of lines in the current buffer visible. The default value is nil.
visible-bellIf not set to nil, Emacs makes the frame blink instead of ringing the audible system bell. The default value is nil.
x-cut-buffer-maxSets the maximum number of characters from the kill ring that are also stored in the X Window System cut buffer. The default value is 20000.

Customize your Emacs key bindings

As you know, Emacs functions are bound to keystroke combinations called key bindings; the standard Emacs bindings are made to be easy to use and remember—there's often a mnemonic hint associated with the key used in a binding—and fast to employ—they're set up so you can type any given keystroke combination quickly and with a minimum of hand motion.

But if you don't like them, you can change them. You can customize every key binding Emacs has: You can, if you desire, make A type a Z, or make C-f move the cursor backward and C-b move it forward. Although these aren't likely to be useful changes for most users, there could be many reconfigurations that you personally might find handy. Furthermore, Emacs has many, many more functions than it has default bindings—and many possible keystroke combinations aren't bound to any function.

If you use a particular function or group of functions frequently and they aren't bound to a keystroke (or if the keystrokes are bound to are less convenient than others), you can redefine them. Or if there's a function you don't use, you can remove its binding, freeing that keystroke for something else.

The global-set-key function binds a given function to a given keystroke, and makes it effective across all modes and buffers. Use it next to make a number of customizations and fixes.

Fix the Home and End keys

The Home and End keys are usually configured in two common ways in Emacs: Either they move the cursor to the beginning and ending of the current line, or they move the cursor to the beginning and ending of the current buffer.

See which of the two ways yours are bound: Press Home and End a few times each in your bee buffer.

Now that you know what these keys are bound to, try changing their bindings:

  • If your Home and End keys are bound to move to the beginning and ending of the current line, type:

    M-x global-set-key Enter
    Set key globally: Home
    Set key <home> to command: beginning-of-bufferM-x global-set-key
    Set key globally: End
    Set key <home> to command: end-of-buffer
  • If your Home and End keys are bound to move to the beginning and ending of the current buffer, type:

    M-x global-set-key
    Set key globally: Home
    Set key <home> to command: beginning-of-lineM-x global-set-key
    Set key globally: End
    Set key <home> to command: end-of-line

Test Home and End in this buffer a few times, and then try them in the cee buffer to show that the changes you just made were global:

HomeEndHomeEnd C-x b cee EnterHomeEndHomeEnd

Fix the Del key

On some configurations for Emacs, the Del key is bound to the same function as the Backspace key, delete-backward-char. This isn't the value most people want or expect; with most software, the Del key deletes the character following the cursor, not behind it.

Test your Del key:

  1. Type C-x b *scratch* Enter to move to the scratch buffer.

  2. Type some text:

    Delete me
  3. Type M-b so that the cursor is on the m character.

  4. Press Del.

If your Del key is bound correctly, the m was deleted. If you deleted the blank space between the two words instead, then you can fix your Del with the following:

M-x global-set-key
Set key globally: Del
Set key C-d to command: delete-char

Make a custom key

To define a new binding for a keystroke that's currently undefined, run the global-set-key function, give the new keystroke, and then the command to run.

For example, the M-F1keystrock is, by default, undefined. You type this keystroke by pressing and holding Alt (or whatever is the Meta key on your keyboard), pressing the F1 key, and releasing both keys. Try it—the only thing that should happen when you do is that Emacs beeps, indicating that this keystroke has been defined to no function.

You can define this keystroke to run the phases-of-moon function, which opens a new buffer window showing the current phases of the Moon.

Try it:

M-x global-set-key
Set key globally: M-F1
Set key <M-F1> to command: phases-of-moon

Try your new key binding: Type M-F1. After you do, you should see a new buffer window open with the current phases of the moon.


Customize your Emacs interface

A number of Emacs modes and functions control the Emacs interface itself—and you can customize them, too.

Take out the menu bar

The Emacs menu bar is a great help for beginners but, once you've gotten the hang of Emacs, you'll almost certainly want to get rid of it. You'll use the keyboard instead of the menu, and removing it gives you an extra line of your buffer on the screen.

The menu bar is turned on and off with the menu-bar-mode function, which is a toggle.

Try turning it off and then back on again:

M-x menu-bar-mode
M-x menu-bar-mode

Some similar functions are also worth knowing. The tool-bar-mode function toggles the display of the Emacs toolbar, which is displayed at the top of an Emacs frame (in X), and contains a number of graphical icons that are mouse shortcuts for various common Emacs commands. And the scroll-bar-mode function (see Table 1) controls whether the scroll bar is drawn on the left or right side of the Emacs frame—or is omitted completely.

Put a clock on the mode line

Another simple Emacs customization is the display-time function, which displays the current time (as well as other useful, current-status information) in the mode line.

Turn it on now by typing M-x display-time.

By default, this function displays the current time in hours and minutes to the right of the buffer name, followed by the current system load level and the word Mail, if you have unread mail. These values are updated every minute.

You can further customize it to precede all the status information with the current day of the week and current month (both in three-letter abbreviations), followed by the numeric day of the month. To do this, you have to set the display-time-day-and-date variable, which was described in Table 1. Try setting it now:

M-x set-variable Enter
Set variable: display-time-day-and-date Enter
Set display-time-day-and-date to value: 1 Enter

The display doesn't update immediately; you have to wait for the minute to change, or run the display-time function again by typing M-x display-time. At this point, if you've been following along with the examples, your Emacs session should look like Figure 2. The mode line of the current buffer (in this case, *scratch*) contains the day of the week, the name of the month, the numeric day of the month, and the time (in standard 12-hour format). You can display the time in 24-hour military format, too; to do this, use the display-time-24hr-format variable (see Table 1).

Figure 2. Customizing the display of the current time in the mode line
Customizing the display of the current time in the mode line

To go back to the original style, set display-time-day-and-date to nil:

M-x set-variable Enter
Set variable: display-time-day-and-date Enter
Set display-time-day-and-date to value: nil

When the minute changes or if you run the display-time function again, the current time appears in the mode line without the day of the week, name of the month, and numeric day of the month.

Customize your location

Emacs can do useful things with your geographic location such as give you the times for the sunrise and sunset. To enable this, set the values of the calendar-latitude, calendar-longitude, and calendar-location-name variables for your location.

Try setting these variables for an example location, as in Listing 5.

Listing 5. Configure geographic location data in Emacs
M-x set-variable Enter
Set variable: calendar-latitude Enter
Set calendar-latitude to value: 26.37 EnterM-x set-variable Enter
Set variable: calendar-longitude Enter
Set calendar-longitude to value: -80.09 EnterM-x set-variable Enter
Set variable: calendar-location-name Enter
Set calendar-location-name to value: "Boca Raton, FL (USA)" Enter

Now, run the sunrise-sunset function:

M-x sunrise-sunset

In the minibuffer, you should get today's sunrise and sunset times for the location you've given.

But this function can give the sunrise and sunset for any day, not just today. To get these times for a specific day, precede the function call with the universal-argument, C-u. Try it, as in Listing 6.

Listing 6. Run the sunrise-sunset function for a specific date
C-u M-x sunrise-sunset

  Year (>0): 2007 Backspace 8 Enter
Month name: Mar Enter
Day (1-30): 4

Once you do this, the minibuffer should report the following:

Tue, Mar 4, 2008: Sunrise 6:41am (EST), sunset 6:22pm (EST)
at Boca Raton, FL (USA) (11:41 hours daylight)

Turn on syntax highlighting

The Emacs Font Lock mode turns on fonts and colors, which is useful for many things including syntax highlighting, where important structural elements of a particular type of document are colorized or otherwise formatted in a certain way on the display. For example, in HTML mode, the bracketed tags of an HTML document are highlighted in color. The font-lock-mode function is a toggle that turns this mode on and off for the current buffer.

Try setting it now:

  1. Visit a new buffer called .emacs by typing C-x C-f, and then specify ~/.emacs as the file to find.

  2. If you have a .emacs file in your home directory, the preceding step opens it in a new buffer; if you don't have a .emacs file, Emacs makes a new, empty file of that name. In either case, insert the lines of Emacs Lisp given in Listing 7 to define the three location variables just described (unless, of course, your preexisting .emacs file already includes and defines these variables).

    Listing 7. Specify geographic location in a .emacs file
    ;; set the current location
    (setq calendar-latitude 26.37)
    (setq calendar-longitude -80.09)
    (setq calendar-location-name "Boca Raton, FL (USA)")
  3. Turn on Font Lock mode for this buffer:

    M-x font-lock-mode

The Emacs Lisp code is colorized, with various highlighting applied to elements, as shown in Figure 3.

Figure 3. Font Lock mode enabled in an Emacs Lisp buffer
Font Lock mode enabled in an Emacs Lisp buffer

You can save the file to disk by typing C-x C-s.

Summary of common Emacs interface functions

Table 2 lists and describes the functions affecting the Emacs interface.

Table 2. Summary of common Emacs interface functions
FunctionDescription
column-number-modeToggle the display, in the mode line, of the current column the cursor is at, preceded by a C. The default value is nil.
display-timeToggle the display of the current time in the mode line. The default value is nil.
font-lock-modeIf not set to nil, Emacs turns on the Font Lock mode automatically for the current buffer. The default value is nil.
global-font-lock-modeIf not set to nil, Emacs turns on the Font Lock mode automatically for all buffers. The default value is nil.
line-number-modeToggle the display, in the mode line, of the current line the cursor is at, preceded by an L. The default value is t.
menu-bar-modeToggle the display of the Emacs menu bar. The default value is t.
sunrise-sunsetDisplay the time of today's sunrise and sunset for the current geographic location. If preceded with the universal-argument, this function prompts for a specific day.
tool-bar-modeToggle the display of the Emacs toolbar. The default value is t.

Use your Emacs startup file

Every time Emacs starts, it looks for a hidden file in your home directory, .emacs, and executes any Emacs Lisp the file contains. This is your Emacs startup file or init file; use it to set variables or make other changes that happen automatically whenever Emacs starts.

Emacs Lisp calls are enclosed in parentheses; comments begin with a semicolon character (;). A number of conventions have evolved with Emacs Lisp; for example, comments describing a function usually begin with two semicolons and a space character. These conventions are described in the GNU Emacs Lisp Reference Manual (see Resources).

Among the many customizations you can make in your .emacs file, you can set variables, define key bindings, and set various modes, as described next.

(As described in the fourth tutorial in this series (see Resources), you can start Emacs without loading this init file first by giving the -q option, and you can have Emacs load another user's startup file by giving the username as an argument to the -u option.)

Set variables in your startup file

Maybe the most common way a .emacs init file is used is to set certain variables so that these values are set automatically every time Emacs is started. To set a variable in a .emacs file, use the setq function, as follows:

(setq VARIABLE VALUE)

You saw an example in Listing 7, where you created a simple .emacs file and saved the buffer in your home directory. Now you can demonstrate it:

  1. Type C-x C-c to exit Emacs; it's okay to lose the changes in any of the unsaved buffers you worked on in this tutorial.

  2. Restart Emacs:

    $ emacs
  3. Get today's sunrise and sunset: Type M-x sunrise-sunset.

You didn't have to set the Emacs variables for latitude, longitude, or location name because Emacs read them in from your .emacs file when it started. But at any point in an Emacs session, you can redefine any variable that's set in your .emacs file.

Define key bindings in your startup file

When you define a new key binding using the methods described in the Make a custom key section, it only lasts for the current Emacs session—once you exit, the changes are lost. But you can put custom bindings in your .emacs file to make them work every time you start Emacs.

If you have a problem with the Del key, for instance, you can include this in your .emacs file:

;; Make Del delete the character at point.
(global-set-key [delete] 'delete-char)

And you can include any one of the pairs described in Listing 8 to automatically redefine your Home and End keys for every Emacs session.

Listing 8. Redefining the Home and End keys in a .emacs file
;; Make Home and End move to the beginning and ending of the buffer
(global-set-key [home] 'beginning-of-buffer)
(global-set-key [end] 'end-of-buffer)

;; Make Home and End move to the beginning and ending of the line
(global-set-key [home] 'beginning-of-line)
(global-set-key [end] 'end-of-line)

;; Make Home and End move to the beginning and ending of the sentence
(global-set-key [home] 'backward-sentence)
(global-set-key [end] 'forward-sentence)

Set modes in your startup file

You can also turn modes on or off in your .emacs file.

Because most modes are called as a toggle, following them with a positive argument turns them on and a negative argument turns them off. You do so using this format:

(MODE-NAME VALUE)

For instance, you can turn off the menu bar automatically with the following:

;; turn off the Emacs menu bar
(menu-bar-mode -1)

Usually, modes are turned on when given a value of a positive integer or t (for "true"); they're turned off when given a negative, zero, or nil value.

All of the following lines do the same thing: They set global-font-lock-mode, which turns on Font Lock mode automatically for all buffers:

(global-font-lock-mode)
(global-font-lock-mode 1)
(global-font-lock-mode t)

Make short answers possible

Sometimes, when Emacs needs an answer from you, you have to type out the word yes or no, and follow it with a tap of the Enter key.

When you know what you're doing, this can be as annoying as how some window applications make you click OK in a popup window to verify the command you just specified.

To simplify the process so that pressing the Yor N key suffices, add the following to your .emacs file:

;; eliminate long "yes" or "no" prompts
(fset 'yes-or-no-p 'y-or-n-p)

This technique uses the fset function to redefine a given function. To learn more about this and similar Emacs Lisp functions, consult the GNU Emacs Lisp Manual (see Resources).

Putting it all together

Listing 9 contains a sample .emacs init file and many of the customizations described in this section. It also contains additional customizations using functions and variables described in Table 1 and Table 2. You can edit your new .emacs file to contain these entries, and then restart Emacs to see how the changes work.

Listing 9. A sample .emacs init file
;; set the current location
(setq calendar-latitude 26.37)
(setq calendar-longitude -80.09)
(setq calendar-location-name "Boca Raton, FL (USA)")

;; eliminate long "yes" or "no" prompts
(fset 'yes-or-no-p 'y-or-n-p)


;; Custom mode configurations
;; 
;; turn off the menu bar
(menu-bar-mode -1)
;; 
;; turn off the tool bar
(tool-bar-mode -1)
;; 
;; turn on Font Lock mode globally
(global-font-lock-mode t)

;; Custom key bindings
;;  
;; Make Del delete the character at point.
(global-set-key [delete] 'delete-char)
;; 
;; Make Home and End move to the beginning and ending of the sentence
(global-set-key [home] 'backward-sentence)
(global-set-key [end] 'forward-sentence)

Remember Emacs window and frame customizations

In the fifth installment of this series (see Resources), you learned how to manipulate Emacs frames and split them into multiple windows, both horizontally and vertically. You can also save your window customizations and recall them later in your session, even after you've made many changes to the layout of the screen; you do this with Winner mode.

Winner mode is a minor mode that records and remembers your changes to windows and frames. Each time you change the window configuration, it's remembered; you can undo your change to revert to the last configuration. You can also redo your changes to go back to the way you had them. It's especially handy if you're trying an unusual or complex configuration, or if you tend to do different kinds of tasks involving different window setups.

Two functions work in Winner mode: C-x <- (which you type by pressing and holding Ctrl, pressing X, releasing both keys, and then pressing the left arrow key) runs the winner-undo function and undoes the last change to the windows. Its counterpart is C-x ->, which runs winner-redo, returning the last change to the windows that you previously undid.

Enable Winner mode

To get started with Winner mode, set up a custom Emacs frame:

  1. Exit Emacs (if it's currently running), and then restart it with no arguments:

    $ emacs
  2. Type C-x 2 to split the Emacs window vertically, and then type C-x o C-x C-f .emacs Enter to open your .emacs file in the lower window.

  3. Type M-x winner-mode to turn on Winner mode.

When you do this, notice that Win is added to the mode listing given in parentheses on the mode lines of both visible buffers. This means that Winner mode is on and that it works in all buffers. (It even works in other Emacs frames, should you create them.)

Your Emacs session should now look like Figure 4. Notice that the Emacs frame no longer has a menu bar or toolbar—these were turned off in the .emacs file.

Figure 4. Winner mode enabled in an Emacs session
Winner mode enabled in an Emacs session

Cycle through your window configurations

Now, make some new window configurations:

  1. Use the mouse to click B1 in the top window so that it becomes the active window, and then type C-x 3 to split the window horizontally once.

  2. Split the upper-left window vertically by typing C-x 2, and then split the new, upper-left window horizontally again by typing C-x. Type C-x b .emacs Enter to switch to the .emacs buffer in this new window.

Your Emacs frame should now look like Figure 5. Notice that Win appears in the mode line of every window in the frame.

Figure 5. Reconfigure an Emacs frame with Winner mode enabled
Reconfigure an Emacs frame with Winner mode enabled.

Now you can go back to your old configurations and cycle through them—type C-x <- to undo your last window change.

Type C-x <- again to undo another change. Keep going until the minibuffer reports that no further undoes are possible. At this point, your Emacs frame should look like Figure 4, which was how it looked when you first enabled Winner mode.

Type C-x -> to run the winner-redo function and undo your last change. You can cycle between C-x <- and C-x -> to move through all your window changes.

The winner-mode function is a toggle: Type M-x winner-mode again to turn it off. When you do, the winner-redo and winner-undo functions no longer work, and window changes aren't remembered—but once it's enabled again, you can undo and redo any changes you've made to the windows.


Use the Emacs Customize function

Customize is a special Emacs function that was designed to make it easy to customize all aspects of the editor's behavior. It allows you to interactively select, set, and save values and settings for many aspects of Emacs, including the various fonts, faces, and colors used to display text. Its purpose is to simplify and rein in the elaborate Emacs customization process, making it easier for Emacs users who aren't Emacs Lisp programmers to customize their setup.

The Customize function is especially useful for setting text colors and faces because you can see and make changes interactively, and you can test them in your current session without applying them to all future sessions. When you do save your changes for future sessions, they're automatically written to your .emacs file, so they apply to the current as well as all future Emacs sessions.

Start a customization buffer

To begin customizing your Emacs, run the customize function by typing M-x customize.

When you do this, a new customization buffer appears in your Emacs frame, as shown in Figure 6. Notice the buffer's name: *Customize Group: Emacs*.

Figure 6. The Emacs customize buffer
The Emacs customize buffer

Pick a customization group

All of the various aspects of Emacs that can be customized are divided into groups containing similar elements and aspects of the editor. The groups that are displayed depend on your system setup.

To open a group and view its individual members, either use the mouse to click B1 on the Go to Group text button for that group, or use the keyboard to move the cursor over that button and press Enter. Sometimes a group opens into a list of new subgroups, in which case the process for selecting is the same.

Try selecting the Editing group now. When you do, Emacs opens a new buffer named *Customize Group: Editing* that contains a new listing of groups, all pertaining to Emacs editing functions.

Select the Fill group in this menu so that a *Customize Group: Fill* buffer is opened. This buffer contains many individual options and additional subgroups—you have to scroll down to see them all. Your Emacs session should look like Figure 7.

Figure 7. The Emacs Fill customize group buffer
The Emacs Fill customize group buffer

Change a customization option

Each option in the group listing has a value that you can change. You see a number of buttons for each option, including More, which provides more information about the option. When you click this button, it's relabeled Hide; when you click it, the expansion is hidden again.

The State button describes the current state of that option: unchanged from its standard setting, hidden, changed but not saved, or changed and saved.

Try changing a value: Scroll down to the Fill Column entry, and notice that the value is set to 70, which you remember is the default for this variable. Move the cursor to the box with its value, and change it to 10. The State button for this value reports the following:

you have edited the value as text, but you have not set the option.

Move up to the top of the buffer, and click the Set for Current Session button; this puts your changes in effect, but they'll reset as soon as you exit Emacs. (If you want to make a change that affects this and all future sessions, click the Save for Future Sessions button instead).

Click the Finish button, which removes this buffer, and click the Finish button on all other Customize buffers.

Now you can test your customization:

  1. Type C-x C-f .emacs Enter to open a copy of your .emacs init file in a new buffer.

  2. Move the cursor to each comment line (they begin with ;; and are followed by a line of text), and type M-q on run the fill-paragraph function on them.

The paragraphs fill at the tenth character on each line, so your .emacs init file should look like Figure 8.

Figure 8. Wrap comment text in a .emacs file after customizing the fill column
Wrap comment text in a .emacs file after customizing the fill column

You can verify that the changes you made to default filling work only for this session: Save your reformatted .emacs file, exit Emacs with C-x C-c, and then restart it with your .emacs file:

$ emacs .emacs

Now, move to all the comment lines containing text, and type M-q on each of them to watch them move back to where they were before (filled at 70 columns).

Customize specific attributes

You don't have to go through the entire series of customization buffers every time you want to make a particular customization. Commands are available to take you directly to a particular group, and some of the Emacs customization menus have special Emacs functions of their own.

For example, the customize-group function opens a customization buffer for the given group.

Try opening a new Emacs customization buffer for the Fill group:

M-x customize-group
Customize group: (default emacs) fill

You get a *Customize Group: Fill* buffer just as before, as in Figure 7.

Know the Emacs customization functions

Table 3 lists and describes the various Emacs Customize functions.

Table 3. Summary of Emacs Customize functions
FunctionDescription
customize-changed-options EnterversionOpen a new customization buffer for all faces, options, or groups that have been changed since the version of Emacs given by version.
customize-customizedOpen a new customization buffer for all options and faces that have already been customized but haven't been saved to disk.
customize-face Enter regexpOpen a new customization buffer for all the face, option, or groups relevant to the regular expression given by regexp.
customize-face Enter faceOpen a new customization buffer for the face name given by face.
customize-group Enter groupOpen a new customization buffer for the group name given by group.
customize-option Enter optionOpen a new customization buffer for the option name given by option.
customize-savedOpen a new customization buffer for all faces and options that you've changed with the Customize function.

Summary

Wrap-up

You've just gone through several important ways that the Emacs editing environment can be configured and customized by setting variables, changing the default key bindings, and manipulating modes interactively. You also learned how to use an Emacs init file to save your customizations for future sessions, how to use Winner mode to save and recall your customizations of Emacs windows and frames, and how to use the built-in Emacs Customize function to customize everything from basic fonts and colors to the way specific text-editing functions are performed.

Every facet of Emacs can be changed or extended in powerful ways, and you've learned how to do that. Now you can get your Emacs to work just the way you want it to.

Resources

Learn

Get products and technologies

  • IBM trial software: Build your next development project with software for download directly from developerWorks.
  • GNU Project Web site: Download a free copy of the latest GNU Emacs for your OS and architecture free of charge.

Discuss

Comments

developerWorks: Sign in

Required fields are indicated with an asterisk (*).


Need an IBM ID?
Forgot your IBM ID?


Forgot your password?
Change your password

By clicking Submit, you agree to the developerWorks terms of use.

 


The first time you sign into developerWorks, a profile is created for you. Information in your profile (your name, country/region, and company name) is displayed to the public and will accompany any content you post, unless you opt to hide your company name. You may update your IBM account at any time.

All information submitted is secure.

Choose your display name



The first time you sign in to developerWorks, a profile is created for you, so you need to choose a display name. Your display name accompanies the content you post on developerWorks.

Please choose a display name between 3-31 characters. Your display name must be unique in the developerWorks community and should not be your email address for privacy reasons.

Required fields are indicated with an asterisk (*).

(Must be between 3 – 31 characters.)

By clicking Submit, you agree to the developerWorks terms of use.

 


All information submitted is secure.

Dig deeper into AIX and Unix on developerWorks


static.content.url=http://www.ibm.com/developerworks/js/artrating/
SITE_ID=1
Zone=AIX and UNIX, Open source
ArticleID=259318
ArticleTitle=Emacs editing environment, Part 6: Customize your Emacs world
publish-date=10022007