Home » Linux Basics » 09 - Editing Shell Scripts with vi and emacs
9

An Introduction to Emacs

Learning the basics of emacs

The emacs editor is a popular editor but is not a standard Linux system utility. Emacs may be downloaded for free from the Internet. Emacs allows users to view two or more files at the same time, compile and debug programs in almost any programming language, typeset documents, run shell commands, read manual pages, e-mail and news and even browse the web. Emacs is also very flexible. Keystrokes and commands may be redefined, and new commands and display modes may be added using Lisp programs as emacs has its own Lisp interpreter. Emacs uses a relatively large amount of system resources compared to vi; its commands tend to have complex structures (a standard joke is that emacs stands for escape-meta-alt-control-shift). In practice, most Linux users tend to use both editors - vi for rough and ready edition of short scripts and emacs for more complex tasks like editing application code.

The following command starts emacs and loads <file_name> for editing:

    [ LinuxUser ] ~$ emacs <file_name>

Text input and navigation in emacs involves using the arrow keys to position the cursor and typing text. Issuing commands usually involves pressing the Ctrl key or the Alt key (sometimes labeled Meta), holding the key down and typing a single character. Other characters may follow after releasing these keys. Holding down the Ctrl or Alt key and typing a character is represented in the following way: Ctrl-<character>. Typing characters after releasing Ctrl or Alt is represented as follows: Ctrl-<character> <character>. Thus, 'Ctrl-x 2' means hold down ctrl and press x, release both and press 2.

Useful commands are Ctrl-a (beginning of line), Ctrl-e (end of line), Ctrl-v (page down), Alt-v (page up), Alt-< (beginning of document) and Alt-> (end of document). Ctrl-x Ctrl-s saves a file. To simultaneously start two windows or 'buffers' press Ctrl-x 2 (Ctrl-x 1 to revert). Ctrl-x o switches between buffers on the same screen. Alt-x shell opens a Linux shell inside a buffer.

Emacs Reference

Cursor Position
Ctrl-a beginning of line
Ctrl-e end of line
Ctrl-< top of document
Ctrl-> end of document
Alt-x goto-line Go to line
Ctrl-v page forward
Alt-v page backward
Text Deletion/Moving
Backspace delete character before cursor(subject to modification of .emacs)
Ctrl-d delete character under cursor
Alt-d delete word
Ctrl-k delete to end of line(s)(restore with Ctrl-y)
Ctrl-SPC set mark
Ctrl-w delete from mark to cursor(restore with Ctrl-y)
Search and replace
Ctrl-s incremental search forward
Ctrl-r incremental search backward
Ctrl-% query replace
Commands
Ctrl-x u undo
Ctrl-x Ctrl-s save file
Ctrl-x Ctrl-f find file
Ctrl-x 2 2 windows
Ctrl-x 1 1 window
Ctrl-x o switch between windows
Ctrl-x b switch buffers
Alt-q reformat paragraph
Ctrl-x Ctrl-c quit