Chapter 10. Customizing Emacs

As you have probably noticed throughout this book, Emacs is very powerful and very flexible. You can take advantage of that power and flexibility to configure Emacs to match your work style and preferences. We'll look at several of the most common customization tasks and also look at a few resources for more in-depth coverage than we can provide here.

You can customize Emacs in three ways: using Custom, the interactive interface; using the Options menu, which is really a backdoor to Custom; and directly by adding lines of Lisp to your .emacs file. This chapter covers all three of these methods.

No matter what method you use, though, the .emacs startup file is modified. Custom modifies it for you when you save settings through that interface. The Options menu invokes Custom behind the scenes; when you choose Save Options, Custom again modifies .emacs. Throughout the book, we have been providing lines for you to add to .emacs directly so you could adjust Emacs to your preferences.

Before we get started, we should say that the very easiest way to customize Emacs is by selecting an option from the Options menu and choosing Save Options. This menu is designed to provide easy access to changing frequently used options. For example, you may not like the Toolbar and its icons, feeling that such graphical codswallop is beneath an Emacs user. You can hide the toolbar through the Show/Hide option on the Options menu. Choosing Save Options modifies .emacs so the toolbar is hidden every time you start Emacs. And if you miss the toolbar someday, you can get it back the very same way.

After describing customization methods, this chapter goes on to discuss several generic issues relating to customization, including how to change fonts and colors, modify your key bindings, set Emacs variables, find Lisp packages to load, start modes automatically based on file suffixes, and inhibit any global customization files that may be interfering with your own .emacs settings.

10.1 Using Custom

Emacs now ships with a quirky graphical-but-not interface that allows you to customize most aspects of Emacs without knowing the gory details. This feature, known as Custom, can be accessed by typing M-x custom or by clicking the tools icon on the toolbar.


Type: M-x custom Enter

Emacs displays the startup buffer for Custom (Mac OS X).

10.1.1 Navigating Custom

You can move around in a given Custom screen much the way you do in any other part of Emacs. All of the basic cursor movement commands like C-n and C-p work just as they should. But that's only part of the story in Custom. To accomplish anything useful, you need to activate special words and phrases. Those bits of text in grey boxes that look like buttons are the words and phrases in question.

To activate one of these buttons, click on the button with the mouse or position your cursor inside its borders and press Enter. Figure 10-1 highlights these options.


Figure 10-1. Custom button activation using the mouse cursor (top) and the keyboard cursor (bottom) (Mac OS X)


When you finish looking at a screen, if you are not interested in changing anything, you can type C-x k to kill the current buffer and go back to the previous screen. You can also activate the Finish button in the common header set discussed next.

10.1.2 Common Options

At the top of each page in Custom is a common set of buttons shown in Figure 10-2. These options affect the entire buffer.


Figure 10-2. The actions common to all pages in Custom (Mac OS X)


From here you can perform any of the following tasks:


Set for Current Session

Make immediate changes that last for the duration of this session but will be reset the next time you start Emacs.


Save for Future Sessions

Make immediate changes that last for the duration of this session and will also be in place the next time you start Emacs. These changes are stored in your .emacs file.


Reset

Switch back to the previous values (previous to your current changes, anyway).


Reset to Saved

Switch back to the previously saved values. In this case, "saved" means saved for future sessions. If you haven't made (and subsequently saved) any customizations to a variable, this option has no effect.


Erase Customization

This option pretty much does what it says. Any customizations made by Custom, whether for this or future sessions, are removed. Your own personal entries in your .emacs file should remain intact, but it's always a good idea to make a backup before deleting any information.


Finish

Close this buffer and return to the previous customization buffer or back to the buffer from which you launched Custom. Note that you can also press the q key to activate Finish from anywhere in a Custom buffer.


These options are useful when you modify more than one option on a page and want to save them all at once (and in the same way).

Custom corrals options into customization groups, which are set up in a hierarchy of parent and child groups. To go to the parent group for the group you're looking at, choose the button for the parent group in question following the

Go to parent group:
prompt. To make it easier to find things, a group might have more than one parent. For example, the I18n (internationalization) group has two parents,
Environment
and
Editing
, as shown in Figure 10-3.


Figure 10-3. Custom's Go to parent group prompt


Choosing

Go to parent group
is much like choosing Finish but without closing the buffer. It's a useful option if you're just poking around looking for related variables. We'll show you better ways to find particular features to customize later in this chapter.

10.1.3 Customizing with Custom

After you learn your way around, you can tackle customizing Emacs. Each screen of Custom lists variables and other settings. You can edit the value of any variable in the grey text field to the right of variable's name. The current value should be listed. Just delete the current value and type the new value.

Changing a value, however, is not the last step you have to take. You need to save the change before it will take effect. You use the State button to save the change (as mentioned earlier, to save all the values on a page in the same way, you can use the options near the top of the screen). As with other parts of Custom, you can use your mouse or the keyboard. Clicking the left mouse button on State should bring up the list shown in Figure 10-4. Depending on the variable and the change you made (if any), you may or may not have all of the options available.


Figure 10-4. Using the mouse to save or reset an option (Mac OS X)


Of course, you can also activate the State button by placing your cursor on it and pressing Enter. That should create a second window with effectively the same options you get when using the mouse. Figure 10-5 shows the options you see using the Enter key to select State. This list is dynamic, showing only options that are available to you. (It won't show any options if you haven't changed anything yet, but it beeps with an error.)


Figure 10-5. Using the keyboard to save or reset an option (Mac OS X)


When using the mouse, simply select the desired choice from the list. When using the text approach, type the number (or other character) corresponding to your desired choice. The options available are similar to those that apply to the entire buffer. You'll see the familiar save and reset options along with a few new ones:


Set for Current Session

Same as the global option. Saves the new value for the duration of this session.


Save for Future Sessions

Same as the global option. Applies this value immediately and updates your .emacs file so the new value is used whenever you start Emacs.


Reset to Current

Goes back to the current value for the variable. Any unsaved changes are thrown out, but changes saved—even just for this session—count as "current" changes.


Erase Customization

Same as the global option. Any changes to the variable are removed and .emacs is updated if needed.


Use Backup Value

Goes back to the value saved before the "current" value was set. In other words, revert to the value replaced by the most recent save.


Add Comment

You can add your own comments to the variable to help you remember why you made this change. Comments last as long as the saved change. Changes made only for the current session keep the comment only for the current session (not often useful). Comments added to changes that you save for future sessions show up on this screen in those future sessions. Erasing the customized value also erases comments.


If you make a mistake or supply a value that is not appropriate for the variable, you get a brief error message in the minibuffer. As with other utilities that grew up in the world of Unix, no news is good news. If you don't see any error messages, your change was successfully saved.

10.1.4 An Abbrev Mode Example

Word abbreviation mode is a wonderful way to correct typos on the fly. But it can't work that way unless it is turned on. Let's use Custom to turn on word abbreviation mode (discussed in Chapter 3).


Type: M-x custom Enter

Main customization screen.


Click on the Go to Group button next to Editing group

The Editing group.


Click on the Go to Group button next to Abbreviations group

The Abbreviations group.


Click on the Go to Group button next to Abbrev Mode group

The Abbrev Mode group.


Finally, we're at a screen where we can set the option! Notice that the first content line, Abbrev Mode group, says next to the State button

visible group members are all at standard settings
. Also note that Abbrev Mode, near the bottom of the screen, says
this option is unchanged from its standard setting
.

We'll turn on the Abbrev Mode option by pressing the Toggle button.


Click Toggle next to Abbrev Mode

Abbrev mode is set to on.


The text near Abbrev Mode group now says,

You have edited something in this group, but not set it
. The text near the Abbrev Mode option says,
you have edited the value as text, but you have not set the option
. These are clear hints that we must take one more step to set this option. And if those weren't hints enough, the minibuffer explicitly instructs,
To install your edits, invoke [State] and choose the Set operation
. We could click on the State button next to the option, but it's just as convenient (if not more convenient) to click on the Save For Future Sessions option near the top of the screen. This saves all options we've changed in the buffer, which in our case is just one option.


Near the top of the screen, click on Save for Future Sessions

Emacs tells you that it wrote the .emacs file.


Next to the Abbrev Mode group it now says,

something in this group has been set and saved
. Next to the Abbrev Mode option it says,
this option has been set and saved
. Note also that
Abbrev
appears on the mode line now; we have indeed successfully turned on word abbreviation mode. Click Finish repeatedly to kill all the Custom buffers.

Congratulations; you're on your way to customizing Emacs. You should spend some time wandering around in the various groups Custom offers to get a sense of the things you can control. We'll look at the popular topics of customizing fonts, colors, and keyboard mappings in later sections. But Custom offers a much wider variety of areas to tweak. Don't be afraid to look around. You can always use the Reset option to undo something that doesn't behave the way you expected or wanted.

10.1.5 The Options Menu

You can also access Custom through a bit of a back door: the Options menu. Figure 10-6 shows the Options menu. There are three key entries at this top level:


Figure 10-6. The Options menu (Windows)


Show/Hide

Allows you to turn on (and off) several features of Emacs including the menu bar and toolbar.


Save Options

A quick shortcut to saving any changes you make to Emacs through the Options menu.


Customize Emacs

A submenu that allows you to tweak common items such as fonts and variables as well as helping you browse and search through the options available to Custom.

10.1.6 A Dired Example

Let's tackle another Custom example with the help of the Options menu. Dired (discussed in Chapter 5) has many customizable features. One such feature is the dired-view-command-alist variable. This is a list of helper applications that allow you to open various kinds of files. This feature can be quite handy for viewing binary files such as images or PDF files. This list of helper applications is tailored to Linux. If you want to use other applications or you're on a Windows or Mac system, you'll need to customize this variable.

Before you customize this option, you need to open a directory or simply type C-x d to enter Dired. Next, from the Options → Customize Emacs menu, select the Specific Option item.


Choose Options → Customize Emacs → Specific Option

The minibuffer prompts for a specific option to customize (Windows).


The minibuffer prompts for an option name. We want to customize dired-view-command-alist.


Type: dired-view-command-alist Enter

Editing a list entry in Custom (Windows).


You should see the familiar Custom options for saving and resetting the values along with the value of the dired-view-command-alist variable. For this particular variable, we have a list of entries for common file types including PostScript files, PDF documents, and images. To alter one of the existing entries, simply move to the

String
line and edit the text in grey to launch the application you would like to use. (You can also alter the filename pattern by editing the text in the
Regexp
line.) For example, PDF documents can be viewed with the open command in Mac OS X, so we could change that line as shown in Figure 10-7. In fact, on Mac OS X, you can use the generic open command for just about every type of file. On Windows it is even easier. Simply enter %s as the string, and Windows uses its default application to open that file type.


Figure 10-7. Editing a list entry in Custom (Mac OS X)


If you don't use DVI documents, you can get rid of that association using the DEL button shown in Figure 10-8.


Figure 10-8. Deleting a list entry in Custom (Mac OS X)


You can also add new document types and viewers by clicking on any of the INS buttons. (The order of the associations isn't important for this particular variable, but it might matter for other lists.) To insert a new association before the PDF entry, activate the INS button to the left of the PDF entry.


Click on INS to the left of the PDF entry.

The first step in adding a new item to a list in Custom (Windows).


Now you can add an association for playing MP3 files on a PC by editing both the

Regexp
and
String
lines. Note that you'd have to supply a path to your helper application (winamp in this example) that matched your system. As mentioned earlier, if winamp was already the default helper application for MP3s, you could simply type %s for the
String
instead of the complete path to winamp.


Type [.]mp3\' for the

Regexp
and c:\apps\media\winamp.exe %s for the
String
:

The second step in adding a new item (Windows).


You may have noticed the Save Changes option in the Options menu. This menu item saves changes you make through the Options menu. For example, you can modify such settings as whether or not the toolbar is visible or the Save Place in Files between Sessions option. It does not save changes you have made through Custom—even if you launched Custom from one of the Options → Customize Emacs submenu items. You'll still need to use the normal Custom options to save those changes.

For our Dired variable example, then, you'll need to select one of the Save options available. In this case, we'll save it for the current session only.


Click on Set for Current Session

Saving changes for this session only (Windows).


When you're done saving your changes, you can exit the buffer as usual by clicking the Finish button, typing q, or typing C-x k to kill the buffer.

10.1.7 But Where Is the Variable I Want?

One of the biggest stumbling blocks to using Custom is knowing where a particular variable is located. Custom has a lot of groups and subgroups—and they aren't always intuitive. There are two quick ways to "search" for a specific variable. You can press Tab to use the completion feature in the minibuffer or you can browse through the entire Custom hierarchy.

To use the completion approach, type M-x customize-option or select Options → Customize Emacs → Specific Option. You'll see

Customize Option:
in the minibuffer. You can type a string like font and then hit the Tab key to see what variables start with that string.

You can also create a custom buffer with options matching a regular expression with M-x customize-apropos (or Options → Customize Emacs → Options Matching Regexp). You can type in a regular expression (or a simple string) and Custom builds a new buffer with all groups containing matching options.

If you want to browse the hierarchy to see the related groups of variables in a reasonably compact view, select Options → Customize Emacs → Browse Customization Groups. That should land you on a screen similar to Figure 10-9.


Figure 10-9. Browsing customization groups (Mac OS X)


You can activate the [+] and [-] buttons just like you do other Custom buttons (click on them with your mouse or move the keyboard cursor to them and press Enter.) This allows you to browse the entire set of Custom groups and subgroups. After you find the variable you're looking for, click on the Option button next to the variable or click on the Group button for the variable's parent group if you want to edit multiple variables in the group.

10.2 Modifying the .emacs File Directly

It's possible to customize Emacs in just about any way you can imagine. Almost everything you see on the screen, every command, keystroke, message, and so on, can be changed. As you may imagine, most customizations involve the Emacs startup file .emacs.

10.2.1 Custom Versus .emacs

The previous section discussed the interactive customization tool, Custom, but left out some of the details on what happens any time you "save for future sessions." Custom places the configuration information in your .emacs file. Some things simply cannot be done through Custom (yet). Once you get familiar with the types of statements that go into your .emacs file, you may also just find it easier to add a line or two directly.

We should emphasize that using Custom or editing .emacs by hand is not an either-or proposition. When you save options via Custom, it adds its settings to the end of your .emacs file and warns you not to edit them by hand. Despite this prohibition, you can easily add your own customizations to the beginning of that file. To illustrate this, Example 10-1 shows a sample .emacs file for Mac OS X that shows edits made directly by the user as well as sections added by Custom (shown in bold)


Example 10-1. A .emacs file for Mac OS X with lines added by the user and by Custom

(setq mac-command-key-is-meta nil)

(diary)

(setq load-path (cons "~/elisp" load-path))

(autoload 'html-helper-mode "html-helper-mode" "Yay HTML" t)

(setq html-helper-build-new-buffer t)

(setq auto-mode-alist (cons '("\.html$" . html-helper-mode) auto-mode-alist))

(setq-default indent-tabs-mode nil)

(setq-default tab-width 15)

(setq-default abbrev-mode t)

(read-abbrev-file "~/.abbrev_defs")

(setq save-abbrevs t)

(fset 'boldword

  [?\C- escape ?f ?\C-x ?\C-x ?< ?b ?> ?\C-x ?\C-x ?< ?/ ?b ?>])

(fset 'italword

  [?\C- escape ?f ?\C-x ?\C-x ?< ?e ?m backspace backspace ?i ?>

  ?\C-x ?\C-x ?< ?/ ?i ?>])

(global-set-key "\C-x\C-kI" 'italword)

(setq shell-file-name "/bin/zsh")

(add-hook 'comint-output-filter-functions

  'comint-watch-for-password-prompt)

(custom-set-variables

 ;; custom-set-variables was added by Custom.

 ;; If you edit it by hand, you could mess it up, so be careful.

 ;; Your init file should contain only one such instance.

 ;; If there is more than one, they won't work right.

 '(global-font-lock-mode t nil (font-core))

 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify))))

(custom-set-faces

 ;; custom-set-faces was added by Custom.

 ;; If you edit it by hand, you could mess it up, so be careful.

 ;; Your init file should contain only one such instance.

 ;; If there is more than one, they won't work right.

)

10.2.1.1 Will the real .emacs please stand up?

You might have a bit of trouble finding the right .emacs file to work with when you're first starting out. Emacs actually looks for a variety of startup files. In order, they are:


.emacs.elc

The byte-compiled Lisp version or your startup file. This is not editable, but can make startup quicker if you have a big, complex startup file.


.emacs.el

The more formal name for your startup file. You can use Lisp commands to customize and initialize your entire Emacs environment.


.emacs

The common name for the startup file. Exactly like the .emacs.el file, just without the .el extension. Both are editable.


As soon as Emacs finds one of these files, that's it; then it's on to the next step in startup. You can't have a .emacs.elc for the big customizations and then a separate .emacs for the last few. Sorry!

For all you Emacs users on Microsoft Windows-based systems, you might bump into a variation of this file that begins with an underscore ( _ ) rather than a dot (. ). In the past, the Windows filesystem required something before the first dot, so .emacs was an invalid filename. Consequently, _emacs was adopted. The same order and notes about the .elc and .el variants applies. In modern versions of Windows, .emacs is a valid filename and the dot variations take precedence over the underscore versions.

10.2.2 Basic .emacs Statements

Some changes require a knowledge of Emacs Lisp programming (see Chapter 11); others are simple enough without such knowledge. In this chapter, we cover a variety of useful customizations that require no programming knowledge. For now, however, you need to know this: every Emacs command corresponds to a Lisp function, which has the form:

(function-name arguments)

For example, if you want to move the cursor forward by a word, you type M-f. What you are actually doing is running the Lisp function:

(forward-word 1)

10.2.2.1 Caveat editor

Two important comments concerning .emacs files are in order. First, if you are inserting code into your .emacs file, you may end up putting in something that causes Emacs to fail or behave strangely. If this happens, you can invoke Emacs without running your .emacs file: simply invoke Emacs with the command-line option -q, and Emacs will not run your .emacs file. (Chapter 13 gives instructions for starting Emacs from the command-line on Windows and Mac OS X.) You can then examine the file to figure out what went wrong.

The other comment is perhaps the most important piece of advice we can give you concerning customizing your Emacs environment: steal mercilessly from other users. In particular, if you are dealing with a messy situation involving a configuration problem or a subtle point about some specialized mode, it is possible that some other user has solved the problem(s) already. This is not dishonest or subversive in any way; rather, it is encouraged by the makers of GNU Emacs, who would rather software be shared than kept to oneself. Emacs even provides an easy way to try out other users' .emacs files: invoke Emacs with the option -u username, and username's .emacs file will run instead of yours. (Of course, this works only with users on multiuser systems.)

In fact, numerous example .emacs files are available on the Web. (Check out "the very unofficial" .emacs site, http://www.dotemacs.de/.)

10.2.3 A Sample .emacs File

Here's a quick example of a (very) simple .emacs file:

;; Turn on font-lock mode to color text in certain modes

(global-font-lock-mode t)


;; Make sure spaces are used when indenting code

(setq-default indent-tabs-mode nil)

The lines beginning with two semicolons are comments. They're meant to help you understand what is being configured. Sometimes they also list possible values or the previous value. You can say anything you want in a comment—as long as it fits on one line. If you need to spill over onto a second or third line, just begin each successive line with ;;.

Blank lines are ignored. Every other line (that's not blank or a comment) is considered part of a Lisp program that is executed to configure your Emacs session. In this example, we first call the global-font-lock-mode function with an argument of t (true, or "on"). Next we make sure that using the Tab key when writing code doesn't actually insert a tab character but uses spaces instead. (This is a good thing to do when writing code—otherwise your code can come out very messy on systems that use a different tab width.) We use the setq-default function to assign the indent-tabs-mode a nil (false or "off") value. Using setq-default has the advantage of setting the default value only—modes that choose to override this value may still do so.

If you're a seasoned Lisp programmer, you can do anything you would normally have access to in Lisp. There are certainly particular functions and variables you need to know about to be effective, but it is just a Lisp program.

For the rest of us, this file mostly consists of blocks of Lisp found on the Internet or on a colleague's computer. You edit in your personal values and hope it all works. Really. If you use Custom to manage all of your configuration changes, you don't even have to look at .emacs unless you want to add your own lines at the beginning of the file or look at what Custom has done.

10.2.3.1 Editing .emacs

The great thing about configuring a text editor is that you can use the editor itself to make the changes. You can visit the .emacs file just as you would any other file. The only thing to watch out for is where you are. Some folks put backup copies of this file in strange places. You want to edit the file that came from your home directory. If you're unsure of where you are, you can use the full name ~/.emacs which Emacs translates to the proper directory.

Note also that .emacs is not required. If you haven't had any reason to customize Emacs, it might not exist. But you should feel free to create it when you're ready to start tailoring your environment. (Making your first change via Custom will also create .emacs if it doesn't exist.)

The best way to deal with this file really is to find an example file and make small changes to it. Use those ;; comments liberally. If you're going to change a line in your .emacs file, make a copy of it first:

;; Turn off font-lock

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

(global-font-lock-mode nil)

That way you can easily get back to a known, working version of your .emacs file. If things get really bad, just start over. Rename your current .emacs file and then copy and paste small chunks of it at a time.

For changes required by modules and other packages, the documentation for those modules usually includes example lines for insertion into your .emacs. For example, the JDEE site includes a sample .emacs file that can be used as-is or appended to an existing file. (And if you want to get fancy, you can leave the JDEE sample in a separate file and simply include a load-file call from your .emacs file. More on load-file can be found in the Elisp documentation.)

10.2.3.2 Saving .emacs

You save your .emacs just as you normally save any file. To test any changes you've made, though, you'll have to do one of two things. The sure-fire method is to quit Emacs and launch it again. If everything comes up the way you expected, you're good to go.

You can also run M-x load-file. You'll be prompted for the name of the file. Just type in ~/.emacs Enter and you should be able to check your changes.

Tip

Be careful here: it's entirely possible that something in your current session will interact with your new .emacs file. For example, if you have already set a default value for a variable, commenting out that line of your .emacs file will not remove the value unless you also remove the default value by hand. If you've got a fairly simple configuration, though, you should be fine. Reloading .emacs is certainly faster that restarting Emacs!

Either way, once you have verified that your configuration works the way you want, you can forget about this file. Until you want to make more changes, of course!

10.3 Modifying Fonts and Colors

Emacs on certain platforms (Windows, Mac OS X, and Unix) can display text in multiple fixed-width fonts. It doesn't yet handle proportional-spacing fonts well, although future releases are expected to address that issue. Emacs can display text in as many combinations of foreground and background colors as your system supports. We'll take a look at your options for changing fonts. You can make quick, interactive changes in any buffer. You can also customize the fonts and colors used by automatic highlight features such as Isearch and font-lock mode.

And just in case you want to use Emacs to edit rudimentary styled-text documents, we'll also look at how to save and load files that have font and color enriched text.

10.3.1 Changing Fonts Interactively

Both Custom and the Edit menu in Emacs provide you with a way to change the current font and color by picking a new one from the Text Properties menu.

To understand the Text Properties menu, you'll find it useful to know that Emacs thinks internally in terms of faces. A face is a font and color combination. The Text Properties menu presents you with a small set of premixed faces and the option to specify others by name.

We'll go into more detail about faces, how to name them, and the related Lisp programming constructs later in this chapter. For now, consider simply that every character in a buffer may have a different face invisibly associated with it (though in practice it would be quite surprising if face changes were that frequent!).

Holding down the Shift key while clicking the left mouse button takes you to a menu of fonts. Selecting one of these instantly changes the Emacs font for the current frame and redisplays the frame. This is an easy way to experiment with different fonts to see how well they trade screen space for readability on your display.

10.3.2 Automatic Highlighting and Coloring

A number of modules in Emacs feature text highlighting and syntax coloring. The various programming and markup language modes (Lisp mode, Java mode, HTML mode, and so on) have such highlighting. How you customize those fonts and colors depends heavily on the individual module.

10.3.2.1 Isearch

The Isearch facility in Emacs has undergone a few changes as it has matured. It uses font faces and coloring to highlight a document when you search for words or expressions. You may find the default choices a bit, well, stark. You can customize the group by typing M-x customize-group Enter isearch-faces Enter to change them.

Incidentally, you might just try changing the face it uses to highlight the secondary matches, so that it's less intrusive.

10.3.2.2 Buffer highlighting

The easiest way to use fonts and colors is to load the Lisp package font-lock.el (included with the Emacs distribution). This mode tries to highlight interesting features of your text buffers using color and different faces. As an example, try picking out comments in C and Lisp buffers, and painting them in a color that contrasts with the basic black of the code.

;; Turn on font lock mode every time Emacs initializes a buffer

;; for Lisp or C.

;;

(add-hook 'emacs-lisp-mode-hook 'turn-on-font-lock)

(add-hook 'c-mode-hook 'turn-on-font-lock)

Font-lock mode tends to be especially helpful for colorizing programming language code or outline mode text but also gives useful results for HTML files and Dired buffers. In fact, we find it useful in so you may want to turn it on globally instead, as we did in "A Sample .emacs file" earlier in this chapter. If you want more examples using font-lock mode, refer back to Chapter 9 on some of the various programming language modes supported by Emacs.

10.3.3 Customizing Fonts Through Custom

Now that you know how to work with Custom, you can also go that route to edit and alter fonts and colors. The easy way to get started in Custom is to run M-x customize-group and enter faces for the group name. (Figure 10-10 shows a sample of the groups you'll see.)


Figure 10-10. Font face groups available in Custom (Mac OS X)

10.3.4 Changing Colors

But what if you just want to change the default foreground and background colors? Well, that turns out to be quite simple. You can use the M-x set-foreground-color and M-x set-background-color commands to pick simple colors (based on their names such as black, white, yellow, blue, red, etc.). Be careful, though, because Emacs has no qualms about letting you set these values to garish—or even impossible—combinations! While black text on a black background may provide some level of security from anyone peeking over your shoulder, it's not the most productive combination in the long run.

To see the range of colors available, run M-x set-foreground-color. When it prompts you for a color, just press Tab to get a completion list of the possible colors—you should get quite a few! These names can also be typed into the foreground and background fields (or any other color-based field) in Custom.

You can also use Custom to control all aspects (including the foreground and background colors) of the "default" font. Figure 10-11 shows the Custom screen for just that font after switching the colors to green and black.


Figure 10-11. Changes to the default font colors effectively set the foreground and background colors for Emacs (Mac OS X)


You can go through the usual channels discussed previously to customize this face, or come here directly with M-x customize-face and then enter default at the prompt.

10.3.4.1 Changing the cursor color

Don't forget about the cursor! You can also use set-cursor-color to change the color of the cursor. That can be especially useful if you want a black background—the default black cursor can easily get lost.

10.3.5 Saving Font- and Color-Enriched Text

The astute reader will have noticed that, although the highlighting machinery allows us to set up enriched text in a buffer, we haven't shown a way to save text properties along with text between sessions. This is a significant issue. As long as there is no way to save properties along with text, all the font and color machinery remains little more than a display hack, good for decorating buffers but adding little to Emacs's editing power.

What's needed to remedy this situation is a way for text properties to be saved in an expanded text-markup form and restored into text properties when the file is next edited.

At the time of this writing, experimental code to support this is included with Emacs. A library called enriched-mode supports saving text properties into the MIME enriched-text format specified by the Internet standards document RFC 1896, and can parse files in that format into Emacs buffers with equivalent text and text properties.

Although this mode is quite usable as is, much design and development still needs to be done before the capabilities enriched mode supports are mature and well integrated with other Emacs modes. By the time you read this, there may be several such libraries, each supporting a different enriched format such as HTML. Eventually modes like these should enable Emacs to support WYSIWYG and even multimedia editing.

To enter enriched mode, type M-x enriched-mode.

Enriched
appears on the mode line. Emacs may ask if you want to make newlines between paragraphs hard. (This is because Emacs reformats the paragraphs when you change margin settings.) Type y.

You can use several font commands to decorate your text. Most begin with the M-g prefix. Table 10-1 lists some of the more common options. If you like using the menus, you can also select the options in Table 10-1 using the Edit → Text Properties → Face menu.


Table 10-1. Enriched mode font commands

Command Font selected
M-g d default
M-g b bold
M-g i italic
M-g l bold-italic
M-g u underline
M-g o other (allows you to pick a font face by name)

The commands listed in Table 10-1 apply to the currently marked text. We used a number of these commands to produce the simple text example shown in Figure 10-12.


Figure 10-12. An enriched text example (Mac OS X)

10.3.5.1 Saving enriched text

When you save enriched text, Emacs marks up the document with XML-like tags. Emacs will happily read the document back in, although not many other applications will know what to do with the tags. Still, as you can see below, the tags are straightforward and would allow custom applications such as CGI scripts for the Web to parse them quickly.

Content-Type: text/enriched

Text-Width: 70


blueTesting


This is a quick test of the


redenriched mode in Emacs.


Not sure what's gonna happen.


Looks good from here.

But, you can't rely too much on enriched mode yet. For example note the

Testing
title line. It doesn't appear to contain any information about the size of the font—which is definitely larger if you look at Figure 10-11. Sure enough, killing the buffer and reloading the file loses the size value. The text is still blue and the content is available, but some of the formatting has been lost.

The moral is a classic one: be careful. If you have serious enriched text needs, Emacs is probably not the tool to use (at least not yet). Many of the various word processors out there will do a much better job. But if you just need some basic enhancements to documents that only you or other Emacs users will view, enriched mode is just the ticket.

10.4 Customizing Your Key Bindings

Perhaps the most common things that Emacs users want to customize are the keystrokes that cause commands to run. Keystrokes are associated with commands via key bindings.

Actually, every keystroke runs a command in Emacs. Printable character keys (letters, numerals, punctuation, and spaces) run the self-insert-command, which merely causes the key just pressed to be inserted at the cursor in the current buffer. (You could play a nasty April Fool's joke on a naïve Emacs user by changing the bindings of their printable characters.)

The default set of key bindings is adequate for most purposes, of course, but there are various cases in which you may want to add or change key bindings. Emacs contains literally hundreds of commands, only some of which have key bindings. As you know, you can access those that don't have bindings by typing M-x command-name Enter.

If, however, you intend to use an unbound command often, you may want to bind it to a keystroke sequence for convenience. You may want to set special keys, such as arrow, numeric keypad, or function keys, to perform commands you use often.

The other important concept you need to know now is that of a keymap, which is a collection of key bindings. The most basic default key bindings in Emacs are kept in a keymap called global-map. There is also the concept of a local keymap, which is specific to a single buffer. Local keymaps are used to implement commands in modes (like C mode, text mode, shell mode, etc.), and each such mode has its own keymap it installs as the local map when invoked. When you type a key, Emacs first looks it up in the current buffer's local map (if any). If it doesn't find an entry there, it looks in global-map. If an entry for the key is found, its associated command is run.

What happens with commands that are bound to multiple keystrokes, as in C-x k for kill-buffer? The answer is that the keys C-x, Esc, and C-c are actually bound to special internal functions that cause Emacs to wait for another key to be pressed and then to look up that key's binding in another map; they also cause messages like C-x- to appear in the minibuffer if more than a second passes before the next key is pressed. The additional keymaps for C-x and Esc are called ctl-x-map and esc-map,[70] respectively; C-c is reserved for local keymaps associated with modes like C mode and shell mode.

For example, when you type Esc d or M-d, Emacs looks it up in the buffer's local keymap. We will assume it doesn't find an entry there. Then Emacs searches global-map; there it finds an entry for Esc with a special function (called ESC-prefix) that waits for the next keystroke and uses esc-map to determine which command to execute. When you type d, ESC-prefix looks up the entry for d in esc-map, finds kill-word, and runs it.

You can create your own key bindings by adding entries in keymaps (or overriding existing ones). Three functions are available for doing this: define-key, global-set-key, and local-set-key. Their forms are:

(define-key keymap "keystroke" 'command-name )

(global-set-key "keystroke" 'command-name)

(local-set-key "keystroke" 'command-name)

Notice the double quotes around keystroke and the single quote preceding command-name. This is Lisp syntax; for more details, see Chapter 11. The keystroke is one or more characters, either printable or special characters. For the latter, use the conventions in Table 10-2.


Table 10-2. Special character conventions

Special character Definition
\C-x C-x (where x is any letter)
\C-[ or \e Esc
\M Meta
\C-j or \n Newline
\C-m or \r Enter
\C-i or \t Tab

Thus, the string abc\C-a\ndef is equal to abc, C-a, newline, and def, all concatenated into one string. Note that control characters are case-insensitive—that is, \C-A is the same thing as \C-a. However, the characters that follow control characters may be case-sensitive; \C-ae could be different from \C-aE, for example.

The function define-key is the most general because it can be used to bind keys in any keymap. global-set-key binds keys in the global map only; since there is only one global-map, (global-set-key ...) is the same as (define-key global-map ...). The function local-set-key binds keys in the local map of the current buffer; it is useful only for specifying temporary key bindings during an Emacs session.

Here is an example of a simple keyboard customization. Let's say you are writing code in a programming language. You compile it and get error messages that contain the line number of the error, and you want to go to that line in the source file to correct the error.[71] You would want to use the goto-line command, which is not bound by default to any keystroke. Say you want to bind it to C-x l. The command to put into your .emacs file is

(global-set-key "\C-xl" 'goto-line)

This binds the l slot in ctl-x-map to the function goto-line globally—that is, in all modes. Alternatively, you can use either of the following:

(define-key global-map "\C-xl" 'goto-line)

(define-key ctl-x-map "l" 'goto-line)

These commands have the same effect but aren't really any more efficient or better. And really, you shouldn't have to know that the keymap for C-x is called ctl-x-map. We'll stick to showing the global-set-key approach for the remaining examples, but remember that you have define-key available for situations where setting the global key is not appropriate, such as when adding a mode-specific keystroke.

Other examples of key rebindings include binding C-x ? to help-command and C-h to backward-char. These key rebindings are shown below:

(global-set-key "\C-x?" 'help-command)

(global-set-key "\C-h" 'backward-char)

Notice that these could also be done as

(define-key ctl-x-map "?" 'help-command)

(define-key global-map "\C-h" 'backward-char)

After you put a key binding (or any other code) in your .emacs file, you need to "run" (or evaluate) the file for the change to take effect. The command for this is M-x eval-current-buffer Enter. Even better, you could press C-x C-e, which (as we will see in the next chapter) causes only the single line of Lisp code that your cursor is on to run. If you don't do either of these, the changes won't take effect until the next time you invoke Emacs.

10.4.1 Special Keys

A more complicated keyboard customization task is binding commands to special keys, such as arrow, numeric keypad, or function keys, on your keyboard. This level of customization takes some work, but if you like using special keys, it is well worth the effort.

Most of the special keys have reasonable names, but using them with the set key functions discussed above requires using a slightly different syntax. The name of the key appears inside square brackets rather than inside double quotes. For example, you could bind the goto-line command to the function key F5 like this:

(global-set-key [f5] 'goto-line)

And you can certainly use modifiers with your special keys. Control-Alt-F5 can be bound like this:

(global-set-key [C-A-f5] 'goto-line)

Table 10-3 lists the names of some common special keys.


Table 10-3. Special key ELisp names

ELisp Name Key
DEL or backspace Backspace
delete Delete key
down Down arrow key
end End key
f1 .. f35 Function keys F1 through F35
home Home key
help Help key
kp-0 .. kp-9 Keypad numbers 0 through 9
kp-enter Enter key on the number pad
left Left arrow key
next Page Down
prior Page Up
right Right arrow key
up Up arrow key

10.4.2 Unsetting Key Bindings

You can also remove a particular key binding with the global-unset-key and define-key commands. For example, the following lines will both remove the goto-line command bindings from our previous examples:

(global-unset-key [f5])

(define-key ctl-x-map "l" nil)

Of course, you don't need to unset any bindings if you plan to replace them with something else. But this can be useful if you have a common "typo" key that you don't want firing off when you type it by mistake.

10.5 Setting Emacs Variables

Now we will get into ways to affect Emacs' behavior—not just its user interface. The easiest way to do so is by setting variables that control various things. We already saw examples of this like auto-save-interval in Chapter 2. To set the value of a variable, use the setq function in your .emacs, as in:

(setq auto-save-interval 800)

Although auto-save-interval takes an integer (number) value, many Emacs variables take true or false values, called Boolean in computer parlance. In Emacs Lisp, t is the true value, and nil is the false value, although in most cases, anything other than nil is taken to mean true. Emacs variables can take other types of values, and here is how to specify them:

Strings of characters are surrounded by double quotes. We saw examples of strings in the arguments to key binding commands earlier in this chapter.

Characters are specified like strings but with a ? preceding them, and they are not surrounded by double quotes. Thus, ?x and ?\C-c are character values x and C-c, respectively.

Symbols are given by a single quote followed by a symbol name—for example, 'never (see the variable version-control in Appendix A).

A list of useful Emacs variables, grouped by category, appears in Appendix A, with descriptions and default values. Emacs has more than 2,500 variables—many more than are covered in Appendix A. If there is something about Emacs that you want to customize, a variable probably controls the feature (especially if what you want to change involves a number or a true-or-false condition). To find out whether any variables relate to what you want to do, you can use the apropos-variable command described in Chapter 14 to look for variables and their descriptions.

Several Emacs variables can have different values for each buffer (local values, in Emacs parlance) as well as a default value. Such variables assume their default values in buffers where the local values are not specified. A common example is starting a new text document. The local value for the left-margin variable has not been set, so Emacs uses the default value for left-margin. You can change the local value in this buffer if you like. But start a new document in a new buffer and you'll find that left-margin is back to the default value—because the second buffer's local value has not been set.

As you might expect, you can set both the default and local values of such variables. When you set the value of a variable such as left-margin or case-fold-search with setq, you are actually setting the local value. The way to set default values is to use setq-default instead of setq, as in:

(setq-default left-margin 4)

Unfortunately, there is no general way to tell whether a variable has just one global value or has default and local values (except, of course, by looking at the Lisp code for the mode). Therefore the best strategy is to use a plain setq, unless you find from experience that a particular variable doesn't seem to take on the value you setq it to—in which case you should use setq-default. For example, if you put the line:

(setq case-fold-search nil)

in your .emacs file, you will find that Emacs still ignores case differences in search commands as if this variable were still t; instead, you should use setq-default.

10.6 Finding Emacs Lisp Packages

Emacs contains lots of Lisp code; in fact, as we will see in Chapter 11, the majority of Emacs' built-in functionality is written in Lisp. Emacs also comes with several extra Lisp packages (also known as libraries) that you can bring in (or load) to add more features. Lisp packages are being added to Emacs all the time, and sometimes your system administrator will add packages obtained from sources other than the Free Software Foundation.

Appendix B lists the most useful built-in Lisp packages, along with explanations of how to use them. You can also get information about which packages are available on your system by typing C-h p (for finder-by-keyword). Briefly, the built-in packages do the following kinds of things:

• Support programming in C, Lisp, Perl, Java, and several other languages (see Chapter 9).

• Support text processing with TEX, LATEX, XML, and HTML (see Chapter 8).

• Emulate other editors (vi, EDT, and Gosling Emacs).

• Interface to operating system utilities, such as the shell (see Chapter 5).

• Provide editing support functions, such as spell checking (see Chapter 3) and outline editing (see Chapter 7) as well as text sorting, command history editing, Emacs variable setting (see Appendix A), and much more.

• Play various games and provide other forms of amusement.

See Appendix B for more details.

10.7 Starting Modes via Auto-Mode Customization

The tables in Appendix B list several major modes that are automatically invoked when you visit a file whose name ends in the appropriate suffix. Look for "suffix" in the right-hand columns of the tables to see many of the associations between filename suffixes and major modes that Emacs sets up by default. These associations are contained in the special Emacs variable auto-mode-alist. auto-mode-alist is a list of pairs (regexp . mode), where regexp is a regular expression (see Chapter 3 and Chapter 11) and mode is the name of a function that invokes a major mode. When Emacs visits a file, it searches this list (from the beginning) for a regular expression that matches the file's suffix. If it finds one, it runs the associated mode function. Notice that any part of a file's name—not just its suffix—can actually be associated with a major mode.

You can add your own associations to auto-mode-alist, although the syntax is weird if you are not used to Lisp (see Chapter 11 for the gory details). If you are programming in the Ada language, and your Ada compiler expects files with suffix .ada, you can get Emacs to put your files in Ada mode whenever you visit them by putting the following line in your .emacs file:

(setq auto-mode-alist (cons '("\\.ada$" . ada-mode) auto-mode-alist))

Make sure you include the single quote after the term

cons
and the dot between
"\\.ada$"
and
ada-mode
. The notation
'(x . y)
is just Lisp syntax for "make x and y a pair." The string
"\\.ada$"
is a regular expression that means "anything with .ada at the end of it," that is,
$
matches the end of the string (as opposed to the end of the line, which is what it matches during regular expression search and replace). The entire line of Lisp basically means "add the pair
("\\.ada$", 'ada-mode)
to the front of the auto-mode-alist." Note that, because Emacs searches auto-mode-alist from the beginning and stops when it finds a match, you can use the above cons construct to override existing mode associations.[72]

As another example, let's say you save certain mail messages in files whose names begin with msg-, and you want to edit these files in text mode. Here is the way to do it:

(setq auto-mode-alist (cons '("^msg-" . text-mode) auto-mode-alist))

Notice that in this case we are matching the beginning, rather than the end, of the filename. The regular expression operator (^) means beginning of string, so the entire regular expression means "anything beginning with msg-."

Finally, if the name of a file you are editing does not match any of the regular expressions in auto-mode-alist, Emacs puts it into the mode whose name is the value of the variable default-major-mode. This mode is normally fundamental mode, a basic mode without special functionality. However, many people like to set their default mode to text mode, accomplished by adding a line like this to .emacs: (setq default-major-mode 'text-mode)

Although we have covered many useful ways to customize Emacs in this chapter, we have really only scratched the surface. To find out more, turn to Chapter 11 and find out about Lisp programming, the key to getting Emacs to do just about anything you want.

10.8 Making Emacs Work the Way You Think It Should

Emacs not only has per-user customizations; it can also have sitewide customizations. If Emacs isn't doing what you expect it to, you might want to try inhibiting any global customization file by starting Emacs with no customization.

You can do that by using one of these command-line options when you invoke Emacs.

--no-init-file, -q
load neither ~/.emacs nor default.el

--no-site-file
do not load site-start.el

If you normally start Emacs from an icon, it's helpful to learn how to start it from the command-line for cases like this. (You may also want to use the

-debug
option sometime to help you figure out what's wrong with your .emacs file if it is messed up following a change.) Chapter 13 describes how to start Emacs from the command-line for Mac OS X and Windows users.

You can also inhibit global initialization by creating a one-line .emacs file in your home directory. It should look exactly like this:

(setq inhibit-default-init t) ; no global initialization

Start Emacs again. This file prevents Emacs from reading its global initialization file.

There's still one awkward situation: what if you're sitting down at someone else's system? You start Emacs, and all of a sudden you're faced with someone else's "private" key bindings and features. Even in this situation, there's a solution:

• Try using the command emacs -q. The -q option tells Emacs not to read the user's .emacs file before starting. By doing this, you'll avoid the user's private customizations.

• Let's say that after this step, you still don't have your own customizations. If you want to make Emacs read your .emacs file, even when you're using someone else's account, give the command emacs -u yourname. For example: emacs -u deb starts Emacs with the user Deb's initialization file (/home/deb/.emacs).

The

-u
option may not work unless you're on a network where users have a shared home directory structure. It assumes either that you have the same home directory on every system, or that you have a different home directory on every system and an up-to-date .emacs file in all of your home directories.

If all that fails, fear not. You have more options. Let's take the worst case scenario: you're on someone else's system and you can't start Emacs from the command line. Go ahead and start Emacs. You can temporarily overwrite the other user's key bindings by loading up your own key bindings file in a buffer and running it with M-x eval-buffer.

You probably should make a separate file with key bindings and other variable options rather than using your .emacs file. That's because many times your .emacs file will have requests to load libraries that exist on a path that works only from your own system. If you find yourself jumping to a lot of different machines, it's worth the effort to create a portable "rebinding" file and put it somewhere accessible like a web page or a shared file server. Then you can evaluate it manually from your current Emacs.

Загрузка...