Emacs: a tutorial for beginners


We're all set to put our feet up and wait for Santa to deliver nice presents, but before we do that we have a present for you: an all-encompassing Emacs tutorial that takes you from getting started all the way through customisation and how to use it for different purposes. So, if you're looking for something to do to give you an excuse to avoid festivities around the Christmas tree, read on. And regardless of whether Emacs is your thing or not, we wish you a very merry Christmas and an awesome, Linux-flavoured new year!

Important note

Before you read on, please read this notice: many moons ago, we (that is, Linux Format) published a series of eight tutorials on Emacs. These have been collecting dust for quite some time now, so we figured we should brush them off, merge them all into one, and put them online for everyone to enjoy - and that's exactly what you see here. But this isn't a finished product: although Emacs doesn't exactly change very often, some things may have changed since these tutorials were written, so if you spot anything please post a comment so we can fix the article.


First steps

Users moving to Linux from another OS quite understandably try to make themselves at home by hunting for tools with the same look and feel of applications they're used to. For many tasks, though, they would be better off leaving their comfort zone and trying out less familiar applications. Having been inspired by Unix and building directly on the GNU project, Linux comes with its own historical tools, at least for basic tasks. These tools are often superior to and more stable than recent Windows clones.

Unfortunately, many of the traditional GNU tools have the undeserved reputation of being difficult and hostile. A fairer statement is that they need to be learned and understood. For little effort, new and established users of Linux can get more out of their system with old apps.

In the specific area of text editing, many Linux users work with WordPad or Notepad clones, often bemoaning their lack of features. In fact, Linux has two excellent text editors, Emacs and Vi, each with its loyal followers always ready to fight each other in a worthless attempt to establish which one is better. Both are fine programs, and we hope we won't offend the Vi camp by dedicating this tutorial to some of the finer points of Emacs.

The always-on app

In many computing jobs, people need to code in various programming languages and write reports of our activity. Just like everyone else, they also write emails and browse the net. Finally, when we have some spare minutes, we like to play old arcade games like Tetris, and we're sure we're not sure the only ones. While coding, independent of the language, we use our favourite IDE, which is Emacs. If we need to go to the command line, we get it directly inside Emacs. To write reports (be they in HTML or LaTeX) we use our favourite word processor, which is Emacs. When we have to pay a quick visit to very simple websites or write an email to our collaborators... well, we have often at least two Emacs windows open, so why should we start another application? And if we want to play Tetris, guess what we use? That's right, it's good old Emacs. There is almost nothing that can't be done with this app.

One of the reasons why people refuse to use Emacs is that reputation of being difficult. This is simply underserved: it takes no more than 30 seconds to learn how to perform the basic Emacs editing operations (though you'll have to forget about shortcuts you're probably used to, such as Ctrl+Z for undo).

The other reason is that Emacs is often alleged of being bloated and slow. What some people refer to as bloated could be considered by others as feature-rich (think for instance of the quarrel over configurability in GNOME and KDE). Personally we prefer the latter interpretation for Emacs: think of it as curvy, not fat. As for the speed factor, we wouldn't consider slow an application that takes around a second to open on a 2.0 GHz Core 2 and whose start-up time can be further reduced if one wishes.

In addition to all that, Emacs features a fast console-only mode, which makes it an ideal editing tool when X is not working or when you're using a remote machine over a slow line. Is there any reason why you shouldn't consider Emacs? The only scenario that springs to mind is when you need to save to proprietary formats or formats that can't be easily classified as raw text like .doc. But we're pretty sure that Emacs will get there in the near future.

In development

Emacs is one of the main text editors on almost all Unix variants. Linux vendors offer variously customised versions and it runs on countless platforms, including Windows, and can be modified for doing a single, arbitrary task.

Though the program is in continuous evolution it's very stable. A crash of an Emacs window is as rare as the explosion of a supernova. The success of the program has prompted developers of other popular editing programs to provide Emacs compatibility modes and Emacs-like shortcuts. Over the years, several clones of Emacs have appeared. One of the most popular is XEmacs, which is still very actively developed. In fact, such is the popularity of XEmacs' popularity that the original Emacs project is often referred to now as GNU Emacs.

Although separately developed and in part incompatible, GNU Emacs and XEmacs share many features, as well as design and the programming language. XEmacs is more innovative in many respects: usually, in terms of features it's always one release ahead of Emacs. But we're really talking about no more than tertiary features for a text editor.

Anatomy of the window

The structure of a typical GNU Emacs window is pretty simple. From top to bottom we find:

  • the menu bar, where all the most used commands are within easy reach
  • the buffer, where the text of the file is displayed
  • the status bar, which displays various information about the file being edited (name, percentage, type and line number among others)
  • the mini buffer, which can be considered the Emacs command prompt

In addition to these, XEmacs has an icon bar. For this reason, it's sometimes preferred to GNU Emacs by new users. In fact, a patch is available with some distributions including Debian to add an icon bar to GNU Emacs, but this is not the default.

We will describe components in more detail (in particular the mini buffer, which implements the least obvious concepts) as we go along. For the moment, it will be enough to keep the terminology in mind.

Basic editing

It's reasonable to assume that you have either GNU Emacs or XEmacs installed. If in doubt, refer to the documentation of your distribution - Emacs should be at least an optional package. If your distro does not package Emacs, we'd suggest you to reconsider your choice.

The distribution- and desktop-independent way to launch an Emacs window is to open a terminal emulator and write emacs & at the prompt. There may be shortcuts, such as selecting 'Menu > Applications > Editors > Emacs' under Mandrake or pressing Alt+F2 then typing 'emacs' under KDE (you can replace emacs with xemacs if you prefer). This will open an Emacs window called 'scratch buffer', which should look like one of the three illustrations in this article.

You can now start typing your text into the buffer. When you're done, from the File menu you can select the option 'Save buffer as'. This action will take you to the mini buffer. What appears there is the path of the directory from which you started Emacs. Just append the name you want to give to the file and press Enter: you've just created your first file with Emacs! Quit the app by simply killing the window or selecting 'File > Exit Emacs'.

On the origin of Emacs

Emacs' name is the abbreviation of the original title, Editor Macros. The application was conceived and developed in the early seventies by Richard Stallman while at MIT as part of an artificial intelligence project. For programming, Stallman chose Lisp, universally reckoned to be one of the most elegant and coherent languages. To be more precise, Emacs is actually coded in Elisp, an original dialect of Lisp. The inspiring principles of the first Emacs version were portability and extensibility. Emacs was conceived as an Elisp engine with easy to add plug-ins (in the form of Elisp functions). When Stallman founded the GNU project, Emacs became one of its key applications.

What's on the menu bar?

To perform even the most basic task with the Emacs text editor you use the menu bar - we already used it to edit and save our first file, for instance. You're now ready to delve more deeply into the menus to discover more Emacs features - some fairly obvious, some less so. When we've acquired enough familiarity with this way of doing things, we'll throw down our graphical interface crutches and learn to stand on our own two feet by interacting with Emacs using just the keyboard.

So that we're all singing from the same hymn sheet, we'll be using the standard menu arrangement of GNU Emacs (which will for brevity's sake be referred to simply as Emacs). Before we start, it's worth noting a couple of things. If you are using XEmacs, you will notice that your menus are different from the ones described below (although you can easily recognise the common structure). Even if you are using GNU Emacs, the set of loaded extensions (and hence the menu entries) can alter depending on your chosen Linux distribution.

On the menu

A typical Emacs window will present (from left to the right) the following menus: File, Edit, Options, Buffers, Tools and Help. When you open special files like a C program or a LaTeX article, context-specific menus will pop up, but we're not bothered by this possibility at the moment - we're going to be limiting our remit to the main six menus.

File The File menu is where you open files and directories and where you save your work. It also offers disaster recovery functionalities, including the ability to revert to the previously saved version of the file being edited. In fact, when you ask Emacs to load an existing file, it automatically creates a backup copy, whose name is the old name followed by the ~ character. This splendid feature gives you the option to erase all changes performed within a given Emacs session.

Emacs also saves the text as you type, in a file whose name is identical to the one of the loaded file except for opening and closing # characters. For instance, while we type the text for this article (you didn't think we'd written it in Word, did you?) we find:

[biagio@ibmite PART2]$ ls
#emacs2.txt#  emacs2.txt  emacs2.txt~

The current version is emacs2.txt (updated only when we decide to save the file); emacs2.txt~ is the version we had before saving the current buffer for the first time; and #emacs2.txt# is the version that contains all the work we have done since we last saved (except a few characters if we am unlucky). When we click on File > Revert Buffer, #emacs2.txt# is thrown away and emacs2.txt is reloaded.

We sometimes fear that Emacs' Recover Crashed Session function will pine away through lack of use, since we're talking about a rock-solid editor on an enormously stable OS. Should you need it, though, it provides you with a list of files with candidate sessions to be recovered. Those sessions are indexed with the date. If you want to see the files index, look in the ~/.emacs.d/auto-save-list directory.

From the File menu it's also possible to print the buffer (or a region of it) and to manage the Emacs window, either by vertically splitting the current window or by opening a new window (also on another display). In the latter case, both windows will belong to the same Emacs session, which means that if you quit Emacs both windows will be closed. The best way to have two independent windows is to call Emacs twice from the command line.

Whichever way you do it, if you have more than one Emacs window open you can end up making incompatible changes to the same file. Should this happen, when you try to save the older buffer Emacs will promptly alert you that a more recent version of the file has been recorded to disk and will ask whether you really want to proceed.

Edit The Edit menu provides the usual text-editing functions for cutting and pasting areas of text - you're probably familiar with Undo and Redo, selecting, cutting and copying.

A more advanced feature is the possibility to search for a given word (either backwards or forwards from your current position) and to replace it with another word. From the Edit menu you can also access more unusual operations, such as bookmarking (a bookmark is a particular position of the cursor). Here, if there is a word or a phrase in your file that you know you will revisit pretty often, you can set up a bookmark for it by clicking on Edit > Bookmarks > Set Bookmark. To go back to the place where you saved the bookmark all you have to do is click Edit > Bookmarks > Jump To Bookmark.

Besides this elementary usage, there are plenty of other operations you can perform with bookmarks - and they can all be accessed by following Edit > Bookmarks.

As well as selecting lines and navigating through standard words and characters, the Go To submenu gives you the option of selecting a given tag from a tag table that you feed to Emacs. This is particularly useful when coding in some non-conventional language - such as custom XML dialect - or writing using non-standard conventions.

Finally, Text Properties allows you to use Emacs like a basic text editor, providing access to different types of fonts, several colours and the basic layout options. It's often necessary to tweak the standard Emacs configuration in order to get all the fonts up and running - but we'll come to that later.

Options Next comes the Options menu. Some of the configurations found here will be particularly useful to programmers. They include the Syntax Highlighting option, which colours keywords according to their semantic meaning in the context of a supported programming language. Or make good use of the Paren Match Highlighting feature, which can tell whether a closing parenthesis matches an opening one, and, if it does, which one.

Other options are oriented more towards the needs of people writing raw text - like Auto Fill. Still more are simply useful for all manners of users, such as Active Region Highlighting, which colours the selected text, or Save Place In Files Between Sessions, which puts the cursor back in its last position when opening an old file.

A ticked box indicates which options from the menu are in use. Emacs will remember only some of the changes you make to its options - to make other selections permanent, use Save Current Setting. The Options menu gives direct access only to the most used configuration options. However, from the Customise Emacs submenu it is possible to browse through all the possibilities offered by this editor. Only time and imagination limit what you can do from the buffer opened by Options > Customise Emacs > Top Level Customisation Group.

Buffer Still moving from left to right along the menu bar (or sinistrodextrally, Countdown fans) we reach the Buffer menu. This is the place where all files open in the current session are listed (in the jargon of Emacs these are called buffers). The best way to switch between buffers - while editing a large C project, for example - is to use this menu.

Tools You can use the Tools menu to access some useful shell tools directly from Emacs such as grep (for finding a given word in a list of files) and diff (in the form of the EDIFF extension). Other commands can be accessed directly from the Shell Command entry and can also be applied to a specific region. A big help for developers is the easy access to options like Apply Patch and Debugger, while the Version Control facility comes in very handy when you want to preserve multiple versions of a file.

This menu is also where you'll gain access to popular extensions for using Emacs as a mail or news reader and the Games submenu.

Help Last but not least comes the Help menu, the gateway to plenty of Emacs resources, including a multilingual tutorial, FAQs and a manual. If you need help with some specific topic, the Describe submenu is the place to look. Also worthy of note are the options which let you find packages and read the Emacs licence.

Shortcuts for speed

The menus provide a wonderful first glance at the major tools and functions offered by Emacs. But once you have a pretty clear idea about what Emacs can do, the quickest way of getting the job done is not to hunt for some hidden entry in a particular submenu, but to remember the shortcut.

As in many other programs, the fundamental keys for accessing shortcuts are Control and Alt. Pressed at the same time, with other keys, they send commands to the editor without the need to go through the menus. Forgive us for stating the obvious, but in the following, we will use notations such as Ctrl+A which means that the Ctrl and the A keys must be pressed at the same time. Some shortcuts are formed with a multiple combination of keys, like Ctrl+X Ctrl+S. In this case, you can just hold down Ctrl while pressing first X, then S.

Having specified that, let's write our first mouse-free file with Emacs. First, from a terminal emulator, give the command emacs. After that, go to the Emacs window and type Ctrl+X Ctrl+F and then 'test' (without the quotation marks) in the minibuffer (where the cursor should have been positioned by the previous command). At this point you can enter some text in the buffer. Once the test is over, you can close the session by typing Ctrl+X Ctrl+S and then Ctrl+X Ctrl+C.

By doing an ls from the terminal where you have started Emacs, you should see among others the newly-created file 'test' - huzzah!

Now, in order to familiarise yourself with the key combinations we have used, try to redo these operations several times. Once you feel comfortable with them, try to do the same operations from the menus and see the difference for yourself. This should convince you that, while they are not strictly needed, learning some key combinations is the right approach to Emacs.

Contrary to wide belief, you don't have to learn the equivalent of complicated spells in ancient languages by heart to use Emacs: you just have to get used to its menus, where you can access basic as well as more advanced functionality.

But if you want to do things quickly, always keep your left thumb close to Ctrl.

Command shortcuts

Shortcut Explanation
Ctrl+X Ctrl+F Load file. The name must be specified in the minibuffer; autocompletion of the file name can be accessed with the Tab key.
Ctrl+X Ctrl+S Save the current buffer.
Ctrl+X Ctrl+C Quit the current session. If any buffers haven't been saved, you'll be asked whether you want to save them.

Learning the basic shortcuts

Once you're familiar with Emacs shortcuts you can forget about most of the menus, and even use some features that the menus don't provide. As you read on, we'd suggest that you open an Emacs session and use the shortcuts on a test buffer until you're confident with them.

If you've been following so far you'll know that the basic operations are performed in the same way in GNU Emacs and in its XEmacs clone. We refer to the former simply as Emacs, and every command we suggest for this program is also possible in XEmacs without having to make a single change.

The key(s) to Emacs

There are two fundamental keys for issuing commands in Emacs: the familiar Control key and the much less familiar Meta key, which we will call C and M respectively. The Control key is ordinarily abbreviated to Ctrl. Aside from being shorter, our new notation C complies more closely with the one commonly used by Emacs. C and M are used to give a new meaning to standard keys when pressed at the same time with them, indicated here by a hyphen. For instance, C-X means press the keys Control and X at the same time.

You might be wondering where the Meta key is on your keyboard. If you're using a recent IBM-compatible PC, the chances are that your keyboard doesn't have one. But don't worry, Emacs hasn't let you down: you can access all the features provided by the Meta key with the Alt or Escape (Esc) key. If you use Alt, you should press it at the same time just as you would with the Meta key. Thus, M-X becomes Alt-X. But if you use Esc, you press the keys in sequence. Thus M-X translates into Esc+X, where you hold down Esc and press X.

Like many other Emacs users, we find it convenient to use Esc, but this is matter of personal taste.

A good text editor allows you to work with multiple files, displayed in a single window split into frames or in different windows. Let's see how this can be accomplished in Emacs. First, start up the application: our favourite method is the command line emacs /path/to/myfile &, where the optional argument /path/to/myfile allows us to visualise directly the file we are interested in, getting rid of the scratch buffer.

We may want to load another file without quitting the buffer. To do this, we can type C-X C-F and then enter the name (and the path if needed) of the new buffer. Now, what if we want to go back to the previous one? Just type C-X B and then enter the name of the file (without the path).

You'll notice that buffers are named after the files edited in them. If there are more files with the same name, an incremental suffix - <2>, <3> and so on - is appended. Suppose, for instance, that we are editing a file called file1 in dir1 and another file called file1 that's in dir2, having opened the file in dir1 first and then the file in dir2. The command C-X b file1 will open the buffer corresponding to the former: C-x b file1<2> will open the latter, always in the original window.

Sometimes it's useful to open files side by side, to check differences or to do some cutting and pasting. We can open a new frame by entering C-X 5 2. At first this frame will have the same content as the original frame, but a new file can be loaded with C-X C-F. An Emacs session comprises the frames spanning from the first frame or from any subframe. These frames are pretty much as the various windows you might open from a browser like Firefox. When you quit the browser, all the windows will close. In the same way, C-X C-C will close a whole session. If we want to close a single frame, the right command is C-X 5 0.

You might want to have files on the same frame for easy reference. Do this by splitting the Emacs window vertically with C-X 2 or horizontally with C-X 3. This split affects only the buffer and the mode line: after a split, the resulting window will still have a single menu bar and a single minibuffer. Emacs windows can be split into virtually as many parts as you want, just by repeating the splitting commands. The space taken up by any part of a vertically split window can be changed at will by dragging the central mode line with the mouse - pretty much as you would the contour of the border of any other window in X11.

Another shortcut worth knowing is C-X I. When followed by the name of a file (typed in the minibuffer, where the command will put the cursor automatically), it will paste in the content of that file starting from the position of the cursor.

Getting out of trouble

You might find yourself getting stuck in the minibuffer while you're getting used to Emacs. The way out is to repeatedly press C-G, which sends the cursor back to the buffer.

A cursory point

The natural reference point in any editor is the cursor. Sometimes, when performing operations such as marking a region it's natural to refer to the cursor's position as an indication of where the mark starts and ends.

In fact, it would be more accurate to talk about the 'point'. This is a more abstract concept that the cursor simply represents. Point and cursor are not completely interchangeable: for specific applications, the cursor is on a character, while the point is to the left of that character. For instance, taking the above example of marking a region, the beginning and the end of the region is set not by the cursor, but by the point.

Although this distinction isn't important in most contexts, it's worth understanding to avoid confusion.

Search and replace

Despite its versatility, Emacs is first and foremost an editor, and focuses on editing functions - as it should. Basic editing operations consist of cutting and pasting (or yanking, in Emacs language), marking a region and running search and replace.

This last finder function can be quite sophisticated, but we'll start at the most basic level. To find the word 'Cake' in the text, we can type C-S Cake into the minibuffer to search forwards from your current position and C-R Cake to search backwards.

Searching for the word 'cake' will match not only 'cake', but also 'Cake', 'CaKe' and any other combination of upper- and lower-case letters. When an upper-case letter is inserted in the word to be searched, the search becomes case sensitive.

So, C-S Cake will find 'Cake', but not 'cake' or 'CakE'. More fine-tuning is possible through the use of regular expressions, but that's a bit more advanced.

To run a search again, enter C-S C-S for a forward search or C-R C-R for a backward search. This also works if you searched forwards last time and now want to search for the same word but backwards.

Another useful function is searching and replacing text. To do this, execute M-X then type replace-string. Press Enter, write the string to be replaced, then after another Enter type the string to replace the undesired one. Suppose we have the file food, whose content is the line 'VI is my favourite food. I love VI!'. This doesn't sound right, does it? We want to replace it with a more appropriate statement. So we open the file with Emacs and with the cursor on the first character we execute

M-X replace-string, followed by Enter. After that, the minibuffer will read Replace string:, so we write 'VI' and press Enter. Then, the minibuffer will show the line Replace string VI with: and we write 'pasta' and again press Enter.

The content of our buffer now will be: 'pasta is my favourite food. I love pasta!' and this is indeed worth saving (with C-X C-S). Any text between the active point and the end of the buffer is replaced, so it won't affect words above or to the left of the cursor. The number of replacements is displayed in the minibuffer when the operation is concluded.

Again, be careful about case sensitivity. Suppose our buffer is 'Vi is my favourite food. I love vi!'. If we search for 'VI' there will be no match, and the buffer content will be preserved. If we ask to replace 'Vi' the replacement will be case sensitive. If we ask to replace 'vi' with 'pasta', both 'Vi' and 'vi' will be substituted, but the first will preserve its upper case V, which means it will be replaced by 'Pasta' and not by 'pasta'.

If you want more precision, you can use the query-replace function, which you can access by pressing M-X and then typing query-replace. It's like replace-string, except that you can choose which entries should be replaced, case by case.

Undo and redo

To delete the last change made, the shortcut is C-X U. This is the equivalent of the popular Ctrl+Z for the Undo command used in other operating systems. There is no obvious limit to the number of changes Emacs will undo, since this number can be chosen at will. To redo a change there's no need for another command, since this operation corresponds to undoing the latest undo. If you want to redo it's just matter of moving the cursor so that the last undo will be registered as the last operation (so that you exit the undo cycle) and pressing C-X U.

Doing more with shortcuts

If you've been following this from the beginning, you will have mastered many of the program's fundamental keystrokes (as we Emacs people call shortcuts). But there's still more, so we're going to complete our overview of the most used keystrokes, learn how to interact with the Emacs help system and finally take a quick look at more advanced Emacs features that you'll be keen to explore.

And so to those keystrokes. The easiest way to mark text in Emacs is by left-clicking at the beginning of the region we want to mark and right-clicking at the end of it. The fastest way is to use C-space ('C' being Control, 'space' indicating the space bar) at the beginning of the region and M-W (where 'M' is the 'Meta' key) at the end. By marking a region we record the corresponding text in a register. If we want not just to mark but also to cut the region, we need to replace M-W with C-W. When consecutive words at the end of a line are involved, C-K (deletes and stores in a register everything from the active point to the end of the line) is a useful shortcut for the marking and cutting operations. Finally, C-Y pastes (or 'yanks' in Emacs jargon) the last copied or cut region starting from the active point.

Navigating the buffer

Navigating an Emacs buffer doesn't need keystrokes much these days, as keyboards are equipped with Page Up, Page Down, Home, End and arrow keys. Also, the Emacs window provides a handy scroll bar on the left-hand side, and a left-click with the mouse on a point on the buffer will move the cursor to that point. But there are still two useful keystrokes that do not correspond to keys on a standard keyboard. These are C-A, which moves the cursor to the beginning of the current line, and C-E, which moves the cursor to the end of it. They do the same in the bash command line.

Square up to rectangles

In many standard text editors it is often complicated to work with columns as a whole. Not so with Emacs. It handles the task easily with the rectangle class of functions. Suppose we have a buffer that looks like the one below, and we want to delete the LUNCH column.

Tea	Bread	Chicken
Coffee	Soup	Pasta
Cereal	Curry	Pizza
Milk	Salad	Beef

If we want to reinsert the column at the end, we move the cursor to the end of the first line and insert as many blanks as needed (by typing M-n space, where n is a number, or by pressing the spacing bar n times). Once the position of the cursor corresponds to the point where we want to insert the column, we execute C-X R Y. This gives us something like:

Tea	Chicken	Bread           
Coffee	Pasta	Soup            
Cereal	Pizza	Curry           
Milk	Beef	Salad

With a few simple keystrokes (overall around three seconds of work) we have been able to swap the position of two arbitrary columns. And that's why we should all be using Emacs. Other useful rectangle commands are:

  • C-X R D Delete the rectangle without storing it.
  • C-X R O Insert a blank rectangle (change the spacing between columns).
  • C-X R R a Copy rectangle to register a ('a' is any character).
  • C-X R I a Insert rectangle from register a.
  • C-X R C Replace the selected rectangle with spaces.

Meet the minibuffer

There is a key element of Emacs that we have overlooked so far: the minibuffer. We have often referred to it as the place where you type commands to complete keystrokes. But the minibuffer isn't just for keystrokes: it is the tool that allows you to interact with the editor. Each keystroke is associated with a command, but there are many more commands than there are keystrokes. To get to these extra commands, we need to use the minibuffer.

Accessing the minibuffer directly will let us exploit the full power of Emacs. But where can we learn all the Emacs commands? The manual is the obvious place, but sometimes we can just use our intuition and the minibuffer itself to guess a command. Suppose, for example, that we are looking for a particular yank feature. We execute M-X (which will take us to the minibuffer) and start to type 'yank', followed by a tab character (which activates the autocompletion feature). If there is only one possible command, it will be automatically completed. Otherwise, the window will split vertically and a Completion buffer will be created to display all the possible commands. At this point, it will just be a matter of selecting the correct alternative.

Getting help

When intuition does not take us very far, it is time to use the sophisticated Emacs help system. Diehard Emacs users will remember a time when the backspace key did not delete words (back then, this function was delegated to the delete key or to the delete-char command), but was the gate to the help system. At that time C-G was the only way to get out of trouble when backspace had been hit by accident. Nowadays, when the backspace plays a more conventional role, access to the help system is provided by C-H (or indeed by the rightmost menu).

There are several ways of asking for interactive help. The most common ones are the following:

  • C-H A Command-apropos. When followed by a substring, this gives a list of commands that contain that substring. It is then possible to click on a command to obtain the corresponding description.
  • C-H B Displays all valid keystrokes and the commands associated with them. Useful when new keystrokes need to be defined.
  • C-H C Followed by a keystroke, displays the name of the command corresponding to that keystroke.
  • C-H K Followed by a keystroke, displays the documentation of the corresponding command.
  • C-H W Followed by a command, gives the corresponding keystroke and the path to access the command from the menu.
  • C-H F Followed by the name of a function, returns the corresponding documentation.
  • C-H I Allows you to access the info documentation reader ('man info') for further details.
  • C-H T Leads to the Emacs tutorial, where you can learn by examples.

Reference cards

Confused by Emacs keystrokes? Having a hard time remembering them? Or are you just looking for a quick summary? Type 'Emacs reference card' into Google and hang your favourite result on the wall beside your desk.

How to customise Emacs

One of the many reasons to pick Emacs as your editor of choice is its unbelievably high level of customisability. Extending Emacs with options is a huge topic that could easily fill a book, so our goal here is to introduce the general strategy and basic concepts so that you can use them to go further on your own. A minor point: to make them clear in the text, We'll present each option in upper case, such as Reset To Saved, even if it's written slightly differently as Reset to Saved on screen.

OK, let's start by opening up the Options menu.

The Options menu

A handful of the most used and most useful setup options can be accessed through this menu, for quick customisation. Here's what they do in detail, from top to bottom:

    >Syntax Highlighting This gives you coloured keywords when writing code or text in any supported language (basically, all programming and markup languages are supported).
  • Active Region Highlighting When it's turned on, this option uses a different background colour to differentiate a region marked for an operation such as cutting.
  • Paren Match Highlighting Particularly useful when programming, this shows with colour whether the parenthesis under the cursor is balanced correctly.
  • Truncate Long Lines In This Buffer Use this to prevent text belonging to a single line from being pushed on to more lines, independently of the extension of the line itself.
  • Word Wrap In Text Modes This is the reverse of the previous option: whenever the characters in a line exceed a default number, that line is automatically broken.
  • Case-Insensitive Search Select this to toggle between a case-sensitive and case-insensitive word search.
  • Use Directory Names In Buffer Names Here, you can give a unique name to buffers referring to files with the same name located in different directories by adding the name of the directory to the buffer name.
  • Save Place In Files Between Sessions If this is selected when you reload a previously edited file, the cursor will return to where it was when the previous session was closed.
  • Automatic File De/compression Decompress files on loading then re-compress them on saving.
  • Enter Debugger On Error and Enter Debugger On Quit These are mainly useful for software developers.
  • The Mule submenu The gate to customising the default language, encoding and input methods.

Each option (excluding the submenus) has a box next to it. To set an option is just matter of checking this box. However, by default, these settings are lost on exit. If you want to save them, the solution is to click on Options > Save Options. This will create a .emacs file (if not already there) in your home directory where the desired features will be recorded, which is loaded at startup by the editor.

Customising with Custom

The last entry in the Options menu opens the Custom buffer. This provides an intuitive interface for tweaking just about every aspect of Emacs. The buffer is navigable, pretty much like an HTML page in a web browser, and highlighted boxes show what look like hyperlinks. Various options are grouped according to the general topic they refer to. A given customisable option can be reached from within any of the groups to which it is reckoned to be relevant. Apart from the Options menu, it is possible to access the customisation buffer with the command

M-x custom

This opens the top-level customisation buffer, in which all parent groups are displayed. A specific option is reached by following a logical path through the groups down to the appropriate entry. It can take some time to familiarise yourself with this approach, but the level of personalisation it allows you to achieve is a good reward for the time spent customising Emacs in this way.

Each screen has a set of general options for setting and saving globally the customisation you've performed in the buffer. They are:

  • Set For Current Session This applies the new options to the current session.
  • Save For Future Sessions Ensures the new values are the default for future Emacs sessions and saves the options for the current one.
  • Reset Sets all your currently edited options back to their previous values.
  • Reset To Saved This sets all modified options back to the previously saved values.
  • Erase Customisation Use this to reset all options in the current buffer back to their default settings.
  • Finish Takes you to the previous Custom buffer (or the buffer from which Custom was launched).

Clicking on the Status button next to each option opens a drop-down menu that gives you access to those very same options, but here you configure not the whole buffer but that single option. Backwards navigation is provided by the Go To Parent Group option, which highlights one or more parent groups (depending on the current group). An editable option can have several forms: if a value is required, you can just enter it; if different or multiple choices are offered, they can be entered by selecting the one you want from a drop-down menu (if they are mutually exclusive) or by checking the box next to them (if more sub-options can be set at the same time).

If you need help for the various options, click on the Show button (clicking on Hide will decrease the level of verbosity). The strategy for setting a value is straightforward: navigate the custom buffer to the option you want to change, then perform the wanted changes and finally press Save For Future Sessions or Save For Current Session, according to whether you want the modification to be temporary or permanent. Reset and Reset To Saved can be used when the end result looks worse than the initial configuration.

Customise appearances

The particular customising we'll be doing is to change a few popular options like the background and foreground colours and the dimensions (or 'geometry', as X calls it) of the window. As we already described in detail how to set Emacs properties with Custom, we'll start from there.

Setting font colours with Custom

First, we must identify which option we need to change:

M-x customize-face <ENTER> default <ENTER>

We've taken a direct shortcut to the face group (customize-face), where colour information is held, and default indicates that we want to act on the properties shared by all fonts. We then scroll down to the Foreground and Background fields and change them to the values we want. In the screenshots, we've chosen 'wheat' for the foreground font, and 'dark slate gray' for the background, which by the way are the default options on Mandriva. Other distributions including Debian use the classic black-on-white scheme.

You can choose any colours you like but be careful: when we say "any colours you like" we really mean it: Emacs does not prevent you from using silly default combinations like grey on white or, even worse, black on black - but you'll probably realise that in those cases your working environment won't be that comfortable for you, or at least for your eyes.

Emacs and the command line

It is always possible to resize the window by left-clicking on the bottom right corner and dragging it around, but this can be inconvenient. It would be better to start Emacs with a size we are comfortable with that we can set as a default. Enter the command line.

As with many other Unix applications, Emacs was born to be launched from a terminal (or a terminal emulator). In the Unix tradition, the command line can be used to set several parameters, among which are those we want to change. The look and feel of our window is reproduced with the command

emacs -bg DarkSlateGray -fg Wheat -geometry 80x40 -fn 10x20

The options -bg and -fg set the background and the foreground colours respectively, while -geometry controls the dimensions of the window and -fn sets the font size.

The geometry is measured in characters per column by number of lines. The window should be wide enough for you to type comfortably in. Bear in mind that Emacs can only use fixed-width fonts. These fonts are usually specified by the width and the height in pixels, as in 12x24. By default, the editor uses the so-called misc fonts from the X11 font directory. The available options can be deduced by looking in /usr/X11R6/lib/X11/fonts/misc. The file named 10x20.pcf.gz, for instance, indicates a font that's 10x20 in size.

Fonts can be changed interactively: pressing the Shift key and the left mouse button produces a drop-down menu from which you can select a new font.

The .Xdefaults file

If you don't like typing a long command every time, there are several ways around this. One is to add the line

alias em="emacs -bg DarkSlateGray -fg Wheat -geometry 80x40 -fn 10x20"

to your ~/.bashrc file, so that any time you type em you will get the desired command.

A second way is to create a file called "em" which contains the lines

emacs -bg DarkSlateGray -fg Wheat -geometry 80x40 -fn 10x20 "$@"

Make it executable with chmod +x em and then (as root) copy it into /usr/bin. As before, when you type em the editor will start up with your customised interface.

Both approaches are OK if you want to stick with a given customisation, but there is a third possibility, provided by the .Xdefaults file, which is more suitable when you're changing things often. .Xdefaults is a file located in the home directory of each user whose function is to set the properties of X applications. If there's no .Xdefaults file present in your home directory, you can safely create one. Each application you want to control should have a section in the .Xdefaults file. Here's an example of a possible .Xdefaults section for Emacs:

emacs*Background: DarkSlateGray
emacs*Foreground: Wheat
emacs*pointerColor: Orchid
emacs*cursorColor: Orchid
emacs*bitmapIcon: on
emacs*font: 10x20
emacs*geometry: 80x25

Note that we've also set the colour for the cursor and the pointer as 'orchid'.

The syntax of each entry is

emacs*keyword: value

where possible keywords are listed in the Emacs man page.

Meet Dot Emacs

There is another dotfile we've mentioned but have never shown in detail: .emacs. This is the place where all Emacs-related customisation is recorded. In particular, this is where all the options you set up with Custom are written to. If you've been following this tutorial from the beginning, you should have the following ~/.emacs in your home directory.

 ;; custom-set-variables was added by Custom -- don't edit or cut/paste it!
  ;; Your init file should contain only one such instance.
 '(current-language-environment "English")
 '(global-font-lock-mode t nil (font-lock))
 '(save-place t nil (saveplace))
 '(show-paren-mode t nil (paren))
 '(text-mode-hook (quote (turn-on-auto-fill text-mode-hook-identify)))
 '(transient-mark-mode t)
 '(undo-limit 30000)
 '(uniquify-buffer-name-style nil nil (uniquify)))
  ;; custom-set-faces was added by Custom -- don't edit or cut/paste it!
  ;; Your init file should contain only one such instance.

Just by reading this you should be able to recognise all the options that we've been setting through Custom and the Options menu. As an exercise, click on the Options menu and try to identify which option corresponds to which line. But why all those semicolons, accents and parentheses? Well, these are imposed by the syntax of the programming language that the .emacs file uses, which is Elisp.

Editing the .emacs file by hand is by far the most powerful way of customising Emacs - but it is also the toughest. Luckily, we just want to set the background and the foreground colours and another couple of options, so we don't need to go into much detail. All that we need to do here is to prepend to the file the following lines:

(set-background-color "DarkSlateGray")
(set-foreground-color "Wheat")
(set-cursor-color "Orchid")
(set-frame-font "10x20")

These create the look and feel that we use on our own Emacs configuration. Note the format:

(set-<property> "<value>")

where property is the property we want to set (background colour, for example) and value (within quotation marks) is the value we want to give it.

To experiment with setup options, you can execute the corresponding commands on an Emacs window. For instance, to change the background colour of the current window to black, run

M-x set-background-color <ENTER> black <ENTER>

Note that in this case there are no quotation marks around the colour name.

You can combine these four techniques for customising the appearance of Emacs. Which approach is the best is really a matter of personal opinion and taste. As for us, we're purists: we tend to delegate X-related options to the .Xdefaults file and implement any Emacs-specific customisation inside our .emacs - let's take a look at how that works...

Shaping .emacs

Using the initialisation file, known as .emacs, an Emacs user can take fine-grained control over every single aspect of the editor. It's one of four customisation techniques we already explored, and we'll be looking at it in more detail here.

The .emacs file is a collection of Elisp code (Elisp being the programming language that Emacs is written in) that can overwrite all default settings of the editor and even extend it. With time, manual editing of the .emacs file will probably become your favourite way of modifying Emacs, and the Custom buffer and the Options menus will be forgotten. Before you get to that point, though, you will have to learn some very basic concepts of Elisp.

Getting started

We already showed you an example of a typical .emacs. This was a 'mixed' type: some lines were written in the Custom interface, others we added ourselves. With time, you will learn how to phase out the Custom portion by hard-coding the changes yourself. While your .emacs file still includes Custom lines you must respect two rules: never edit the lines written by Custom; and add the manually-inserted lines before the section owned by Custom.

Meanwhile, we need to stay on friendly terms with Custom. In the .emacs file, sections from Custom are marked by the following, which appears after the first Custom line:

;; custom-set-variables was added by Custom -- don't edit or cut/paste it!

Using one or two semicolons to start comments is a characteristic of Elisp. Multiple comment lines are allowed, but each of them must have a leading ';;' - any blank lines are ignored in Elisp.

The most basic chunk of code you'll work with is a statement, or assignment. In Elisp (as in Lisp, from which Elisp was derived) statements are enclosed between two parentheses. The general form of a statement is

(function-name argument1 argument2 ... argumentN)

where the number of arguments depends on the function invoked. For instance, we already showed you how to set the colours and styles of your Emacs appearance using statements like

(set-background-color "DarkSlateGray")
(set-frame-font "10x20")

Here, the first word is the function (ie set-frame-font), and that particular function accepts only one argument (ie "10x20"). In "10x20" the quotes are important: they indicate that the enclosed set of characters is a string.

We will mainly look at statements that take the forms

(setq variable value)


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

The first statement is used to associate a value to a variable, in order to overwrite a default. The second allows you to define new keystrokes.

Making a statement

A sample application of setq is

(setq transient-mark-mode t)

This code states that the marked region will be highlighted. The first term (setq) is the operation we want to perform, the second (transient-mark-mode) is the variable on which it acts and the third (t) is the value. The value is t because transientmark- mode is a logical variable and, like any other logical variable, it can have two values: true and false. In Elisp logical true is indicated by t and false by nil.

If you think 'command looks a little odd in the second statement form above, note that non-Elisp variables (or 'symbols') need to be prefixed with a single quotation mark when passed as an argument to operands, as in

(global-set-key [f6] 'replace-string)

Here the function is global-set-key, which will be described in more detail below. Its two arguments are a combination of keys and an action. The action must be prefixed with '. If it weren't, Elisp would try to evaluate replace-string as if it were a variable. And since this is not a variable, an error would occur.

It takes some time to learn when you should use the single quotation mark. As a general rule, if there is an error you really don't understand, the odds are that you have forgotten a '. The Elisp interpreter executes Elisp files on request (such as when invoked with "M-x eval-buffer") or automatically (for initialisation files). If an error occurs, the execution stops at the problematic line, and every following line will be ignored. You can change this by inserting error recovering hooks in the .emacs file (find out how at www.dotemacs.de). An easier alternative is to test every statement of your code in a scratch buffer before it is inserted in the .emacs file.

Fresh keystrokes

Let's put what we have learned so far into practice. If you use Emacs pretty frequently, you'd probably like to have easy access from your keyboard to the functions you use the most. You can do so by adding new keystrokes. This requires you writing some new lines in your .emacs file, one for each new keystroke:

;; key bindings
(global-set-key [f1] "\C-x1")
(global-set-key [f2] "\C-x2")
(global-set-key [f3] "\C-x3")
(global-set-key [f4] 'describe-key)
(global-set-key [f5] 'eval-buffer)
(global-set-key "\C-xl" 'goto-line)
(global-set-key "\C-xs" 'shell)
(global-unset-key [insert]

The first line is a comment. Its purpose is to remind you what the following block does, should you come back to the code at a later stage. The second line uses the function globalset- key to associate the key F1 with the shortcut C-x 1, using the special Control key, indicated by \C, pressed at the same time as X (indicated by the hyphen), then 1 (note that there are no blanks in "\C-x1"). This key combination is associated in turn with the function delete-other-windows (in case you've forgotten, this function closes all non-active subframes).

The first argument can be a keystroke or a single action key on the keyboard, such as F1, as in our example. Here we have bound actions to function keys from F1 to F5, but it is possible to bind actions to function keys up to F35. Non-single-character keys are enclosed in square brackets, and include [end], [home] and [insert]. The second argument of global-set-key is the name of a function, which has to be preceded by a single quotation mark. It could be replaced by a keystroke referring to it, as in "\C-x1" - in which case the keystroke must be enclosed by double quotation marks - but it would be better to free this keystroke for later use with the function global-unsetkey. This also works with action keys.

The functions local-set-key and define-key are similar to global-set-key. local-set-key is useful for defining keystrokes that are local to a given buffer. define-key is equivalent to global-set-key, but has a more complicated syntax and requires you to know in more detail how keymaps are handled in Emacs. The advantage is that it allows you to define keystrokes in situations in which global-set-key can't be used, as when the keystroke is specific to a given mode.

Defining variable value

Many Emacs variables can be initialised with either numerical or logical values. Those variables can be modified with the use of the functions setq, which we used earlier, and setq-default. The former sets local values of variables, while the latter acts on the default. The syntax of the two is exactly the same:

(setq variable value)
(setq-default variable value)

To highlight syntax when editing program files, you'd run

(setq font-lock-maximum-decoration t)
(setq font-lock-maximum-size nil)

Another example, used to set the undo limit, is

(setq undo-limit 30000)

Unfortunately, there is no easy way to guess whether a variable can be set with setq or setq-default. The general strategy is to try with setq first, then move on to setq-default if setq does not have any effect on it.

Customising Emacs via its initialisation file is the most powerful way of extending it. As well as the uses we've shown you here and previously, .emacs can be used to load Elisp code, define functions and 'hooks', and more. The Elisp syntax might take some getting to grips with, but there are so many examples in the wild that there is hardly anything left to be discovered. Why not take a look around the Emacs and Elisp manuals that come with the Emacs distribution?

Working with extensions

Did we ever mention that Emacs is extensible? To clear any doubt, we'll say it here: Emacs is extensible. And just to be sure that you got the point, let us repeat it: Emacs is extensible.

Yes, just as it's possible to run a global crime ring while never leaving your underground cave lair, it's quite possible to browse the web, play games and listen to La Traviata without leaving your favourite text editor. To put this to the test, we will take a look at some of the top Emacs extensions not distributed with the editor (the selection is entirely subjective), leaving in our wake the widespread belief that Emacs is just a text editor. The Loading Simple Extensions box, below, gives brief instructions on how to make them work. Most are Elisp files (.el), the language in which most of Emacs is coded.

Loading simple extensions

Emacs comes packed with several Elisp extensions that cover many aspects of text editing and interfacing with command-line tools. Its initialisation routines take care of loading the default extensions. But how can the editor know about the third-party extensions that we are using? If the extension consists of a single self-contained file the easiest way is to execute

M-x load-file <ENTER> /path/to/file

For instance, suppose that we put all our favourite extensions in a directory called elisp below our home. To load the Nero extension, we'd need to execute

M-x load-file <ENTER> ~/elisp/nero.el

Some extensions might require external tools. For instance, nero.el, used in the above example, makes use of the Lynx web browser, which should obviously be installed for this extension to work at all.

So what are we waiting for? Let the fun begin!


WEB: www.barzilay.org/misc/calculator.el

CATEGORY: Utilities

One of our favourite Unix tools is the simple but powerful command line-based calculator Bc. Still, until we discovered this extension, we had to leave Emacs and switch to an Xterm whenever we needed to use it. Now we can have the numbers displayed right in our editor.

To call the calculator function, it is just matter of executing

M-x calculator <RETURN>

Then, you can start to add, subtract, multiply and so on. The results will be displayed in a dedicated buffer.


WEB: http://emarsden.chez.com/downloads

CATEGORY: Amusements

Of course Emacs can brew coffee! Sceptical? Then load this extension and run

M-x coffee

Answer the questions (using Tab will display the available options), go to the coffee machine and collect your deserved hourly dose of caffeine. Warning: the required RFC2324-compliant coffee machine (see ftp://ftp.isi.edu/in-notes/rfc2324.txt) is not provided. You will also need W3 installed on your system (ftp://ftp.xemacs.org/pub/xemacs/emacs-w3).


WEB: http://emarsden.chez.com/downloads

CATEGORY: Utilities

Are you ever unsure of the meaning of an obscure word? If so, the solution is this very nice Emacs extension. Select a word in the buffer, then type

M-x dict

You will be prompted for a word to enter; the one you selected will be the default. Press Enter and an explanation of the word will pop up. Since this extension uses www.dict.org, you will need to be connected to the internet, and more than that, the Emacs web browser W3 (ftp://ftp.xemacs.org/pub/xemacs/emacs-w3) needs to be installed.


WEB: http://pop-club.hp.infoseek.co.jp/emacs/emacs-wget

CATEGORY: Internet

Wget is a favourite old command-line tool for retrieving websites. Hang on a minute, did we say command line? Sorry, we meant Emacs. If you don't believe us, try this extension. Once it is correctly set up, execute

M-x wget

and enter the URL to retrieve. Not only does wget correctly work from within Emacs, but the output displayed in the minibuffer is also identical to that of the shell.


WEB: http://sourceforge.net/projects/erc

CATEGORY: Internet

Emacs as an IRC client? Why not? Install this extension, then add to your .emacs file the lines

(require 'erc-auto)
(autoload 'erc "erc")

and execute

M-x erc-server-select

The data that needs to be inserted should be familiar if you're a habitual user of this network.


WEB: http://lists.gnu.org/archive/html/gnu-emacs-sources/2002-01/msg00017.html

CATEGORY: Internet

This extension transforms Emacs in a web browser, using Links as an engine (hence Links must be installed on your system). After loading the extension, from a buffer, try

M-x links-browse-url

At the prompt, specify a web address, such as www.linuxformat.com. This will show the website content on a new Xterm. If you want the content displayed in a dedicated Emacs buffer, replace links-browse-url with links-browse-url-within-buffer. Now the content of the website is editable, but you can't follow the hyperlinks.


WEB: www.asahi-net.or.jp/~pi9s-nnb/monk

CATEGORY: Multimedia

Ultimately if we want to win over all users to Emacs, we should also provide decent multimedia applications. One that definitely fits in this category is Monk. This is a front-end for various command line multimedia applications (including Ogg123, Timidity and Mpg123). To use it, install the extension, add

(autoload 'monk "monk" nil t)

to your .emacs, open a new Emacs window and run

M-x monk

Insert the name of a playable file (including the path) and relax. If you just hit Return, monk will attempt to play an audio CD. Don't forget to insert one!

Just the beginning...

One of the zillion hilarious jokes about Emacs says that our editor "is a good operating system, but Unix has more applications". Is that really still the case? Just take a look at the Elisp catalogue at www.damtp.cam.ac.uk/user/sje30/emacs/ell.html, and you will realise that there is hardly an aspect of Linux that can't be accessed from within Emacs. True, the interface doesn't have any of the bells and whistles of modern desktop environments, but we're proved the point that Emacs is one of the most versatile and useful apps out there. Try it for yourself: load a bunch of extensions that cover your most-used tasks, open an Emacs windows and try to do everything without leaving it. Need SSH? Execute C-x 2, move to the lower buffer and open SSH with the command M-x ssh. Need another application? Just superimpose another buffer. Don't need a task any longer? Kill the corresponding buffer.

Thanks to the Emacs telepathy.el extensions we know what you're thinking: this is really cool and will gain us several geek points, but what's the point in 2005 when fully fledged desktop environments shine all around us? Well, several times so far we have said that everything is possible with Emacs, and we decided that the time had come to prove it to you. Now, if Emacs is a fair IRC client, a nice web browser and a reasonable SSH client, can you imagine how far ahead of the pack it is when it comes to text editing?

Installing extensions

By now you will have probably visited www.damtp.cam.ac.uk/user/sje30/emacs, downloaded coffee.el, bought that exotic RFC2324-compliant coffee machine and become hopelessly frustrated with your computer, asking yourself why when you execute

M-x coffee

you get a 'No match' error instead of a cup of steaming java.

Stop yelling at your computer: there's probably nothing wrong with it. Make yourself a cup of tea instead, sit in your most comfortable armchair and keep reading: when you go back to your desk, you won't have any problem in loading any working Emacs extension, including those that brew coffee.

Step 0: read the docs

When we buy a new appliance, the first thing we do is plug it in and switch it on. Sometimes this method works, and sometimes it does not. Either way, what we really should do (and we will end up doing anyway if we break something) is to read the instructions carefully before doing anything else. Although most fridges work in the same way, there might be some knobs to fiddle with to achieve the best performance. And though all TVs work in roughly the same way, how channels are tuned and recorded on your new set might be different enough to put you at a loss.

The same thing applies to software: although you might think that you know what you are doing, you should always read the instructions. Like home appliances, Emacs extensions can be fairly simple or very sophisticated. Some extensions consist of just a single file. They are the equivalent of fridges because they mostly work in the same way: they are written in Elisp (the scripting language in which most of Emacs itself is written) and can be loaded by executing

M-x load-file ENTER /absolute/path/to/yourfile.el ENTER

However, you should read the instructions, since at the very least you have to understand how to call the extension's main routine. Fortunately, this is very easy. Usually the main Elisp file of the extension has instructions on how to get it working. Open the extension file with Emacs and read the comments in the first lines of the source code, until the real code starts. These comment lines, usually no more than 20, will provide you with all you need to know to make the extension work.

More complicated extensions (the TV in our example) span multiple files and are distributed as tarballs. These usually have a Readme file in the source top directory that will explain how the package must be used. This changes slightly from one application to the next, but the bulk of the installation process consists of copying the files to a sensible location and loading the corresponding functions, either manually or by adding the appropriate entries in the .emacs file.

Step 1: choose a good home

Spreading extensions across the filesystem is not a good idea: it's best to put all your extensions in one place. Fortunately Emacs offers well-defined locations where Elisp extensions can be found. Those places are recorded in a variable called load-path, whose value tells the editor where to look for functions that are part of extensions. In a standard Emacs 21.4 installation, the load path consists of the directories:

  • /usr/local/share/emacs/site-lisp
  • /usr/local/share/emacs/21.4/site-lisp
  • /usr/local/share/emacs/21.4/leim
  • Subdirectories of the above.

Should you administer your system yourself (rather than having it done for you by a central admin), it would be a good idea to put your extensions in /usr/local/share/emacs/21.4/site-lisp (or in an appropriate subdirectory), since in this way they will be immediately available to all users.

If you do not have the root password, you can create a private Emacs repository in your own home directory. For instance, simple extensions can go in ~/elisp and more complex extensions can be hosted in a subdirectory.

As an example, let's have a look at emacs-wget, which is one of the extensions we already looked at. You can extract the source emacs-wget-0.5.0.tar.gz in the following way. From a terminal emulator, execute

cd ~/elisp
tar xvzf /path/to/emacs-wget-0.5.0.tar.gz

This creates the directory ~/elisp/emacs-wget. Home at last!

Step 2: modify your .emacs

Whatever you call your personal Elisp repository, this won't be in the load path. This means that Emacs won't know that it should look there for extra extensions. If you want to use them, you'll still need to load them by hand - an operation that can become tedious if you need to load a large number of files in a given order.

To avoid playing with applications by hand every time we want to load them, we can modify the load path by acting on the .emacs file. The line

(add-to-list 'load-path "/home/biagio/elisp")

adds the top level of the repository to the load path (remember to replace 'biagio' with your username). Placing a single-file extension in /home/biagio/elisp will now be like connecting the plug of our new fridge. We still need to turn it on, by running

M-x load-library ENTER myextension ENTER

Note that load-file, which we have been using up to now, is replaced by load-library. The advantage is that we don't have to specify the full path of the extension: just the name (without the .el extension) will do.

We can go even further and autoload extensions. Single file extensions are the easiest to autoload. For instance, for coffee.el we insert in the .emacs the line

(autoload 'coffee "coffee" "It's about time you worked!" t) 

Here, the relevant function is autoload. Its arguments are, from the left to right, the name of the file (without the .el suffix and with a leading apostrophe); the name of the main function (within quotation marks); an optional descriptive string (within quotation marks) that will be displayed when calling the interactive help for the function; and an optional interactive type (true or nil, depending on the function, with nil being the default). Now in each Emacs session you will be able to execute

M-x ENTER coffee ENTER

For more complicated applications, we also need to add the subdirectories of ~/elisp to the load path. This is easily accomplished by adding another line to our ~/.emacs:

progn (cd "~/elisp") (normal-top-level-add-subdirs-to-load-path)) 

The Emacs IRC extension, ERC, gives us an interesting example of autoloading extensions. There's a dependency issue here: erc-auto must be loaded before erc. The solution is:

(require 'erc-auto)
(autoload 'erc "erc")

Finally, you might need to autoload multiple functions from the same file, like in this example:

(autoload 'monk "monk" nil t)
(autoload 'monk-open-new "monk" nil t)
(autoload 'monk-other-window "monk" nil t)
(autoload 'monk-other-frame "monk" nil t)

Here, potential problems connected with dependency issues are dealt with in the Elisp code of the functions.

These examples should give you a good idea of how to load different types of extension, but you shouldn't think of them as an exhaustive guide. In any case, do look at the documentation: this should provide Elisp code for you to cut and paste into your .emacs and get the extension working in no time.

Step 3: load extensions faster

If you browse through Emacs extension directories, you'll see that most files do not have a .el extension, but a .elc one. These are binary files obtained by compiling Elisp sources. This process is called byte compilation. Byte-compiled files load quickly (it is not by accident that the function load-library will look for a byte-compiled version of the file before it looks for the Elisp version) and take up little disk space. The disadvantage is that if you want to modify them you will need the source.

You need an Elisp compiler to compile one. But don't worry, you don't have to look too far: as you might have guessed, Emacs is among other things an Elisp compiler. To compile a file from within Emacs, run

M-x byte-compile-file RETURN file.el RETURN 

If you have upgraded some Elisp packages in one directory, you can speed up the process of recompilation by executing

M-x byte-recompile-directory RETURN /path/to/directory RETURN 

It's also possible to invoke Emacs in batch mode from the command line (type man emacs for more).

Modes revisited

We know we say it all the time, but we just can't resist telling you one more time: Emacs is extensible, and this gives it flexibility. With its plugin-based architecture you can use it to work with virtually any type of text (and non-text) files.

Usually the bunch of functions related to a type of file is called 'mode'. Emacs folk speak of the C mode, the HTML mode, the Perl mode etc. Modes are major or minor. A major mode gives the bulk of the infrastructure for editing files and working with them. The C mode provides rules for syntax highlighting and matching parentheses, but also a menu for calling the compiler, debugging the executable and more.

Minor modes provide refinements to the major mode. They can add a generic function, say, and hook it to an extra entry in a menu. Minor modes can usually be used with more than one major mode. For a buffer, we can specify several minor modes, but only one major mode.

Major modes can be automatically associated with extensions. Many major modes are provided with the default distribution of Emacs or packaged by Linux vendors in such a way that they work out of the box. If this is not the case for the mode that you want to use, just remember that a mode is pretty much like an extension: put its files in your repository and load it by adding an appropriate entry to your .emacs, as in this example:

(setq auto-mode-alist (cons '("\\.lxf$" . lxf-mode) auto-mode-alist))
(autoload 'lxf-mode "lxf-mode" "Mode for writing LXF tutorials." t)

This loads a hypothetical lxf-mode, which provides facilities for writing tutorials according to prescriptions. The first line instructs the editor to use the LXF mode for files with a .lxf extension; the second line associates the LXF mode with lxf-mode.el or lxf-mode.elc.

Emacs for programmers

Coding involves a series of operations: writing the actual code, compiling and debugging it, maintaining the program and sharing the source with other developers. Text editors like Kate and Vim are generally useful only for the first stage, when you have to type in your code, but there are applications that will assist all along the development process. Those applications are referred to as integrated development environments - IDEs for short.

Popular IDEs for open source are Anjuta, KDevelop, Eclipse and Emacs. Hang on... isn't Emacs a text editor? Well, guess what - our 'editor' provides a generic development environment that can be easily adapted to even the weirdest language. Thanks to Emacs's plugin architecture you can use it with just about any programming language on Earth. If a major mode for your favourite language does not exist (which, although possible, is very unlikely), it would not be difficult to write one, since Emacs supports a practically endless list of languages - Java, Python, Ada, Fortran... We're going to show you how we can use Emacs as an IDE with one of the all-time favourite languages, C (and, hopefully, convert you to our belief that Emacs is a kind of fifth element that pervades all our lives. Or at least computing).

Start your Emacs and type in the following code:

1 /* This is some sample code */
2 Int main() 
3 {
4 char mystring[15];
5  int ivect[3], i;
6  strcpy(mystring,"Hello Emacs \n"
7  printf(mystring);
8  for (i=0; i<3; i++)
9    ivect[i] = 2*i - 3;
10  for (i=0; i<3; i--)
11    printf("component %d of ivect is %d \n", i ivect[i]);
12  return 1;
13 }\

The line numbers are for reference only and should not be copied. Don't worry at this stage about the obvious mistakes.

The first thing you should notice is that different lexical objects within the code (keywords, type words, variables, strings, comments etc) are highlighted with different colours. This is called syntax highlighting. If you're getting a dull, homogeneous foreground, you probably don't have syntax highlighting active. To rectify this, go to the Option menu and tick the corresponding box. Colours associated with lexical types can be changed in the Custom buffer.

If syntax highlighting were Emacs's only programmer-oriented feature, it would be hard to make a case for Emacs as an IDE. But there are many other features to help the developer. Among these is parenthesis matching, which is essential for helping you find errors before they break your code.

Go back to the Option menu and ensure that the Parent Match Highlighting box is ticked. Now put the cursor on any opening parenthesis: the corresponding closing parenthesis (if any) will be highlighted, either in a light colour (if correct) or in a more striking one (if the match is incorrect). The choice of these two colours is entirely up to you; on our system, they are turquoise and magenta respectively. In our example code, there is an unmatched parenthesis in line 6. In this case it's easy to spot the mistake, but in more complicated cases such as multiple nested conditionals, a mistake could be hard to find.

Good programming practice prescribes sensible indentation of the code. Emacs does not let you down here either: hitting the Tab key at the beginning of each line will put the cursor in the right position. Still, what we believe is "the right position" might not be right for you, so you can customise the indentation if you like. Not only does auto-indentation improves code's readability, it also catches mistakes. If you hit Tab at the beginning of line 7, you'll notice that the printf function will not be aligned with line 6, as it should be. When this happens, the reason is a syntax error (line 6 is not correctly ended by a semicolon). With the help of auto-indentation, we can fix this; but we'll leave the error there for the time being.

Electric Emacs

Facilities for editing C code are provided by the C mode. Manual loading of this mode is generally not required, but if the visual appeal of your code is pretty low or you are finding it difficult to follow this, the odds are that the C mode is not loaded. To remedy this situation, you'll have to execute

M-x c-mode

A few functions provided by this mode are listed in the table above right, together with their usual keystrokes. Although accessing the functions through the corresponding shortcut is generally more convenient, there appear to be exceptions on how functions are bound to keystrokes. If a particular keystroke does not work for you, try

M-x <function-name>

where the function name is that given in the first column of the table on the right.

Some development-oriented features are what is known as 'electric': a number of operations can be rolled in to one key combination. As an example, the keystroke C-j combines the actions performed by the Return and Tab keys (ie it puts you one line down with the correct indentation). If you want to explore more electric Emacs features, look for functions that have the c-electric prefix. Emacs is not electrified by default; you can toggle electrification on and off with C-c C-a.

In the trenches

It's time to test our code. Execute

M-x compile

and change the default compile command to gcc -g emacs-hello.c, where emacs-hello.c is the name of our source file. After hitting Return, you'll see the window split vertically, with the lowest part of the frame containing the compilation output. In our case, we get:

 gcc -g emacs-hello.c
emacs-hello.c:3: error: syntax error before "main"
emacs-hello.c: In function `main':
emacs-hello.c:9: error: syntax error before "printf"
Compilation exited abnormally with code 1 at Mon Nov 14 16:45:39

This code needs fixing. Put the cursor on the first error in the compilation window, left-click and type C-c C-c. You will be taken to the line that the compiler does not like, to give you a chance to fix your code. Repeat this operation until you've corrected all the errors that the compiler found, then try to compile again. If you have done things correctly, you shouldn't have any problem this time, and your a.out executable will be generated. Go ahead and run it (by executing M-x shell Return ./a.out Return in the compilation window) - but you'll discover that it does not work quite as you expected. The astute reader will have already identified the problem at line 10 - we wrote i-- when it should have been i++.

But what if the issue is more subtle than that? You'll need to debug the code, so enter

M-x gdb ENTER

GDB (the GNU Project Debugger) is probably your debugger of choice, so just accept the default and hit Enter again. Emacs will now enter GUD (Grand Unified Debugger) mode. GUD provides both a command line and menus for accessing the debugger's most useful features. In GUD mode, the window is split horizontally, with one half dedicated to the debugger itself and the other for the source file. Note that an arrow in the source buffer tells you which line is being executed. All this provides a handy visual tool for fixing faulty code.

Version control

Developers engaged in large projects will be pleased to learn that Emacs is perfectly integrated with the CVS and SVN revision control systems, among others. The framework that enables revision control is called VC. VC can autodetect which revision control system you are using, determine the status of the file (updated or locally modified) and check it in or out as necessary.

Finally, you can stop grepping around for places where a given function is defined, and start using Etags. There is more to Etags than we have space to go into here, but in short, Etags is the Emacs way of dealing with tags, which in turn are a collection of information organised by function and typedef names. Before you can use Etags in Emacs, you should run the etag command on all your sources and headers. Running

etag --help

will give you the corresponding instructions. Then, when you are looking at a line containing a call to a function, M-. (Meta-stop) will show the name of the function in the minibuffer. If this is correct, press Return, and a new buffer will display the code of that function.

We hope we've shown how Emacs can be used as a powerful IDE. It's not perfect, since it lacks some marginal tools, such as those related to code refactoring. But you must have noticed that we followed our simple program through the entire development cycle without quitting Emacs for a second. Isn't that what an IDE is supposed to be?

Complex editing

So far we've strayed into the super-cool territory of extensions and IDEs, but even in the vanilla world of text editing, it should come as no surprise that our favourite editor offers a little chocolate vermicelli on top.

You're now ready to investigate how Emacs can be used to create and edit documents with a complicated structure (useful for coders or anyone who writes reports, articles, wiki entries...) and how it can work in combination with more advanced formatting tools such as HTML and Latex. We know that if you are considering Emacs as your text editor, the chances are that you need more than basic functionality, and we hope to show here how sophisticated it can be.

Outline mode

We're not saying it's Scribus, but Emacs can be efficiently used as a simple word processor, and it's great for helping you structure your work. Fairly long pieces like articles and reports need to have a logically organised structure: chapters, sections, subsections and beyond must be self-contained and consequential. Unfortunately, sometimes when you start compiling the various sections you lose the big picture. This problem is well known not just to freelance Linux Format writers but also to developers, who often have to deal with multi-nested chunks of code.

In software development the answer is a feature called code folding: the code of the innermost conditionals is hidden, so that the controlling statement can be more easily exposed. A similar feature for writers would help them see whether two sections link well or if some reorganisation of the text is needed. Emacs provides this in the form of the outline mode. As an example, suppose we were writing the text for a brochure about holidays in Italy. We'd start with an outline, something like this:

Beautiful Italy
* An enchanting country
Why would you want to go to Italy? Sun, good food and nice people: do you need other reasons?
* On the beach
** The Adriatic coast
** Sicily 
* The Alps: something for everyone in every season
** Enchanting Dolomites
* Charming cities
** Rome
Rome is the capital of Italy. It is called La Città Eterna ('The Eternal City'), and a look at the wonderful
Fori Imperiali would be enough for you to understand why. 
** Florence
** Venice

Titles of sections are the lines that start with an asterisk, while the subsections starts with two asterisks. You can add complexity and have sub-subsections, sub-sub-subsections and so on, but your reader is likely to get lost. Lines with no asterisk form the so-called body of the text (obviously you'd write much more in real life). This way of marking the layout of the structure is not conventional but it is what the Emacs outline mode would expect, so that's what we've used (planning to replace it with more common layout markings later).

Let's go ahead then and activate this mode by executing

M-x outline-mode Enter

If you have syntax highlighting turned on, you will notice that the text following the asterisks is coloured. Different logical levels (sections, subsections etc) are given different colours. This is a great visual help for analysing the structure of the piece you are writing. But it is not enough: the statements we have written to convince people to visit Rome are too strong a distraction from our main focus: the organisation of the various topics. We could remove them, but this would be unpractical.

Here is where we can use the outline mode. We type C-c C-t and all the body bits disappear, leaving us with the pure outline. The dots (...) indicate that some text is hidden. Now we can start to reorganise our text: if we decide that Florence must follow Venice, we just cut the Venice line and yank it before Florence. we now revert to the full text view (C-c C-a) and find that all the text hidden by the dots has moved around with them, as it should be.

Still, we decide that this display is not clear enough; we want more fine-grained control. Again, we hide the body with C-c C-t and then we go one step further by hiding the sublevels with C-c C-q. Now just the title of the main sections are left. By glancing at the displayed text, we decide that the reader's attention would be better caught if the first topic after the introduction were the cities. No problem, we cut (C-k) the last line, move the cursor to line 3 and execute C-y (yank). The whole cities section has moved up at the bearable cost of cutting and yanking one single line!

Another useful feature of the outline mode is the possibility of navigating between headings: C-c C-p moves to the previous heading, C-c C-n moves to the next one, both independently of whether it's a section, subsection etc, C-c C-b moves backward in the same level (ie if you start from a subsection you'll go to the next subsection), C-c C-f moves one heading forward in the same level and C-c C-u moves up one level.

Finally, you can promote headings up one level or demote them down one level without editing the number of asterisks (an operation that would be tedious if an header has multiple subsections) by executing C-^ and C-v respectively (note the characters used in the keystrokes, which resemble arrows to visually reproduce the upwards and downwards motion).

Although using keystrokes save you precious time, you don't need to learn them by heart. When the outline mode is active (look at the status bar to check that it is), the Headings, Show and Hide submenus provide access to its most used features.

A spot of colour

Once you are happy with both the outline and the content, it is time to start to think about the most aesthetically effective way to present your work. Yes, Emacs can format text. It won't turn your copy into a shiny holiday brochure, but it can help you clarify your work and make it easy for others to read. The outline mode has done its job, so we need to leave it behind and enter the enriched text mode. As you might imagine, to activate this mode you need to execute

M-x enriched-mode Enter

In enriched mode, you are able to change the typefaces used in your text, so you could use bold faces for headlines, stress interesting concepts with italics and so on. Let's start with the title. With the mouse, select 'Beautiful Italy', then go to Edit > Text Properties > Face > Bold (or execute M-g b).

Now we'll add some colour. We'll make the section title red, by selecting the text, clicking on Edit > Text Properties > Face > Foreground Color > Other, then writing Red in the minibuffer. Repeat this for all the section or level one headers. Now we move to the subsection or level two headers. Again, we change the titles to any colour we want. We've also decided that it would be more stylish to have those headings moved to the right margin. A sufficient number of tabs will do.

As for the body text, a white background colour would be too dull. Something like yellow would be less cold. Clicking Edit > Text Properties > Face -> Background Color > Other and then entering Yellow in the minibuffer will achieve that. Finally, we could italicise some text such as 'La Città Eterna' by selecting it and pressing M-g i or underline it with M-g u (note that you can't change the fonts and the background at the same time: this is a current limitation of Emacs).

Adventures in Latex

That's some of its word processing tools; now let's try Emacs out with numbers. When it comes to rendering complex mathematical formulae, nothing produces better results than Latex. Emacs and Latex make a very powerful combination: not only does the Latex syntax get highlighted in Emacs, but all the document rendering process can be managed from within our editor. The most complete Emacs Latex mode is Auctex. This should be set up by your distribution; if not, consult your distro's package list or get it from www.gnu.org/software/auctex.

Suppose you have a Latex source named emacs.tex. When you open it with Emacs, the menu bar acquires an extra menu called TeX, courtesy of the Emacs TeX mode. Among other things, from this menu you can Latex your file, check its syntax and display the camera-ready version of the document. To get the full package, you need to set the variable tex-dvi-view-command by appending the line

(setq tex-dvi-view-command "xdvi *")

to your .emacs (make sure that Xdvi is installed). Now you can Latex your document with C-c C-f, or validate its syntax with

M-x Enter tex-validate-buffer Enter

Then get a preview with C-c C-v and print it directly to your printer with C-c C-p. Note that you can change your Latex viewer to Kdvi if you like by replacing xdvi with kdvi in your .emacs file.

While editing, you are offered other facilities, such as macros for inserting Tex blocks with C-c C-o (C-c C-o figure will write in the buffer the skeleton commands for inserting a figure) and parenthesis and dollar-matching functions.

We have provided a few example of using Emacs as an advanced text formatting tool and as an interface to HTML and Latex, but the possibilities are endless. Other popular options include using Emacs as a PGML, SGML or XML editor, just to mention a few, but our 'editor' (by now you understand why the quotes are there) can be used in conjunction with (or instead of) virtually any other document production application. Should it lack some facilities out of the box, often a few lines in Elisp fix the problem.

Web spinning

We hope you try it out as a Latex editor, but as we promised, Emacs also has a role as an HTML editor. Useful keystrokes of the Emacs HTML mode include M-; (insert comment tags), C-c 1 (create an h1 heading), C-c 2 (create an h2 heading), C-c C-c l (list item) and C-c Tab (toggles between hiding and showing tags). The HTML and SGML menus in Emacs provide easy access to most HTML-related facilities and specify the corresponding keystrokes.

Compiling from source

Our goal here is not to have you replace your existing installation, which is probably set up well already, but to get you used to customising the editor - even by hacking its dotfiles if necessary. Once you get beyond these basics, you should be able to revert to your old environment and apply tweaks there.

Before you start

As it does not have any complicated dependencies, installing Emacs from source is usually a painless operation, though we would suggest you take real care in the preparation stage in order to avoid clashes with the package provided by your distro. First, by default (and we won't change this) the files we are going to install will affect the layout of the OS in the following way:

  • /usr/local/bin The location of the new Emacs executable.
  • /usr/local/share/emacs/site-lisp Contains initialisation files specific to our system but shared by all Emacs versions.
  • /usr/local/share/emacs/site-lisp Contains initialisation files specific to our system but shared by all Emacs versions.
  • /usr/local/info Hosts the info node documentation for Emacs.
  • /usr/local/man/man1 Contains the man page.

Other version-specific directories will also be created, but these are not relevant for the moment, assuming that the version of Emacs we are building is different from the one you might already have.

To avoid conflicts, make sure that these directories are not already present before we start or that, if they are already on your system, they don't contain anything that refers to Emacs. The standard locations for Emacs-related files are /usr/bin, /usr/share/emacs and so on. If you find this isn't right, we would strongly recommend that you remove the previous version of Emacs using your distribution's package manager. There are no potential side-effects in doing this, as you can always reinstall the default version at a later stage.

Next, back up the .emacs file, .emacs.d directory and everything in /etc/emacs. Don't worry if you don't have these directories: we are still at a stage in which distro-specific considerations apply.

If you're building from source for the first time, don't worry: there's only a little preparation needed to install Emacs. Basically, just make sure that GCC (the GNU compiler) and the make utility are installed on your system. You can do this by opening a shell and typing which gcc or which make. This should print the location of the executables to the screen. If they're missing, you will probably find them on your distro's CDs or website.

Another fundamental requirement for to continue is X. Of course X11 support can be disabled, in which case you get Emacs running within a console rather than its fully graphical counterpart. But unless you have a particular reason for building Emacs without X support, make sure that an X11 development package is installed. XFree86 and X.org are equally good, although the package needed depends on which version of X you are running. For instance, on our Mandriva-based system, X development headers are provided by libxorg-x11-devel.

A number of other graphical libraries are optional. They are used either to build a fancier interface with 3D effects (like libXaw3d) or to support the embedding of images. If you feel like making Emacs a bit prettier, you will need one or more of libxpm, libpng, libjpeg, libtiff and libungif.

Building Emacs

We are going to compile and install the latest stable release of Emacs, which at the time of writing is version 21.4. The main features of this version are shared by other releases in the 21.x series, and include support for pictures in various formats, the ability to play sounds, initial support for Unicode (with more planned for the next release) and the capacity to insert text with variable height and width. Even if you don't intend to work through the practical element of this tutorial, it is a good idea to install the latest release anyway, as it fixes some security issues present in previous versions.

We need to get the file emacs-21.4a.tar.gz from http://ftp.gnu.org/pub/gnu/emacs. Copy this file on to your hard disk, bearing in mind that 120MB of disk space is required to build and install Emacs, and unpack it with the command

tar xvf emacs-21.4a.tar.gz

This command must be used in the directory where the tarball was saved. Be aware that you may also need to become superuser with the su command if the directory is not writable by normal users. After decompression, you should see a new directory called emacs-21.4. Type

cd emacs-21.4

to enter that directory. Before starting the build process, we would strongly that you spend a good 15 minutes looking at the README and INSTALL files in the package directory, as these may highlight any potential problems that could affect your particular system.

Once you're satisfied that everything is as it should be, you can start the build. This is the easy part, since only three commands are needed (see Express Installation box, below). First, we let Emacs work out the characteristics of our system and the libraries available by executing ./configure. This script also supports command line options that allow us to change some defaults (refer to the INSTALL file for more details) but we are going for a standard install.

Express installation

  • Get the source file and unpack it.
  • Change to the Emacs directory:
    cd emacs-21.4
  • Execute
    ./configure && make
  • Become superuser (if you are not logged in as root) and install the software by executing
    su -c 'make install'

If everything works, the script will display a summary report before creating the makefiles that we'll use to build Emacs. Before we go any further, it is a good idea to have a look at this report, especially the line referring to the operating system and machine descriptions. Among other things, the configuration report also tells us which graphical formats are supported according to the libraries found on the system. We've gone for the comprehensive option, in which we get support for all the common image formats and also for the Xaw3d widgets on the interface, although strictly speaking this is not required.

In the unlikely event that you get an error at the configure stage, the script's output will offer a hint at the nature of the problem, so you may have to spend a little time searching for a solution. Google and the Linux Format forums (www.linuxformat.co.uk) are a good place to start. Quite possibly you will need to know which library contains the function that hasn't been found and install the corresponding header package (usually labelled lib<name>-devel, where <name> is the name of the library). We would stress, however, that we don't expect the script to fail if you have followed all of the steps above.

The configure script can be run several times. Usually the best strategy is to run it, take a look at the summary report, make any necessary adjustments (for instance adding a library that wasn't found or changing a default option with the corresponding command-line switch) and then run it again. This can be repeated as many times as needed, but to prevent settings from the previous configure step messing up the new one, you should always execute make distclean before each new ./configure run.

Having ironed out any problems, we can get on with the build by typing make. On fairly recent hardware, the compilation process should take no more than five minutes. A failure at this stage would signal either a bug in the configure script or a compatibility problem with the system compiler. Both events are highly unlikely, but should either of them happen, it would be wise to have a look at the PROBLEMS file in the etc subdirectory, which logs any issues. If the problem is not discussed there, you may need to contact the developers, but we would be very surprised if you encounter any real difficulties. Finally, assuming that everything went right, you can install your freshly compiled Emacs by typing make install as root.

Testing the environment

We can now start Emacs by executing /usr/local/bin/emacs. Typing the whole path every time is inconvenient, but fortunately you don't need to do this as long as /usr/local/bin is already in the PATH environment variable. This can be checked with

echo $PATH

In our case, this outputs


If /usr/local/bin does not appear in your path, you can add

export PATH=/usr/local/bin:$PATH

to the .bashrc file in your $HOME directory.

If you kept your previous Emacs installation, make sure that the executable file points to the new version. The command

which emacs

should give the output:


If not, you will need to initialise your PATH in such a way that /usr/local/bin has priority over /usr/bin - it should come before it in the output of the echo $PATH command above. There are several ways of achieving this, but we don't have space to cover the subject in detail here. An alternative to this would be to rename the old Emacs executable by doing

mv /usr/bin/emacs /usr/bin/emacs.old

On distributions such as Debian and Mandriva, the alternative system allows you to have different copies of Emacs installed without any ill effects.

Installing Emacs should not present any major problems. The procedure is clean and mostly prevents any clashes with previous versions. For these reasons, it's a really good idea to keep the software up to date without waiting for your distribution vendor to release new versions. Installing Emacs from source gives us a common and distro-independent working environment that should work fine in all the other examples in this tutorial.

First published in Linux Format

First published in Linux Format magazine

You should follow us on Identi.ca or Twitter

Your comments

Emacs has changed a lot.

Let me first begin by saying that emacs has both changed a litte and changed a lot.

Saying it has changed a little is like sxaying the kernel has changed a little since 2.4, Yeah you can take a system running 2.4 and put in 2.6 and not have many changes to deal with. True on the other hand if you look at the actual installation, a lot has changed, including: gnome, kde, multimedia ( mplayer, vlc ... ) browsers (firefox, chrome ) etc. The core of emacs is still the same but there is a lot on the outside that changes.

Probably the three changes I feel the most: org-mode ( a favorite of GTD fans -- which I am not ), emacs-themes ( which allow you to change customizations ) and auctex ( which allows you to view compiled TeX ).

why I never liked emacs

simple, I open a windows and I have to learn first how to get a blanc screen

seriously, I am taking the oportunity of this tutorial to learn a bit of emacs, but contrary to what you state (I know, emacs has changed) when I type emacs -nw (I like console) or emacs (gets me the gui), I end up with a text and I cannot get out of it

try to type vi, or mcedit et there you go, type away

Please bring on the flame wars, vi and emacs fans...

... Christmas can be boring sometimes and I need something to read!

Need to run xrdb after editing .Xdefaults

Nice intro to emacs. I haven't used it much since university in the mid 1990's. It's on my "one of these days I need to get back into it" lists, but it never happens.

I didn't know much about .Xdefaults until reading this article. I modified it, but nothing changed. I searched around and found that I needed to run

xrdb -merge $HOME/.Xdefaults

after modifying it for the changes to work.

C-x h RET C-w

Sorry but I think this is far too dated to be a good Emacs tutorial¹ and it will be /especially bad/ for beginners. Major additions, changes and modernisations have made most version 21 era documentation worse than useless, IMHO.

¹ And I'm somewhat doubtful it ever was. There are many problems with it, perhaps mainly because it is so dated, but for just one time-independent example: the “shortcut“ notation - which we Emacs users call “key sequences”, not “keystrokes” - is wrong, and while it does indeed comply “more closely with the one commonly used by Emacs”, that just makes an unhelpful inconsistency into a perversely unhelpful one.

... "which should look like

... "which should look like one of the three illustrations in this article."

leftover from the original article? ;)

good tutorial

good tutorial

Comment viewing options

Select your preferred way to display the comments and click "Save settings" to activate your changes.

Post new comment

We can't accept links (unless you obfuscate them). You also need to negotiate the following CAPTCHA...

Username:   Password:
Create Account | About TuxRadar