How to Use Emacs Editor

An EMACS Primer

What is EMACS ?

EMACS is a powerful text file editor that has been much emulated by others. Its core functions are provided by a virtual machine implementation of MAC lisp which provides a set of editor primitives. The primitives are then combined using lisp to build more powerful functions. The result is a power extendable and totally configurable editor which has been ported to all mainstream operating systems, Unix, msdos, NT, MAC, VMS, Windows 9x.

If you don't like the way something works in EMACS you can change it. If you want a certain key to perform an editing function you can 'bind' it to a custom macro.

The major extensions to EMACS come in the form of lisp packages which can be added as required. These provide features such as:

EMACS stands for 'Editor MACroS'

Other abusive interpretations are:

Now that 8MB is not considered a huge amount of memory all but the last of these has fallen out of use. On my linux box GNU Emacs 20.4 takes up about 5M when resident and around 20Mb of disk space.

History

Terminology

Getting Started on The Tutorial

Invoke emacs

$ emacs &

Once Emacs is running type 'CONTROL+H' followed by the letter T. This will run the interactive Emacs tutorial. A file called TUTORIAL is loaded which takes you through all the basic steps required to edit files in EMACS. The text directs you step by step in carrying out simple edits on a file.

The Help Commands

Typing Control+H enters the help system. From here hitting a key will provide access to further help subsystems. For example C-H a will invoke the apropos command. Type in a search string (eg html) and EMACS will list all functions that contain that string in the name of the function. This is very useful when exploring what functions exist and also when you are not sure of the exact name of a function that you wish to invoke.

The Info System

Typing CONTROL + H followed by the letter i enters the info system. This is text based hypertext document system. The documentation is detailed and extensive and covers all aspects of EMACS. It should be the first port of call for answering queries and for learning more. You can move the cursor onto a keyword or piece of highlighted text and jump to further information, much like an HTML document. You can display the keystrokes used to navigate round the info system by typing ? once inside info mode. The source files for the info documents can also be run through the GNU TeXinfo processor to produce a full user guide which can then be printed as a book.

EMACS Key bindings

The majority of common editing functions are already bound to keys. The more complex or less often used commands can be invoked by calling then up from the minibuffer or you can arrange a custom key binding for your favorite commands.

In general the most frequently used editing sequences are bound to CONTROL + a letter (written C-letter) or META + a letter (written M-letter). The ESCAPE key can be used instead of META on keyboards that do not have a META key. Commands associated with files tend to be bound to CONTROL + X followed by a letter or another control key sequence. The CONTROL+X (written C-X) sequence is known as a prefix and a separate key map is defined for commands invoked using the same prefix. The common prefixes are:

Emacs Keystroke Cribsheet

The following is a listing of a basic set of key bindings for the majority of common editing tasks. A useful EMACS reference card is also available in TeX format and one can be found in the back of the O'Reilly book.
Key
---
C-X   control X
C-X F control X followed by F
M-F   meta F or Esc followed by F
M-C-S hold down control + meta + S
where Meta appears you can use ESC

File Handling                           Searching
-------------                           ---------
C-X C-F  load a file                    C-S   isearch-forward
C-X C-S  save file                      C-R   isearch-backwards
C-X C-C  exit emacs                     M-C-S isearch-forward-regexp
C-X C-R  view a file                    M-C-R isearch-backward-regexp   
C-X C-W  write file (specify filename)
C-X C-Q  toggle view mode
C-X I    insert-file
C-X S    prompt save all buffers
C-X K    kill-buffer (unload a file)
C-X 4 f  find-file-other-window
C-X 4 r  find-file-read-only-other-window

Moving Around                           Replacing
-------------                           ---------
C-n   next-line (down-arrow)            ESC-% query-replace
C-p   previous-line (up-arrow)          query-replace-regexp
C-f   forward-char (right-arrow)
C-b   backward-char (left-arrow)        Responses During Query Replace
                                        ------------------------------
ESC-f forward-word                      y  replace this instance
ESC-b backward-word                     n  dont replace this one
                                        !  replace all remaining instances
C-a   beginning-of-line                 .  replace this one and exit
C-e   end-of-line                       ^  back up to previous replacement
                                        C-R recursive edit
ESC-a forward-sentence                  C-M-c exit recursive edit
ESC-e backwards-sentence                ?  help
                                        q  exit
ESC-} forward-paragraph
ESC-{ backwards-paragraph               Cut Copy Paste                          
                                        --------------
ESC-< beginning-of-file                 C-SPC   set-mark-command 
ESC-> end-of-file                       C-w     kill-region
                                        C-y     yank
C-v   scroll-up                         ESC-w   kill-ring-save (copy-region-as-kill)
ESC-v scroll-down                       C-X h   mark whole file

Window Management                       Changing Case
-----------------                       -------------
C-X 1   delete-other-windows            ESC-C   capitalise-word
C-X 2   split-window-vertically         ESC-U   upcase-word
C-X 3   split-window-horizontally       ESC-L   downcase-word
C-X o   select other window             C-X C-U upcase-region
C-X 0   delete this window              C-X C-L downcase-region
C-X C-B buffer-menu (? for help)

Deleting                                Spell Checking
--------                                --------------
ESC-d      kill-word                    M-x ispell-buffer
ESC-DEL    backward-kill-word           M-$ ispell-word
C-d        delete-char                  i   accept and insert into dictionary
DEL        backward-delete-char         a   accept for this session
C-k        kill-line                    SPC accept this once
ESC-Z char zap-to-char                  r   replace with typed in word
                                        C-R recursive edit
                                        C-M-c exit recursive edit
                                        x   exit

Miscellaneous                           Transpose
-------------                           ---------
C-X u   undo                            C-X C-T transpose-lines
C-X m   start mail                      M-T     transpose-words
C-C C-W load signature file
C-C C-C send mail
C-Z     iconfify emacs window
ESC=    count-lines-region
C-X `   next-error
        (parse compile errors)

Moving Around Source Code               Shell Commands
-------------------------               --------------
C-M-F forward-brace                     ESC-!   shell command to buffer (esc bang)
C-M-B backward-brace                    ESC-|   shell command on region (esc pipe)
C-M-A forward-func                      ESC-x shell RET
C-M-E backward-func                     (run a shell in a buffer)

Command Line Completion and Recall in the Minibuffer

As in most modern shells EMACS has command line completion when inside the minibuffer. Pressing the TAB key causes EMACS to attempt to complete the command being typed. If the command is not unique EMACS displays a buffer with a list of possible completions. You then continue typing until you feel enough text has been entered to allow further completion when the TAB is pressed again.

Emacs stores a history of commands that have been entered through the minibuffer and commands can be recalled by pressing the up-arrow key.

Incremental Search

EMACS provides several different ways to search for text strings. Incremental searching means that the cursor jumps to and highlights the nearest match as the search string is typed in.

Also available are the functions isearch-forward-regexp and isearch-backward-regexp which are incremental searches using regular expression matching. These are bound to M-C-s and M-C-r respectively.

Dired Mode

Directory Editing Mode provides access to a fast and easy to use file management system all within an emacs buffer. Type C-X C-D and you are prompted in the minbuffer for a directory path.

Dired (directory): ~/src
The default path is the last pathname that was entered in the minibuffer. You can use the up-arrow key to recall a previous path and command line completion to complete a partially entered path. Once the return key has been pressed Dired lists the contents of the directory in a manner similar to the ls command.
  /root/src:
  total 56
  drwxr-xr-x  14 root     root         4096 Apr 30 06:22 .
  drwxr-x---  32 root     root         4096 May  8 22:33 ..
  drwxr-xr-x   4 root     root         4096 May  8 22:36 emacs-talk
  drwxr-xr-x   2 root     root         4096 May  4 02:45 homepage
  drwxr-xr-x   2 root     root         4096 Apr 18 03:07 keep
  drwxr-xr-x   2 root     root         4096 Jan 16 03:17 misc
  drwxr-xr-x   2 root     root         4096 May  1 23:55 notes
  drwxr-xr-x   2 root     root         4096 Apr 18 03:07 ppp-setup
  drwxr-xr-x   2 root     root         4096 Mar 17 00:14 screenshots
  drwxr-xr-x   2 root     root         4096 Feb 14 20:55 tmp
  drwxr-xr-x   2 root     root         4096 May  5 02:45 web

Here is a sample of the key bindings active when moving the cursor over file entries in a Dired buffer.

Ange FTP

Ange FTP extends dired mode to remote file systems across a network. At the dired prompt type the remote filename or path using the syntax used by the rcp command (remote copy program). For example:
Dired (directory): /hughb@bobcat:/Tools
You are then prompted for the user password of the remote machine.
password for hughb@bobcat:
Emacs then opens up an ftp session with the remote machine, requests a directory listing and displays it in a Dired buffer. From then on you can use all the normal Dired commands as previously described. You can can select a file using the cursor, open it for editing using f, edit it and save it back to the remote machine using C-X C-S as if it were a local file. The file gets sent back to the remote machine by the background ftp process. Even hard core vi users go green with envy when they see this in action.

SCCS/RCS Interface

EMACS provides a useful interface to the version control suites SCCS and RCS. Here is a typcial example:

Man Page Viewing

Man pages can be viewed inside an EMACS buffer by invoking the manual-entry command. The man page is generated from the nroff source and displayed using the appropriate EMACS fonts for bold , italic and underline text etc. You can then use all the normal EMACS navigation commands to browse the man page. The default argument to the manual-entry command is the current word underneath the cursor. This is useful when browsing program code and you want to lookup the arguments to a certain system call you come across.

Sending EMAIL

Sending email works as follows:

ediff

ediff is a powerful package that enables software developers to compare two text files, step through the differences and selectively apply a difference from one file to update another. This is very useful if you are a developer that spends a lot of time porting or merging changes between development and maintenance trees.

ediff is invoked by entering the minibuffer (M-x) and typing ediff followed by RETURN. You are then prompted for the pathnames for the two files you wish to compare. The screen splits into two windows one above the other and the files are loaded into two buffers A and B. A special control window called the ediff control panel is also created which pops up as a new X Window. Typing various keys whilst the focus is in the control panel enables you perform various ediff functions.

GNUS

A very popular package is the GNU Newsreader or Gnus which is pronounced GNews. This is a complete, extendable and highly configurable usenet news reader. It can be invoked from the minibuffer by typing gnus. Those that use gnus love it.

Reading EMAIL

GNU EMACS provides RMAIL and XEmacs the vm mail reader. RMAIL is fairly basic in comparison to vm which handles MIME attachments well. Those that use vm seem to find it very productive. Both mailer's tend to modify the mail headers in a way that yeilds the resulting mailbox unreadable by other mailers such as elm, pine, mutt or dtmail. This is something to bear in mind if your mailboxes need to be shared with others.

Parsing Compiler Errors

HTML Helper mode

The following lines can be used to automatically setup html-helper-mode whenever an HTML file is loaded.
(autoload 'html-helper-mode "html-helper-mode" "Yay HTML" t)
(setq auto-mode-alist (cons '("\\.html$" . html-helper-mode) auto-mode-alist))
(setq html-helper-do-write-file-hooks t)
The last line enables a timestamp to be updated each time the HTML document is saved to disk. The timestamp text is delimited by two marker HTML comments as shown.
<!-- hhmts start -->
Last modified: Tue May  9 02:25:54 2000
<!-- hhmts end -->
html-helper-mode can be obtained from: http://www.santafe.edu/~nelson/hhm-beta/

Configuring Emacs

EMACS is configured through lisp commands specified in the user's ~/.emacs file.

Some EMACS command line args

Extracts from My .emacs file

(setq-default scroll-step 1)               ; turn off jumpy scroll
(setq-default visible-bell t)              ; no beeps, flash on errors

(display-time)                             ; display the time on modeline
(column-number-mode t)                     ; display the column number on modeline
(setq-default kill-whole-line t)           ; ctrl-k kills whole line if at col 0
(setq-default fill-column 75)              ; wrap at col 75
(setq-default tab-width 4)                 ; show tabs as 4 cols

(setq font-lock-maximum-decoration t)      ; use colours in font lock mode
(setq font-lock-maximum-size nil)          ; trun off limit on font lock mode
(add-hook 'c-mode-hook 'customize-cc-mode) ; cc-mode setup

;; some useful key bindings

(global-set-key [home] 'beginning-of-line)
(global-set-key [end] 'end-of-line)
(global-set-key [(control home)] 'beginning-of-buffer)
(global-set-key [(control end)] 'end-of-buffer)
(define-key esc-map [right] 'kill-word)         ;; esc -> kill-word
(define-key esc-map [left] 'backward-kill-word) ;; esc <- backward-kill-word

;; Setup Alt Keys

(global-set-key [(alt b)] `buffer-menu)
(global-set-key [(alt c)] `copy-region-as-kill)        ; ESC-w
(global-set-key [(alt g)] `goto-line)

;; setup cc-mode
(defun customize-cc-mode()	      
  (c-set-offset 'substatement-open 0)
  (setq c-basic-offset 4)
  (setq c-indent-level 4)
  (setq comment-column 40)
  (setq indent-tabs-mode t)
  (setq c-tab-always-indent nil)
  (define-key c-mode-map "\C-m" 'newline-and-indent)
)

My .Xdefaults

A number of EMACS options can also be specified in the X resources file .Xdefaults. This can be useful for quickly setting up syntax highlighting colour schemes. Note that syntax highlighting can also be setup in the ~/.emacs file.
Emacs.geometry: 85x45+70+0
Emacs.font: 9x15
Emacs.background: midnightblue
Emacs.foreground: grey90
Emacs.cursorColor: cyan
Emacs.pointerColor: cyan
Emacs.bitmapIcon: on
Emacs.verticalScrollBars: off

Emacs.modeline.attributeForeground: black
Emacs.modeline.attributeBackground: grey
Emacs.region.attributeForeground: black
Emacs.region.attributeBackground: grey
Emacs.highlight.attributeForeground: black
Emacs.highlight.attributeBackground: grey
Emacs.secondary-selection.attributeForeground: black
Emacs.secondary-selection.attributeBackground: green

Emacs.font-lock-function-name-face.attributeForeground: cyan 
Emacs.font-lock-comment-face.attributeForeground: SpringGreen
Emacs.font-lock-doc-string-face.attributeForeground: SpringGreen
Emacs.font-lock-preprocessor-face.attributeForeground: cyan
Emacs.font-lock-keyword-face.attributeForeground: Yellow
Emacs.font-lock-variable-name-face.attributeForeground: Gold
Emacs.font-lock-string-face.attributeForeground: Wheat
Emacs.font-lock-type-face.attributeForeground: deepskyblue

Emacs.info-node.attributeForeground: cyan
Emacs.info-node.attributeFont: default
Emacs.info-xref.attributeForeground: cyan
Emacs.info-xref.attributeFont: default

Emacs.bold-italic.attributeForeground:cyan
Emacs.italic.attributeForeground:lightgoldenrodyellow
Emacs.underline.attributeForeground:gold
Emacs.underline.attributeUnderline:no
Emacs.bold.attributeForeground:cyan

Emacs*menubar.foreground: black
Emacs*menubar.background: grey
Emacs*menubar.font: 9x15
Emacs*menu.popup.foreground: black
Emacs*menu.popup.background: grey
Emacs*menu.popup.font: 9x15
Emacs.popup.foreground: black

Web References

http://www.emacs.org/

Books

Learning GNU Emacs
Debra Cameron, Bill Rosenblatt & Eric Raymond
O'Reilly & Associates, Inc.
ISBN 1-56592-152-6

Writing GNU Emacs Extensions
Bob Glickstein
O'Reilly & Associates, Inc.
ISBN 1-56592-261-1