We hope you find this tutorial helpful. In addition to guides like this one, we provide simple cloud infrastructure for developers. Learn more →

How To Use the Emacs Editor in Linux

PostedMarch 16, 2014 79.8k views Linux Basics Miscellaneous

Introduction

Emacs is one of the oldest and most versatile text editors available for Linux and UNIX-based systems. It's been around for a long time (more than twenty years for GNU emacs) and is well known for its powerful and rich editing features. Emacs is also more than just a text editor; it can be customized and extended with different "modes", enabling it to be used like an Integrated Development Environment (IDE) for programming languages like Java, C or Python.

For those who have used both the ubiquitous vi and the user-friendly nano, emacs would come as an interesting cross-between. Its strengths and features would resemble those of vi while its menus, help files and easy-to-remember command-keys would compare with nano.

In this article, we will see how we can install emacs in a Linux system and use it for basic text editing. Emacs is also available for graphical window managers for Linux like GNOME; however we will only cover the "text based" version here.

How To Install Emacs

You can check if your Linux system has emacs installed by simply running the following command:

emacs

If the program is installed, the editor will start with the default welcome message. This was not the case in my CentOS 6.5 system:

[root@TestLinux ~]# -bash: emacs: command not found
-bash: -bash:: command not found

So I ran the following command to install the emacs packages:

[root@TestCentOS ~]# yum install emacs

In Ubuntu 12, I ran the following command to install emacs.

root@TestUbuntu:~# apt-get install emacs

In both cases, Linux will query the required package information from available mirrors or software libraries and ask whether you would like to go ahead and install it. It will also give you an estimate of disk space required. Once you say yes (with a single keystroke of "y"), all emacs packages and their dependencies will be downloaded and installed. The process is just like installing any other Linux package: a lot of text messages will scroll by and installation progress will be shown. At the end of it, emacs will be available for you to work with.

First Taste of Emacs

The User Interface

You can start emacs either by itself, issuing the simple command emacs, or by specifying a file name after it. If the file doesn't exist, emacs starts with an empty editing buffer and waits for you to start typing. For an existing file on disk, the contents are copied into memory first and then loaded into the main editing window.

In the screenshot below, I have started emacs by itself. The program displays a welcome message in the main window:

To start a new file, I have moved the cursor over to the link "Visit New File" and pressed Enter. A prompt appears at the bottom of the screen, asking for a file name. Find file: ~/

I type a name for my new file (myfile.txt) and press Enter again. A clean window appears. This is the new file, ready for text entry:

Let's pause for a minute and look at the different parts of the user interface. It's also time we familiarize ourselves with some basic concepts.

At the very top of the screen there is a menu. This is a major difference with vi, where you are presented with an empty screen. This looks like any other application menu and indeed, a lot of emacs functionality is accessible from here.

Later, we will see how we can access it.

After the menu, there is a large editing space. This is called the main buffer where you type your text or view the contents of a file.

Let's talk a bit more about buffers.

When emacs edits an existing file on disk, a copy of that document is first loaded into memory and then displayed in the main editing window. This area in memory is called a "buffer". As you work through the document, all the changes you make in the editing space are applied to the buffer; the original file on disk remains unchanged. Occasionally, emacs will auto-save in the background, but it's only when you manually save the document the changes are actually written to the disk. The same applies for a new file as well: all changes are made on the buffer until you save it.

The main editing space in emacs is therefore your view to the buffer.

After the main buffer, a highlighted bar of text is displayed near the bottom of the screen. This is called the status bar or the mode line. What this shows depends what "mode" emacs is currently in. Among other things, the status bar shows:

  • Name of the current file

  • Current cursor location

  • Current editing mode (in our case it's text mode)

  • The status of the file (-- for an unmodified file, ** for a file with un-saved changes and %% for read-only files)

Finally, a single line of space exists below the status bar where the screen ends. In our example, it's showing the text "(New File)". This area is called the mini buffer. Emacs is a command driven tool and the mini buffer is your main point of interaction with emacs. This is where emacs prompts you for command inputs or shows you the output.

Windows

The text-based version of emacs treats "windows" quite differently from its GUI-based version. Unlike GUI-based applications, text-based emacs windows don't just pop out, they can't physically do so in a terminal or console session. Instead, when emacs needs to start a new window, its main buffer is split into two parts, like having two frames in a browser. The top half shows the main buffer and the bottom half displays the new content. An example of emacs spawning a new window is when you are accessing its help files or tutorials. We will talk more about windows later.

Basic Command Keys

Now that we are familiar with the user interface, it may be tempting to start typing and messing around. Just before we do so, let's spend a few more minutes on emacs' command keys. Like most things in Linux, emacs relies heavily on keyboard commands. Fortunately, most of these keystrokes are fairly standard and easy to remember. Also, unlike vi, emacs doesn't have to switch between editing and command modes. When you open a file with emacs, you can just start typing and issue commands at the same time.

Command functions in emacs usually involve two or three keys. The most common is the Ctrl key, followed by the Alt or Esc key. In emacs literature, Ctrl is shown in short form as "C". So if you see something like C-x C-c, it means "press the Ctrl key and x together, then press Ctrl and c". Similarly, if you see C-h t, it means "press Ctrl and h together, then release both keys and press t".

Alt and Esc keys are referred to as "meta" key in emacs lingo. In Mac machines that's the Option key and in some keyboards it's labelled as Edit. That's why emacs documentations show these keys as "M" (M for meta). Just like the Ctrl key, emacs uses multi-key functions with the meta key. So if you see a notation like M-x, it means "press Alt/Esc/Option/Edit key and x together".

The Enter key is shown as RET (short for "Return") and The Esc key is often shown as E.

The Esc key usually plays its part when you try to back off from a command or prompt. Just keep pressing it till you get out of trouble. Another way of cancelling an operation would be pressing C-g (Ctrl+g).

Saving and Quitting

Once you have made some changes to your document or written some text, you would want to save it.

To save a file, press C-x C-s (Ctrl+x, followed by Ctrl+s). The mini buffer will show a message like this:

Wrote <file_path_and_name>

If you don't want to save but quit, use the command C-x C-c (Ctrl+x, followed by Ctrl+c). If there is unsaved data, the mini-buffer will show a prompt like this:

Save file <file_path_and_name>? (y, n, !, ., q, C-r, d or C-h)

When you press "n" (for no), emacs gives you a second chance to change your mind:

Modified buffers exist; exit anyway? (yes or no)

If you are really sure you don't want to save, type yes (the whole word) and press Enter. This would take you back to command prompt.

Getting Around: Navigation Basics

Navigating through a long document or help topic can be a tedious task if you don't know the right keys. Fortunately, in emacs there are not too many of these to remember and they are quite intuitive. Here is a list:

To perform this function             | Use these keys
-------------------------------------|---------------------------------
Moving to the next line              | C-n (n for Next)
Moving to the previous line          | C-p (p for Previous)
Moving one character forward         | C-f (f for Forward) 
Moving one character backward        | C-b (b for Backward)
Moving one word forward              | M-f (f for Forward) 
Moving one word backward             | M-b (b for Backward)
Moving to the start of a line        | C-a 
Moving to the end of a line          | C-e (e for End)
Moving to the start of a sentence    | M-a
Moving to the end of a sentence      | M-e (e for End)
Moving one page down                 | C-v (or PgDn)
Moving one page up                   | M-v (or PgUp)
Moving to the beginning of the file  | M-< (Alt + Shift + "<")
Moving to the end of the file        | M-> (Alt + Shift + ">")

As mentioned before, C stands for Ctrl key and M stands for meta (Alt / Option / Esc / Edit).

Basic Editing Functions

We will now learn about some basic editing functions in emacs. Let's start with the simple task of selecting text.

Marking Text Regions

To mark a text region (similar to selecting text in popular word processors), follow these steps:

  • Move the cursor to the position where you would like the selection to start. You can use any of the methods described before to move the cursor.

  • Press C-Space (Ctrl + Space Bar) or C-@ to set a mark. The mini buffer will show a status message of Mark set.

  • Move the cursor to the position where you want the region to end. Again, use any of the key combinations described before.

  • The text will be highlighted up to the point where your cursor is now located.

  • If you want to "un-mark" the highlighted text, press C-Space or C-@ twice. The mini buffer will show a status message of Mark deactivated.

Here is an example of marked text:

If you want to select the all the contents of the main buffer (i.e. "select all"), press C-x h.

Pressing M-h will select the current paragraph.

Cut, Copy & Paste

Once you have the text region marked, you can copy or cut the text and paste it elsewhere.

  • For copying the text, press E-w

  • For cutting the text, press C-w

  • Move your cursor to the position where the text needs to be pasted.

  • Press C-y (y stands for "yank" - you are yanking the text from one position to another). The contents will be pasted here.

Deleting Text

For deleting, Backspace and Delete keys work just the way you would expect them to work.

For deleting a whole word, move the cursor at the beginning of a word and press M-d. For deleting multiple words, hold the meta key down and keep pressing d. Words will start deleting one by one.

For deleting a whole line, position the cursor where you want it to be and press C-k. This would delete the text right up to the end of the line on screen.

For deleting a sentence, press M-k. Just so that we know, emacs considers a sentence to have completed when it sees two spaces after the full stop. This is unlike traditional publishing where a new sentence begins after a single space following a full stop. That's how emacs is smart enough to know even when a sentence has broken across multiple lines.

Undo & Redo

Undoing the last operation is simple. Press C-x u. You can keep repeating this to go backwards. Another key combination is C-/ (Ctrl + /) or C-_ (Ctrl + _).

For redoing your last undo, press C-g, followed by C-_ (that's Ctrl + Shift+ Underscore). Another way to do the same thing would be to press C-x C-u again (Undoing the Undo).

Search & Replace

There are two search directions in emacs: forward and backward. In forward search, the word you specify will be searched forward from the current cursor position. For backward search, it's the other way round.

  • Press C-s for forward search

  • Press C-r for backward search

The mini-buffer will display a prompt like

I-search:

or

I-search backward:

As soon as you start typing, emacs will try to search for the text being typed and highlight any matches it finds in the main buffer.

Here is an example. The next screenshot shows we are trying to search for the word "cat". Note how every occurrence in the main buffer is highlighted.

For replacing text, follow these steps:

  • Press M-% (that's Alt + Shift + %). The mini buffer shows the prompt for the text to be searched (Query replace:).

  • Type the text and press Enter

  • The mini buffer displays a message like (Query replace <search_word> with:)

  • Type the replacing text and press Enter.

  • For each match emacs finds, it will ask whether you would like to make a replacement (Query replacing <search_word> with <replace_word>: (C-h for help)). You can take any of the following actions:

  • Press y to replace the current match found.

  • Press n to skip to the next match.

  • Press q to exit without any replacements (basically escaping).

  • Press ! to do a global replace without any prompts. (emacs will show a message like replaced n occurrences)

Spell Check

Spell checking is performed in emacs through the ispell spell-checker. You can use ispell to check spelling of the whole buffer or a selected region.

Just so that we know, ispell did not install by default in my test CentOS 6.5 and Ubuntu 12 systems when I installed emacs (this was emacs 23.3.1). I had to install ispell separately using the following command for Ubuntu:

root@TestUbuntu:~# apt-get install ispell

And for CentOS, it was hunspell:

root@TestCentOS:~# yum install hunspell

Now if you have the spell checker installed and working in your system, press M-x (Alt + x). The mini buffer will await your response. Type ispell- and press tab:

M-x: ispell-

A new window will open under the main buffer and display different options related to ispell:

In this buffer, type RET to select the completion near point.

Possible completions are:
ispell-buffer                          ispell-change-dictionary
ispell-comments-and-strings            ispell-complete-word
ispell-complete-word-interior-frag     ispell-continue
ispell-kill-ispell                     ispell-message
ispell-minor-mode                      ispell-pdict-save
ispell-region

Start typing "b" after ispell- in the mini buffer and press tab again. Emacs will complete it with the option ispell-buffer. Press Enter and emacs will start spell checking for the entire document.

The following two screenshots were taken from an Ubuntu system. We have the popular nursery rhyme written in emacs with a few spelling mistakes here and there. Once ispell is invoked, note how emacs suggests the correct spelling and prompts you to choose the right word. When you type the number corresponding to a suggestion, that replacement will happen and ispell will move to the next misspelled word.

Once the spell checking completes, the mini buffer will show a message like this:

Spell-checking <file_name> using ispell with american dictionary...done

Left, Right and Centre Alignment

For centering a line, move the cursor at the beginning of the line and press M-o M-s (Alt-o followed by Alt-s).

For justifying a selected text region, follow these steps:

  • Create a text region to highlight the text you wish to justify

  • Press M-x. The mini buffer will await a response

  • Start typing set-justifiction- and press Tab.

  • You will be given completion options like set-justification-center, set-justification-left, set-justification-right, set-justification-none and set-justification-full

  • Complete the justification command (for example set-justification-right) and press Enter.

  • The selected text will be justified.

In the first part of the following image, the original text has been selected (highlighted in blue). We have then used the set-justification commands to right, left and centre justify the text.

Converting Case

Here are some command keys for converting cases.

To perform this function                 | Use these keys
-----------------------------------      |----------------------------
Capitalizing a word after the cursor     | M-c (c for Capitalize)
Converting a word to lower case          | M-l (l for Lower case)
Converting a word to upper case          | M-u (u for Upper case) 
Converting a paragraph to upper case     | Block select, then C-x C-u
Converting a paragraph to lower case     | Block select, then C-x C-l  

Accessing the Menus

When emacs starts, it usually takes up the whole screen. Most of its functions are also accessible from a menu bar located at top of the screen.

Unlike GUI-based programs, text-based emacs menus can't be pulled down by mouse. In fact you can't even highlight and scroll through the menus with a shortcut key.

To access the menus, you will have to press the F10 key. This would open another window under the main buffer and display a list of keys to access the menu items. The mini buffer will show a prompt for you to enter the required key. Once you press that key, contents of the new window will change, reflecting the next level of options. From there you can dig deeper and deeper.

To get out of the menus (no matter how deep you are in), just press the Esc key three times (Esc-Esc-Esc). This would usually close the menu window and you will be back in the main buffer.

In the following two screenshots, the main menu window has opened under the main buffer and the Edit menu options are displayed. Note the prompt in the mini-buffer.

To give an idea of the power of emacs, here are some extras available from its Tools menu:

  • Calendar

  • Simple calculator

  • Programmable calculator

  • Searching a directory

  • Encrypting and decrypting document

  • Send and read e-mails

  • Search files using grep

  • Spell checking

  • Running shell commands and compiling codes

  • Version control

  • Compare and merge files

Accessing Help & Tutorials

Emacs has an extensive help system and tutorial available. Accessing it is fairly simple: you can either use the menu or use a shortcut key.

Here is how you can find help through the menu:

  • Press the F10 key. A new window will open beneath the main buffer showing main menu options.

  • Press h (for help). The contents of the window will change to something like this:

Press PageUp key to reach this buffer from the minibuffer.
Alternatively, you can use Up/Down keys (or your History keys) to change
the item in the minibuffer, and press RET when you are done, or press the
marked letters to pick up your choice.  Type C-g or ESC ESC ESC to cancel.
In this buffer, type RET to select the completion near point.

Possible completions are:
e==>Emacs Tutorial                     E==>Emacs Tutorial (choose language)...
f==>Emacs FAQ                          n==>Emacs News
k==>Emacs Known Problems               s==>Send Bug Report...
p==>Emacs Psychotherapist              S==>Search Documentation
d==>Describe                           r==>Read the Emacs Manual
m==>More Manuals                       F==>Find Emacs Packages
P==>External Packages                  g==>Getting New Versions
c==>Copying Conditions                 0==>(Non)Warranty
a==>About Emacs                        A==>About GNU

From here, choose the appropriate option.

Alternately, if you favor short-cut keys, here is a quick list:

  • To access the emacs tutorial, press C-h t

  • To read the emacs manual, press C-h r

Managing Windows

One of the things you need to know for getting around in emacs is how to manage windows. Take an example: you are writing a document and need to access the emacs tutorial. You press C-h t and the tutorial starts in its full window in the main buffer. How do you get back to your document? Esc won't work, neither would C-g.

Press C-x b to get out of the active buffer (in this case it's the tutorial). This is the switch buffer command. Emacs will prompt you for a buffer name. You can start typing the buffer name (the document name in this case) and press tab. Just like command completion in the main shell, emacs will complete the rest. Press Enter and you will be back in your document.

Here is an an example where I have just opened the tutorial window and want to get back to my main document called myfile.txt. I have issued the command C-x b and emacs prompts me with a buffer name.

Emacs commands generally involve the CONTROL key (sometimes labeled
CTRL or CTL) or the META key (sometimes labeled EDIT or ALT).  Rather than
write that in full each time, we'll use the following abbreviations:

 ...
 ...
 ...

-=--:**--F1  TUTORIAL       Top L1     (Fundamental)----------------------------
Switch to buffer (default myfile.txt): my

I type "my" at the prompt and press tab again and emacs completes the rest for me. Pressing Enter then takes me back to the document.

Once I am back in the main buffer for the document, I can press C-x b again to switch to the TUTORIAL buffer. I can start typing "TU" and press tab. Emacs will complete the rest and pressing Enter will take me to the tutorial page.

Another option for getting out of windows is to press C-x 0. This usually kills the currently active window.

Emacs Modes

One of the reasons emacs has been adopted so widely in the UNIX community is due to its ability to assume different modes. A mode in emacs lingo determines how it's behaving under current settings.

Depending on the mode selected, emacs can be used as a simple word processor for writing text files, like we have been doing so far or it can be adapted for other advanced tasks, like writing Python, C or Java code. For example, you can change emacs' mode to make it work with version control systems, run shell commands or read man pages.

There are two different types of emacs modes. One is called the major mode. In major mode, emacs can be used as an integrated development environment for programming or scripting languages. In these modes, the program offers specialized features like color syntax-highlighting, indentation and formatting, language specific menu options or automatic interfacing with debuggers and compilers.

To give an example, we will write a simple "Hello World" app in Python using emacs.

At the shell prompt, emacs is invoked with the name of our Python file:

[root@TestCentOS ~]# emacs hello.py

Emacs is smart enough to know the file extension and will start in Python mode. As you can see in the screenshot, the status line shows the mode (Python) and the main menu also has a separate entry for Python.

We then write the code for our hello world app. Note how the main buffer is now showing keywords and comments in different colors.

We can now save the file, quit emacs, change the file's permission and run it from the command prompt.

To change the major mode from within emacs, press the M-x keys. The mini buffer will wait for your response. Examples of some major modes are:

  • c-mode

  • python-mode

  • java-mode

  • html-mode

  • perl-mode

  • shell-script-mode

To get back to simple text editing, type text-mode and press Enter.

Compared to major modes, minor modes offer specific features. Generally speaking, these features can be either tied to a specific major mode, or have a system-wide effect, irrespective of the major mode. Also, unlike major modes, there can be multiple minor modes in effect at any one time. Minor modes are also like switches: some are enabled by default, some are not. If a minor mode is already on, calling it will switch it off. If it is off, it will be switched back on.

We have used two minor modes before: one was with the ispell-mode for spell checking, the other one was for setting justification.

Here is another example of minor mode:

M-x: auto-fill-mode

This mode enables a line of text to break and wrap to the next line when its length becomes more than 70 characters. It's a toggle switch, which means invoking it again will disable the line wrap.

Here are some examples of minor modes:

  • auo-save-mode: This toggles the property of auto saving that periodically saves the contents of the main buffer behind the scene.

  • line-number-mode: This toggles the display of current line number in the status bar.

  • linum-mode: Toggles the display of line numbers along the left edge of the window.

  • column-number-mode: Shows the current position of the cursor in status bar.

  • overwrite-mode: This is like pressing the INS key. When switched on, it will overwrite text on the right side of cursor as you type.

  • menu-bar-mode: This can switch the main menu on or off.

Conclusion

It's been a very basic introduction to emacs. We have not touched on more advanced topics like editing an emacs configuration file or enhancing its functionality through scripts.

The program was written in Lisp and C and its raw power comes from the ability to write code in Elisp (Emacs Lisp) for customizing its default behavior. With Elisp, programmers and power users can change or enhance emacs features, record macros, create new shortcut keys or build a new functionality. Like any advanced computer software, emacs has a large command set and mastering everything isn't easy. There's so much to it that there are entire developer communities and programming resources in the Internet that focus solely on emacs commands and how-tos.

But what we have covered here today will help you get started with basic editing, and that's all you may need for the moment. Once you are familiar with the basic commands, you can move on to more advanced topics.

The GNU Emacs web page has a wealth of information including links to other resources like Emacs Wiki. I strongly recommend you visit this site.

Sadequl Hussain

4 Comments

Creative Commons License