Getting started with Emacs on Windows

These notes summarize some of my discoveries (re-)learning GNU Emacs. Since these are my personal notes, it may help to briefly describe my background. I used Emacs on Unix from somewhere around 1990 until 1995. Then in 1995 I began using Windows as my primary operating system and stopped using Emacs. In 2010 I decided to give Emacs on Windows another try. I may not mention some basic things just because I remember them from my initial experience.

These notes are not a thorough introduction to Emacs. For a more systematic reference, the Emacs Wiki is a good place to start. I wanted to write these things down for future reference, and I put this file up on my web site in case someone else finds it useful. If you have comments or corrections, please let me know.

 

Table of contents

Installation and configuration

Installing Emacs and setting up .emacs

I install all my Unix-like software under C:\bin and have that directory in my Windows PATH environment variable. I installed Emacs 23.1 in C:\bin\emacs-23.1 and created an environment variable HOME set to C:\bin. The significance of HOME is that Emacs can find your configuration file if you put it there. This file is called “dot emacs” because the traditional name for the file on Unix systems is .emacs. On Windows, it is more convenient to name the file _emacs. (You can also name the file _emacs.el. Giving the file the .el extension causes Emacs to open the file in Lisp mode. And if someday the file becomes huge, you can compile it to make startup faster.)

Backup files

Emacs automatically saves backup versions of file and by default leaves thesebackup files beside the files being edited. This can be annoying. Some people call these extra files “Emacs droppings.” Adding the following lines to .emacs instructs Emacs to put all backup files in a temporary folder.

(setq backup-directory-alist
`((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
`((".*" ,temporary-file-directory t)))

Recycle Bin

The following line configures Emacs so that files deleted via Emacs are moved to the Recycle.

(setq delete-by-moving-to-trash t)
More details here.

Integration with the Windows File Explorer

The following registry script creates an “Open with Emacs” option in the Windows file explorer context menu.

Windows Registry Editor Version 5.00

[HKEY_CLASSES_ROOT\*\Shell\Open In Emacs\Command]
@="\"C:\\bin\\Emacs-23.1\\bin\\emacsclientw.exe\" -a \"C:\\bin\\Emacs-23.1\\bin\\runemacs.exe\" \"%1\""
See also this blog post for how to open a file in a running instance of Emacs rather than starting a new instance for each file.

Putting these two lines in .emacs creates a menu item File -> Open recent.

(require 'recentf)
(recentf-mode 1)

If you have a desktop shortcut to runemacs, you can open a file in Emacs by dropping it on the shortcut icon.

Getting rid of the start-up screen and toolbar

I turned off initial start-up screen by adding (setq inhibit-startup-screen t) to .emacs. This had the pleasant side effect of making the “Open with Emacs” context menu work as expected. (Before, Emacs would open with a split window. Now it opens with just the “sent” file.)

Got rid of the toolbar by using the configuration editor under Options / Customize Emacs.

Changing fonts

I used the Options menu to change the default font to Consolas.

Enabling commands to change case

The commands for converting the text in a region to upper or lower case are disabled by default. (The GNU Emacs manual says beginners find these commands confusing and so you have turn them on. That seems very strange. Many other Emacs commands are more confusing.) The following turns the commands on.

(put 'upcase-region 'disabled nil)
(put 'downcase-region 'disabled nil)

Once this is enabled, you can make the text in a region lowercase with C-x C-l or uppercase with C-x C-u.

Spell check

GNU Emacs does not provide a spell checker. Instead, it provides hooks to install your own spell checker, usually Aspell. I downloaded Aspell version 0.50.3 (win32) from here. I then installed the English dictionary from the same page. The dictionary installer warned me that Aspell was already installed and suggested that I uninstall it. I did, thinking that it might install a newer version. That didn' work. I re-installed Aspell, then installed the dictionary, ignoring the warning. Everything worked fine.

After installing Aspell, I let Emacs know where to find it by adding these lines to my .emacs file.

(setq-default ispell-program-name "C:/bin/Aspell/bin/aspell.exe")
(setq text-mode-hook '(lambda() (flyspell-mode t) ))

The command M-x ispell will run the spell checker on your file. If flyspell-mode is turned on, as it is in the lines above, misspelled words are underlined in red as you type.

Installing color-theme

It was difficult to find a more direct way to configure the color schemes that Emacs uses, so I installed color-theme version 6.60. I then used color theme creator to create a basic theme then tweaked the colors.

Installing nXhtml

The default support for editing HTML files was less than I expected. I heard good things about nXhtml and decided to go with it. Notice that it inserts extra menus when you open a file in nXhtml mode. You can use the commands from the menu until you learn their keyboard shortcuts.

nXhtml mode requires HTML to be valid XHTML. If your HTML is not valid, you can use HTML Tidy to bring it into standard compliance. HTML Tidy appears as a menu option under nXhtml, but it must be installed separately. Installing HTML Tidy is very simple: download two files, the executable and a DLL, and copy them to somewhere in your path. Once HTML Tidy is installed, it will continually check the validity of the XHTML. It will display its status in the mode line and will turn angle brackets red that are not in the correct place.

Incidentally, the table of contents for this page was automatically generated using nXhtml. Just give every <h> tag an id. Then you can use commands from the nXhtml menu to insert the table of contents and its style sheet.

NB: Apparently the nXhtml code does not allow a space on either side of the equal sign when specifying the id value.

Installing powershell-mode

I installed a mode for editing PowerShell code by copying powershell-mode.el, downloaded from here, by copying the file to C:\bin\emacs-23.1\site-lisp, which is in my Emacs load-path. I tried installing some code that would allow me to run PowerShell as a shell inside Emacs. That did not work on the first try and I did not pursue it further.

Remapping my keyboard

Many emacs users recommend remapping your keyboard so that the caps lock key becomes a control key. I don't like the idea of changing my keyboard just to accomodate one program, even a program I may use very often. However, I recently bought a laptop that came with a Fn key right where my muscle memory expects the left control key. I hardly ever use the caps lock key, so I made it a control key for the sake of emacs and for making it easier to use my laptop. I mapped the scroll lock key, a key I have not used in a decade or two, to caps lock in case I ever need a caps lock key. My initial intention was to keep the original left control key as an addition control key, but then I disabled it to force myself to get into the habit of using my new control key. I mapped the keyboard of every computer I use to be the same. This has been hard to get used to.

I used the KeyTweak application to remap my keyboards.

I don't know what I want to do for my “Meta” key. For now I'm using the Esc key. Some recommend using the original Control key after remapping the Caps Lock key. I have two problems with that: it will not work on my laptop, and I first have to break my habit of using the original Control key as a Control key. (Why not just remap the Fn key on my laptop? Unfortunately this key cannot be remapped like an ordinary key.) I may try to get in the habit of using the right Alt key as my Meta key.

Line wrapping

I set global-visual-line-mode as the default way to handle line wrap. I did this through the menu sequence Options / Customize Emacs / Specific Option. This causes text to flow as it does in most Windows programs.

Column position

By default, Emacs displays the current line number in the mode line but not the current column number. To display the column number, add the following to your .emacs file.

(setq column-number-mode t)

 

Emacs vocabulary

Emacs uses a set of terminology that is not commonly used elsewhere. The following correspondences are not exact, but they are a good first approximation.

Emacs terminology Common terminology
fill word wrap
yank paste
kill cut
kill ring clipboard
mode line status bar
point cursor
font lock syntax coloring

The “echo area” is the very bottom of an Emacs window. It echoes commands, displays the minibuffer, and provides a place to type extra arguments for commands.

 

Editing LaTeX

One of the most useful key sequences for editing LaTeX files are C-c C-o to insert a \begin and \end pair. Emacs will prompt you for the keyword to put inside the \begin{} statement. Another useful key sequence is C-c C-f to run latex on a file. (Emacs can detect whether a file is plain TeX or LaTeX. I use LaTeX exclusively.)

There is Emacs package AUCTex for eding (La)TeX files, but I have not tried it.

I would like to have C-c C-f run pdflatex rather than latex, but I have not found out how to configure that.

 

Editing source code

Here are a few useful commands for editing source code files.

Command Explanation
C-M-a Go to beginning of a function definition
C-M-e Go to end of a function definition
C-M-h Put a region around a function defintion
C-j Insert a newline and properly indent the next line

I put these lines in my .emacs file to make the C++ mode behave more like what I am accustomed to.

(add-hook 'c++-mode-hook
  '(lambda ()
     (c-set-style "stroustrup")
     (setq indent-tabs-mode nil)))

Selecting and delting text

C-x h selects the entire current buffer.

You select a region by using C-SPACE at one end of the region and a selection command and moving the point (cursor) to the other end of the region. Then you can use C-w to cut or M-y to copy. The paste command is C-y. Emacs maintains a “kill ring”, something analogous to the Windows clipboard but containing more than just the latest cut or copy. For example, C-y M-y. lets you paste the next-to-last thing that was cut. Use M-y again to paste the cut before that, etc.

You can kill all but one whitespace character with M-SPACE. You can kill all but one blank line with C-x C-o.

Emacs has commands for working with rectangular regions, analogous to vertical selection in some Windows programs. Specify a rectangular region by setting the mark at one corner and the point at the opposite corner. All commands for working with rectangular regions start with C-x r. Here are a few rectangular region commands.

Command Explanation
C-x r k Kill the rectangle
C-x r d Delete the rectangle
C-x r c Clear the rectangle, i.e. fill the region with whitespace
C-x r y Yank (paste) the rectangular region

 

Searching and replacing

Use C-s for forward incremental search, C-r for backward incremental search. Type another C-s or C-r to repeat the search. Type RET to exit search mode.

Regular expressions

C-M-s and C-M-r are the regular expression counterparts of C-s and C-r.

Eamcs regular expressions must escape the vertical bar | and parentheses. For example, the Perl regular expression (a|b) becomes \(a\|b\) in Emacs.

Emacs regular expressions do not support lookaround.

The whitespace patterns \s and \S in Perl are written as \s- and \S- in Emacs. There is no equivalent of Perl's \d except to use the range [0-9].

Replacing

Use M-x replace-string and M-x replace-regex for replacing text. There are also interactive counterparts M-x query-replace and M-x query-replace-regex.

 

Saving text and positions

Saving text

You can save a region of text to a named register for later pasting. Register names can be any single character. The command to save to a register a is C-x r s a. The command to insert the contents of register a is C-x r i a .

Saving positions

Bookmarks are named positions in a buffer. The command to create a bookmark is C-x r m bookmark_name. The command to go to a bookmark is C-x r b bookmark_name.

 

The Emacs help system

All help commands start with C-h. If you don't know a more specific location to go to, you can start by typing C-h C-h to get to the top of a navigation system for help.

C-h m is very useful. It displays all active modes and describes key bindings.

C-h k tells what command is bound to a key and gives documentation on how it is used. C-h w is a sort of opposite: given a command, it sells what keys are bound to that command.

 

Files

The command to open a file is C-x C-f. The command for ‘save as” is C-x C-w.

Emacs has a sort of File Explorer named Dired. You can open Dired with the command C-x d. You can move up and down in the Dired buffer by using p and n just as you can use C-p and C-n in any other buffer. You can still use the control key, but you do not have to.

Here are a few of the most important Dired commands.

Dired command Action
RET Visit selected file (or directory)
C Copy
D Delete immediately
d Mark for deletion. Use x to carry out deletions.
R Rename a file
! Specify a shell command to carry out on a file

Adding the following two lines to your .emacs file will create an Open Recent submenu under the File menu.

(require 'recentf)
(recentf-mode 1)

Buffers

The command C-x b takes you to your previous buffer.

The command C-x C-b creates a new window with a list of open buffers. You can navigate this list much as you would the Dired buffer.

You can type the letter o to open the file on the current line in another window. You can type the number 1 to open the file as the only window.

The command M-x kill-some-buffers lets you go through your open buffers and select which ones to kill.

Windows

The command C-x 1 closes all windows except the current one.

C-x 2 splits the current window horizontally, one buffer on top of the other.

C-x 3 splits the current window vertically, one beside the other.

C-x o cyles through windows.

 

Miscellaneous commands

 

Command Explanation
M-g g Go to line number
M-= Report line and character count of region
M-/ Autocomplete based on text in current buffer
C-x C-e Evaluate the Lisp expression to the left of the cursor
M-x eval-region Evaluate the selected region as Lisp code
M-x shell Run a shell inside Emacs
M-! Run a single shell command
M-x sort-lines Sort the lines in a region
M-x desktop-save Save an emacs session
C-t Transpose characters
M-t Transpose words, works across punctuation and tags

 

Emacs resources

One program to rule them all
Emacs cursor movement
Emacs and Unicode
Emacs kill (cut) commands
Emacs for Writers
Real Programmers (xkcd cartoon)
10 Specific Ways to Improve Your Productivity With Emacs from Steve Yegge