Using Emacs

Emacs is a very popular and extremely powerful text editor. Emacs is installed on Winstat, Linstat, and the lab PCs in Social Science 3218 and 4218.

Emacs has too many specialized commands and features to cover completely here. This article serves only as an introduction, helping you get started using Emacs. A GNU Emacs Reference Card is attached to the end of this article which lists many of the most frequently used Emacs commands along with a short description of what each command does. If you find you need to learn more, Emacs has a comprehensive online help facility where you can get more information.

There are actually two versions of Emacs available, and each can run in two different modes. Originally Emacs was text-only and XEmacs used Xwindows graphics. However, Emacs is now graphical as well. Both versions have the option to use a text-only mode, which is useful if you do not have the ability to display Xwindows graphics. The differences between the two are either cosmetic or subtle enough to be beyond the scope of this article. In this article we'll use Emacs to refer to both Emacs and XEmacs, unless the difference is important.

Emacs is not hard to learn. However, it does not follow the conventions for Windows programs. If you're more comfortable in a Windows environment, keep in mind you can use a Windows text editor, such as TextPad, and then save your files on the Linux file system where Linux programs can access them. This is a very popular way to run programs like Stata or SAS on Linux without spending the time to learn Linux or Linux tools like Emacs. Our Guide to Research Computing covers what you need to know to work this way.

Emacs Commands

All Emacs commands involve key combinations. But the Emacs documentation has its own way of describing them. For example, C-key, means hold down CTRL and press key (so C-x means Ctrl-x in the way you're probably used to these combinations being described). In addition, the documentation refers to the Meta key (M-key). Some keyboards have a Meta key, though none of SSCC's do. On a PC, it depends on the terminal program you're using and how it is configured. SecureCRT has an option to use Alt as the Meta key, but if you do so you can't use Alt to send commands to SecureCRT itself. The alternative is to use Escape (Esc), but in this case it works a bit differently. Rather than holding down Esc, you press it once and then press the key you want. So to execute a command described as M-x, press Esc (and let go), then press x.

The most commonly used commands involve the Control key. Slightly less common commands are assigned to Meta. Other commands are executed by typing C-x and then the command (for example, to quit the program you type C-x C-c). Any command can be executed by typing M-x and then the full name of the command, and some commands can only be executed in this way.

Emacs has a very helpful feature known as completion. For example, if you are typing the name of a file after issuing a command such as find-file (C-f), you need only type the first few letters of the name, enough to make a unique filename. Then press the Tab key and Emacs will complete the filename for you.

Starting and Stopping Emacs

To enter Emacs, simply type

> emacs file

where file is the name of the file you want to edit. If you use a filename that does not exist, Emacs creates a new file. If you type emacs with no file, you'll get a window with copyright information. This will go away as soon you press a key. Emacs then puts you in an empty buffer (a buffer is a temporary workspace that may be saved later as a file) called *scratch*. Note: *scratch* buffers are not saved when you exit Emacs. Type C-x C–w to write this temporary buffer to a permanent file.


Emacs

The Emacs window contains three major areas: the largest area which takes up most of the window is where you enter your text. A cursor marks your position in the file. The cursor is also called "point" or "dot".

The grey area at the bottom of the window is called the mode line and provides information about the editing session: the name of the buffer being edited, the mode you are in (Emacs has many different modes, each of which customizes Emacs for editing text of a particular sort), and where you are in the file. If you are at the beginning of the file, Emacs prints the word Top; if you're at the end, it prints Bot; if you are somewhere in the middle, it shows you a percentage; and if the entire file is visible on the screen, Emacs prints the word All. At the left edge of this line, you may see two asterisks (**). If the asterisks are there, this means that whatever you are editing has been modified since the last time you saved it.

At the bottom of the window, below the mode line is the minibuffer. This is the area where Emacs echoes the commands you enter and where you specify filenames for Emacs to find, values for search and replace, and so on.

Note the colors. The file shown is a Stata .do file. If it is configured correctly, Emacs will recognize this and color various words accordingly. See Programming in Color for details.

If you type xemacs instead of emacs, you'll get the following:

Xemacs

Pick according to taste.

If you do not have Linux graphics available you can still use Emacs. You just have to use the -nw option (think no window) to tell it to run in text mode. Xemacs has the advantaget hat it will do some syntax highlighting even in text mode (assuming you set up syntax highlighting). To run it, type

> xemacs -nw file

Text-only XEmacs

To exit Emacs at any time, type C-x C-c. If you have made any changes that have not been saved, Emacs will prompt you, asking you if you want to save your changes.

Getting Help

Emacs has an extensive help facility, though it is quite different from Windows-style help. If you are just starting out, the tutorial can be handy. There are also tools that can tell you more about a given command, or try to identify the command you need to perform a specific task.

To start the tutorial, in Emacs click on Help and you'll see the the Emacs Tutorial at the top of the menu. In XEmacs, under Help there is a Tutorials sub-menu, allowing you to choose the language for the tutorial. If you are running either version in text mode, type C-h t. The tutorial provides an excellent guided tour of most of the important Emacs features and concepts. However, do not use it for retrieving information on how to do something in particular. There are better ways of doing this.

If you want to learn more about a command, in Emacs click on Help, put the mouse over Describe (but do not click), click on Describe Key, and then type the command. In XEmacs, click on Help, Commands and Keys, Key, and then type the command. In text mode, type C-h k and then the command.

If you want to do something and don't know which command to use, in Emacs click Help, put the mouse over Describe, click on Apropos Commands, and type a key word related to what you want to do. In XEmacs, click on Help, Commands and Keys, Apropos, and then type the key word. In text mode, type C-h a and then the key word. Emacs will then give you a list of commands that include the key word you chose in their titles. This is generally much less useful than the kind of search you may be used to, which searches the descriptions of what a command does.

No matter how you get help the resulting windows can be confusing if you aren't familiar with the keystrokes that control them. The following commands provide the window operations you will need in order to use the help system and exit from it when you are done:

  • To switch windows when the screen contains more than one window, type C-x o.
  • To scroll the selected window forward, type C-v.
  • To scroll the selected window backward, type M-v.
  • To scroll the other window forward, type M-C-v.
  • To make all windows disappear except for the selected window, type C-x 1.
  • To remove help information from the selected window, type C-x k.

Editing Files

Emacs achieves some of its famed versatility by having various editing modes in which it behaves slightly differently. Mode in Emacs simply means being sensitive to the task at hand. When you are writing, you often want features like word wrap so you do not have to press Return at the end of every line. When you are programming, the code must be formatted correctly depending on the language. For writing, Emacs has a text mode; for programming, Emacs has modes for different languages. Whenever you edit a file, Emacs attempts to put you in the correct mode for what you are going to edit.

Fill Mode and Text Mode

Before you start typing, look at the mode line at the bottom of the Emacs window. If the word Fill appears, you are in fill mode. In fill mode, when you type past the end of a line, Emacs automatically starts a new line for you. If Emacs is not in fill mode, you have to press Enter at the end of every line. You can turn on fill mode for a session by typing M-x auto-fill-mode. This command is a toggle command so if you want to turn fill mode off, just type the command again.

Moving the Cursor

Most of the time you can use the arrow keys on your keyboard (or the mouse in graphical Emacs) to move the cursor. Occasionally these aren't set up properly in your terminal program, so there are alternatives. To move the cursor forward one space, type C-f (f for forward). C-b moves the cursor backwards one space (b for backwards). To move up, type C-p (p for previous) and to move down, type C-n (n for next).

In Emacs you can also move to the beginning or end of a line. C-a moves you to the beginning of the line (just like a is the beginning of the alphabet). C-e (e for end) moves you to the end of the line. Using Emacs commands not discussed here, you can also move the cursor by words, sentences, and paragraphs--see the help..

Use C-v to scroll through your document one page at a time. Emacs leaves a couple of lines from the previous screen at the top to give you continuity. Likewise, M-v shows you the previous screen.

You often want to move all the way to the beginning or end of a file. To go to the end, type M->. To go to the beginning, type M-<.

Sometimes you may want to go to the n-th line or to the n-th character in the file. M-x goto-line n moves the cursor to the beginning of line n of the file. Likewise, M-x goto-char n goes to character n of the file.

The command C-l redraws the entire Emacs display and puts the line that has the cursor in the center of the screen.

Deleting Text

Emacs provides many ways to delete text. The simplest way to delete text is to press the Backspace or Delete key; this deletes the character immediately to the left of the cursor (note that this is different from what you're probably used to Delete doing). Sometimes, particularly in text Emacs, Backspace is not set to Delete, but rather sends C-h, putting you in help mode. Another way to delete a single character is with the C-d command. C-d deletes the character under the cursor.

If you want to delete an entire line, or part of a line, use the command C-k (for kill-line). This deletes everything from the cursor to the end of the line. Typing C-k on a blank line deletes the line itself. As a result, it usually takes two C-ks to delete a line; one to delete the text, and one to delete the resulting the resulting blank line.

When you use C-k, the material you delete does not just disappear. Emacs hides it away in a special place called the "kill ring". You can get back what you have killed with C-k by typing C-y (y for yank). Conveniently, if you kill several lines in succession, Emacs collects them all in a single item and places the whole unit into the kill ring; a single C-y will bring back everything.

Marking Regions to Delete, Move, or Copy

You can mark areas of text called regions which you can then delete, move, or copy. To define a region, you use the primary pointer (your cursor) along with a secondary pointer called a mark. Unfortunately, the mark is invisible so you have to remember where it is. To mark a region, you set the mark at one end of the region by pressing C-<Space Bar>, then move the cursor (the point) to the other end of the region. Deleting text requires the following four steps:

  1. Move the cursor to the beginning of the area you want to delete.
  2. Press C-<Space Bar>. Emacs displays the message Mark Set.
  3. Move the cursor to the end of the region you want to delete.
  4. Press C-w to delete the region.

Remember, you can retrieve whatever you have deleted with C-y. C-y also gives you an easy way to move text from one part of the file to another. Follow these steps to move text:

  1. Delete the text you want to move following the four steps above.
  2. Move the cursor to the point where you want to insert the text.
  3. Press C-y and Emacs will insert the text at the location of the cursor.

To copy text, follow these steps:

  1. Move the cursor to the beginning of the area you want to copy.
  2. Press C-<Space Bar>. Emacs displays the message Mark Set.
  3. Move the cursor to the end of the region you want to copy.
  4. Press M-w to copy the region.
  5. Move the cursor to the place you want to insert the copied text.
  6. Press C-y and Emacs will insert the copied text at the location of the cursor.

 

GNU Emacs Reference Card

(for version 19)

Starting Emacs

To enter GNU Emacs 19, just type its name: emacs

To read in a file to edit, see Files, below.

Leaving Emacs

suspend Emacs (or iconify it under X)              C-z
exit Emacs permanently                             C-x C-c

Files

read a file into Emacs                             C-x C-f
save a file back to disk                           C-x C-s
save all files                                     C-x s
insert tables of another file into this buffer   C-x i
replace this file with the file you really want    C-x C-v
write buffer to a specified file                   C-x C-w

Getting Help

The Help system is simple. Type C-h and follow the directions. If you are a first-time user, type C-h t for a tutorial.

remove Help window                                 C-x 1
scroll Help window                                 ESC C-v

apropos: show commands matching a string           C-h a
show the function a key runs                       C-h c
describe a function                                C-h f
get mode-specific information                      C-h m

Error Recovery

abort partially typed or executing command         C-g
recover a file lost by a system crash              M-x recover-file
undo an unwanted change                            C-x u or C-`
restore a buffer to its original tables          M-x revert-buffer
redraw garbaged screen                             C-l

Incremental Search

search forward                                     C-s
search backward                                    C-r
regular expression search                          C-M-s
reverse regular expression search                  C-M-r

select previous search string                      M-p
select next later search string                    M-n
exit incremental search                            RET
undo effect of last character                      DEL
abort current search                               C-g

Use C-s or C-r again to repeat the search in either direction. If Emacs is still searching, C-g cancels only the part not done.

Motion

entity to move over                        backward      forward

character                                  C-b           C-f
word                                       M-b           M-f
line                                       C-p           C-n
go to line beginning (or end)              C-a           C-e
sentence                                   M-a           M-e
paragraph                                  M--           M-"
page                                       C-x [         C-x ]
sexp                                       C-M-b         C-M-f
function                                   C-M-a         C-M-e
go to buffer beginning (or end)            M-<           M->

scroll to next screen                              C-v
scroll to previous screen                          M-v
scroll left                                        C-x <
scroll right                                       C-x >
scroll current line to center of screen            C-u C-l

Killing and Deleting

entity to kill                             backward      forward
character (delete, not kill)               DEL           C-d
word                                       M-DEL         M-d
line (to end of)                           M-0 C-k       C-k
sentence                                   C-x DEL       M-k
sexp                                       M-- C-M-k     C-M-k

kill region                                        C-w
copy region to kill ring                           M-w
kill through next occurrence of char               M-z char

yank back last thing killed                        C-y
replace last yank with previous kill               M-y

Marking

set mark here                                      C-@ or C-SPC
exchange point and mark                            C-x C-x

set mark arg words away                            M-@
mark paragraph                                     M-h
mark page                                          C-x C-p
mark sexp                                          C-M-@
mark function                                      C-M-h
mark entire buffer                                 C-x h

Query Replace

interactively replace a text string                M-%
using regular expressions             		   M-x query-replace-regexp

Valid responses in query-replace mode are:

replace this one, go on to next                    SPC
replace this one, don't move                       ,
skip to next without replacing                     DEL
replace all remaining matches                      !
back up to the previous match                      ^
exit query-replace                                 ESC
enter recursive edit (C-M-c to exit)               C-r

Multiple Windows

delete all other windows                           C-x 1
delete this window                                 C-x 0
split window in two vertically                     C-x 2

split window in two horizontally                   C-x 3

scroll other window                                C-M-v
switch cursor to another window                    C-x o

shrink window shorter                         M-x shrink-window
grow window taller                                 C-x ^
shrink window narrower                             C-x -
grow window wider                                  C-x "

select buffer in other window                      C-x 4 b
display buffer in other window                     C-x 4 C-o
find file in other window                          C-x 4 f
find file read-only in other window                C-x 4 r
run Dired in other window                          C-x 4 d
find tag in other window                           C-x 4 .

Formatting

indent current line (mode-dependent)               TAB
indent region (mode-dependent)                     C-M-"
indent sexp (mode-dependent)                       C-M-q
indent region rigidly arg columns                  C-x TAB

insert newline after point                         C-o
move rest of line vertically down                  C-M-o
delete blank lines around point                    C-x C-o
join line with previous (with arg, next)           M-^
delete all white space around point                M-"
put exactly one space at point                     M-SPC

fill paragraph                                     M-q
set fill column                                    C-x f
set prefix each line starts with                   C-x .

Case Change

uppercase word                                     M-u
lowercase word                                     M-l
capitalize word                                    M-c

uppercase region                                   C-x C-u
lowercase region                                   C-x C-l
capitalize region                                  M-x capitalize-region

The Minibuffer

The following keys are defined in the minibuffer:

complete as much as possible                       TAB
complete up to one word                            SPC
complete and execute                               RET
show possible completions                          ?
fetch previous minibuffer input                    M-p
fetch next later minibuffer input                  M-n
regexp search backward through history             M-r
regexp search forward through history              M-s
abort command                                      C-g

Type C-x ESC ESC to edit and repeat the last command that used the minibuffer. The following keys are then defined:

previous minibuffer command                        M-p
next minibuffer command                            M-n

Buffers

select another buffer                              C-x b
list all buffers                                   C-x C-b
kill a buffer                                      C-x k

Transposing

transpose characters                               C-t
transpose words                                    M-t
transpose lines                                    C-x C-t
transpose sexps                                    C-M-t

Spelling Check

check spelling of current word                     M-$
check spelling of all words in region              M-x ispell-region
check spelling of entire buffer                    M-x ispell-buffer

Tags

find a tag (a definition)                          M-.
find next occurrence of tag                        C-u M-.
specify a new tags file                            M-x visit-tags-table

regexp search on all files in tags table           M-x tags-search
run query-replace on all the files                 M-x tags-query-replace
continue last tags search or query-replace         M-,

Shells

execute a shell command                            M-!
run a shell command on the region                  M-_
filter region through a shell command              C-u M-_
start a shell in window *shell*                    M-x shell

Rectangles

copy rectangle to register                         C-x r r
kill rectangle                                     C-x r k
yank rectangle                                     C-x r y
open rectangle, shifting text right                C-x r o
blank out rectangle                                M-x clear-rectangle
prefix each line with a string                     M-x string-rectangle

Abbrevs

add global abbrev                                  C-x a g
add mode-local abbrev                              C-x a l
add global expansion for this abbrev               C-x a i g
add mode-local expansion for this abbrev           C-x a i l
explicitly expand abbrev                           C-x a e

expand previous word dynamically                   M-/

Regular Expressions

any single character except a newline              .   (dot)

zero or more repeats                               *
one or more repeats                                +
zero or one repeat                                 ?
any character in the set                           [ : : :]
any character not in the set                       [^ : : :]
beginning of line                                  ^
end of line                                        $
quote a special character c                        "c
alternative ("or")                                 "_
grouping                                           "( : : :")
nth group                                          "n
beginning of buffer                                "`
end of buffer                                      "'
word break                                         "b
not beginning or end of word                       "B
beginning of word                                  "<
end of word                                        ">
any word-syntax character                          "w
any non-word-syntax character                      "W
character with syntax c                            "sc
character with syntax not c                        "Sc

Registers

save region in register                            C-x r s
insert register tables into buffer               C-x r i

save value of point in register                    C-x r SPC
jump to point saved in register                    C-x r j

Info

enter the Info documentation reader                C-h i

Moving within a node:

   scroll forward                                  SPC
   scroll reverse                                  DEL
   beginning of node                               .   (dot)

Moving between nodes:

   next node                                       n
   previous node                                   p
   move up                                         u
   select menu item by name                        m
   select nth menu item by number (1-5)            n
   follow cross reference (return with l)          f
   return to last node you saw                     l
   return to directory node                        d
   go to any node by name                          g

Other:

   run Info tutorial                               h
   list Info commands                              ?
   quit Info                                       q
   search nodes for regexp                         s

Keyboard Macros

start defining a keyboard macro                    C-x (

end keyboard macro definition                      C-x )
execute last-defined keyboard macro                C-x e
append to last keyboard macro                      C-u C-x (
name last keyboard macro                           M-x name-last-kbd-macro
insert Lisp definition in buffer                   M-x insert-kbd-macro

Commands Dealing with Emacs Lisp

eval sexp before point                             C-x C-e
eval current defun                                 C-M-x
eval region                                        M-x eval-region
eval entire buffer                                 M-x eval-current-buffer
read and eval minibuffer                           M-ESC
re-execute last minibuffer command                 C-x ESC ESC
read and eval Emacs Lisp file                      M-x load-file
load from standard system directory                M-x load-library

Simple Customization

Here are some examples of binding global keys in Emacs Lisp. Note that you cannot say ""M-#"; you must say ""e#".

(global-set-key ""C-cg" 'goto-line)
(global-set-key ""C-x"C-k" 'kill-region)
(global-set-key ""e#" 'query-replace-regexp)

An example of setting a variable in Emacs Lisp:

(setq backup-by-copying-when-linked t)

Writing Commands

(defun command-name  (args)
   "documentation"
   (interactive "template")
   body)

An example:

(defun this-line-to-top-of-window (line)
   "Reposition line point is on to top of window.
With ARG, put point on line ARG.
Negative counts from bottom."
   (interactive "P")
   (recenter (if (null line)
                    0
                 (prefix-numeric-value line))))

The argument to interactive is a string specifying how to get the arguments when the function is called interactively. Type C-h f interactive for more information.

           Copyright c 1993 Free Software Foundation, Inc.
              designed by Stephen Gildea, May 1993 v2.0
              for GNU Emacs version 19 on Unix systems
Permission is granted to make and distribute copies of this card provided the copyright notice and this permission notice are preserved on all copies.
For copies of the GNU Emacs manual, write to the Free Software Foundation, Inc., 675 Massachusetts Ave, Cambridge MA 02139.


Keywordsemacs text edit linux   Doc ID102179
OwnerRussell D.GroupSocial Science Computing Cooperative
Created2020-05-18 12:54:24Updated2024-01-30 14:17:42
SitesSocial Science Computing Cooperative
CleanURLhttps://kb.wisc.edu/sscc/using-emacs
Feedback  0   0