Emacs Text Editor: A Comprehensive Guide

Introduction

In the early days, text editors lacked sophistication and the ability to handle large documents, which led people to create macros to perform specific tasks. In 1983, Richard Stallman introduced a collection of his macros, naming it editing macros or Emacs. As part of his GNU project, Dr. Stallman's Emacs quickly gained recognition as one of the most advanced applications in its field.

Over the years, it has earned widespread acclaim for its exceptional editing capabilities, efficiency, and various features. Users praise its remarkable customizability and seamless integration capabilities, which makes it a suitable integrated development environment (IDE) for programming languages like C, Java, and Python.

Features of Emacs

  • Lightweight: The editor developed using C and Lisp programming languages exhibits minimal impact on system resources despite being more than just a text editor.

  • Flexible: Emacs can operate in Graphical User Interface (GUI) and Terminal environments. Software engineers, web developers, and Sysadmins find the terminal version indispensable. On the other hand, the GUI version is preferred for its ability to facilitate learning. Additionally, Emacs offers the advantage of remote launching, which benefits software engineers.

  • Portable: Emacs modular code design allows for porting to other systems. Emacs is built with minimal dependencies, making encountering a computer incapable of running Emacs a rarity.

  • Commands: Emacs uses commands similar to Vi and Vim text editors but with a distinct approach. By default, Emacs is centered around the Ctrl and Alt keys. The Ctrl key is denoted by C and the Alt key by M (This convention stems from the historical terminology where the "Alt" key was referred to as the "Meta" key).

How to install Emacs

💡
Note: First, I installed Ubuntu 20.04 LTS on my Windows system and then used the sudo apt install emacs command to install Emacs on my Windows terminal. You can watch a tutorial on how to install Ubuntu 20.04 LTS by following this link. https://www.youtube.com/watch?v=dzmtbyX0sgg

If you have already installed Ubuntu, open up your Terminal and verify the presence of Emacs by typing Emacs and pressing the Enter key. If Emacs is installed, it will open the default welcome message below.

If not, type the following text below into your Terminal:

sudo apt install emacs

How to start Emacs

Type the command Emacs, into your Terminal to open Emacs:

Emacs

When starting Emacs without specifying a file, it displays a welcome message in the following image:

To create a new file, move to the "Visit New File" line in the preceding image and press Tab and Enter.

Alternatively, you can press Ctrl+x, and Ctrl+f to achieve the same outcome.

The Terminal will prompt you to type your file name:

After entering demo and pressing enter, the system will display a blank file for text input:

Emacs-like Terminologies

To operate Emacs efficiently, you must grasp some essential terminologies. These encompass a menu bar, buffer, mode line/status bar, mini buffer, windows, and frames.

Menu Bar

The highlighted top of the screen contains the menu bar, which holds various functions of the Emacs interface. Unlike GUI-based programs, you can't activate terminal-based menus through the mouse.

To access the menus, press the F10 function key. This activates a window beneath the file option in the menu bar revealing a list of available actions and their corresponding key bindings. You can navigate the options using the arrow keys and select an action by pressing the Enter key. The same outcome can be achieved by utilizing the corresponding key bindings.

Exit the menus by pressing Esc three times, regardless of how deep you are in. This action will close the menu and return you to the "main buffer."

Buffer

The current editing window displays text and other information in the buffer. A menu rests at the top of the screen. The space beneath the menu bar is termed the 'main buffer.'

Emacs loads a copy of an existing file into memory, referred to as a buffer when editing, and then displays it in the main editing area. While working through the document, your edits apply to the buffer, while the original file on the disk remains unchanged.

Emacs will auto-save intermittently in the background, but you must manually save to write changes to the disk. The same applies to a new file.

Mode Line/Status Bar

The mode line or the status bar is the highlighted "bar" displayed near the bottom of the screen, following the main buffer. The text displayed in this area depends on the current mode of Emacs. Primarily, the status bar includes:

  • Current editing mode

  • Name of the existing file

  • Current cursor location

  • Status of the file - ( \* for a file with unsaved changes, --* for an unmodified file, and %% for read-only files)

Mini Buffer

The mini buffer is the single line of space after the status bar where the screen ends. In the image below, this space displays Find file.

Emacs operate as a command-driven tool, with the main point of interaction being the mini buffer. In this space, Emacs requests command inputs and displays the resulting output.

Windows

In Emacs, you can split frames into multiple windows, which enables you to open files/buffers within split windows simultaneously. You have the option to split windows either horizontally or vertically.

Split a frame into horizontal windows by pressing Ctrl+x 2 (ctrl+x, then "2"):

Pressing ctrl+x 3 (ctrl+x, then "3") divides a frame into vertical windows:

To split your frame into even more windows, type either ctrl+x 2 or ctrl+x 3 multiple times. For example, press ctrl+x 3, three times to divide your frame into four windows, as illustrated in the following image:

To jump from one window to another, press ctrl+x o (ctrl+x, then the letter "o").

To open multiple files simultaneously, perform the following steps:

  1. Split your frame vertically into two by pressing ctrl+x 3.

  2. Use ctrl+x o and jump to the right-side window.

  3. To visit a new file, press C-x C-f.

In the image below, the file demo appears on the left side, and demo2 is open on the right side:

Press ctrl+x 0 (ctrl+x, then number "0" ) to close your current window.

Frames

The terminal version of Emacs treats frames differently compared to its GUI-based version. Unlike the Gui-based version, terminal Emacs frames don't pop out due to their incapability to do so within a console or terminal environment. Upon initiation, Emacs divides and allocates a buffer between them. This functionality proves beneficial when examining various sections of a file. The mode line/status bar designates them as F1, F2,..., etc.

Below, you can see an example of frames displayed as F1 in the mode line/status bar:

Typing ctrl+x 5 2 (pressing ctrl+x, "5" and "2") opens a new frame, displaying F2 in the mode line/status bar below:

To move between frames, utilize ctrl+x 5 o (press ctrl+x, type "5", and then press the letter "o").

When accessing the GUI-based version of Emacs, your new frame will emerge as a conventional new window.

Emacs Basics

First, let's examine the command keys function within Emacs, exploring their fundamental concepts. Afterward, we will delve into essential tasks such as navigating, saving, and exiting a file.

Command Keys

Upon opening a file, you can begin typing and executing commands.

In general, executing a command often requires a combination of two or three keys. The most commonly used keys for this purpose are Ctrl, Alt, and Esc. In Emacs, the letter C denotes Ctrl.

In the context of Emacs, the Alt and Esc keys denote the Meta keys. However, on Apple devices, Alt is substituted with the option key.

Emacs utilizes the multi-function key. For example, when you input C-x C-s, It indicates that you press Ctrl+x, then press Ctrl+s to execute the action of saving a file.

To abort an operation or command, press the keyboard shortcut Ctrl+G or Esc shown as E.

Meanwhile, Emacs displays Enter as RET, an abbreviation for return.

Navigating a File

Navigating through extensive documents might become challenging; nevertheless, Emacs offers several methods to move around within a file. Some keyboard bindings for navigation include:

  • Ctrl+a: Moving to the start of a line.

  • Ctrl+e: Moving to the end of a line.

  • Alt+a: Navigating to the beginning of a sentence.

  • Alt+e: Navigating to the end of a sentence.

  • Alt+<: Moving to the beginning of the file by inputting Alt + shift + '<' key combination.

  • Alt+>: Moving to the end of the file by inputting Alt + shift + '>' key combination.

  • Ctrl+n: Move to the following line.

  • Ctrl+p: Move to the preceding line.

  • Ctrl+f: Navigate one character forward.

  • Ctrl+b: Navigate one character backward.

  • Alt+f: Move forward by one word.

  • Alt+b: Move back by one word.

Saving and Quitting a File

To save, press Ctrl+x, then Ctrl+s, after you modify or write content within your file. Afterward, an indicator will display in the lower left corner, showing the specific action: 'wrote/home/<name of PC>/<name of file>

To exit Emacs, perform the binding Ctrl+x , then Ctrl+c . If the file contains any unsaved changes when quitting, the system will display the following message:

Save the file by pressing Y.

Pressing N will result in the display of the following message:

Selecting yes indicates your intention to quit without saving.

Emacs Intermediate

Emacs enables you to execute various forms of text manipulation: cutting, copying, pasting, deleting, and more.

Paste, cut, and copy in a File

Execute text manipulation using the following commands:

  • Ctrl+y: paste text.

  • ctrl+w: cut text.

  • Alt+w: copy text.

Undo and Redo in a File

To perform an undo or redo action in a file, utilize the following commands:

  • Ctrl+x u: Undo

  • Ctrl+g Ctrl+_: Redo (This is done by pressing Ctrl+g, then Ctrl+Shift, and - to get an underscore _)

Delete in a File

The Backspace and Delete functions operate similarly to conventional text editors for text deletion. You can utilize alternative commands for deletion:

  • Ctrl+k: Deletes a whole line from the cursor's current position to the end of the line.

  • Alt+d: Delete a word by positioning the cursor at the word's beginning. To delete multiple words simultaneously, press and hold the Alt key while continuously pressing d.

  • Alt+k: Delete an entire sentence.

💡
Note: Emacs will delete an entire line if there aren't two line spaces after the full stop. Emacs determine when a sentence has broken across multiple lines based on the two spaces after a "full stop."

Search and Replace Text in a File

In Emacs, you can search forward or backward. You accomplish this task using the following command:

  • Ctrl+s: To search forward from your current cursor position.

  • Ctrl+r: To search backward from your current cursor position.

After inputting your search item, Emacs will immediately highlight any matches in the main buffer.

To replace the highlighted text above, follow these steps:

  1. Press Alt+% to initiate, prompting the mini buffer to request the text/phrase for query replace::

  2. Type the text you wish to change and Enter:

  3. The Mini buffer displays Query replace your_search_term with: , then you enter the word or phrase you want to replace your_search_term with and press Enter:

  4. The mini buffer will highlight each match and prompt for a replacement. It will ask to replace with query replacing your_search_word with your_replacement_word:(? for help)

  5. Press the y key to substitute the currently identified "match."

  6. Skip to the next "match" by pressing the n key

  7. Quit without any replacements by pressing the q key.

  8. Press ! to perform a global replacement without receiving any prompts. The mini buffer will display the following: replaced number occurrences.

Select/Highlight Text in a File

To Select/highlight text in Emacs, follow the steps below:

  1. Place your cursor in the position you want the selection to start.

  2. Press Ctrl+spacebar or Ctrl+@ to set a "mark" to begin your text highlighting. The mini buffer will show a message of Mark activated.

  3. Move the cursor from that point to any position you want it to end. The text will be highlighted to the point where your cursor is now located.

  4. Press Ctrl+spacebar twice to unmark the selected text. The mini buffer will show a status message of Mark deactivated.

Alternatively, hold down Shift and use the arrow keys to actively highlight your text in any direction, similar to how a conventional word processor functions.

Press Alt+h to select the paragraph your cursor is already on. Continuously press Alt+h to highlight an entire section in your text file.

Press Ctrl+x then h to highlight all the content in the main buffer.

Emacs Advanced

Emacs gained widespread acceptance in the UNIX community because of its capability to assume different modes. A mode enhances Emacs's functionality.

Emacs has two distinct modes: Major mode and Minor mode. Depending on the selected mode, Emacs enables writing text files or adapting for advanced tasks such as coding in Python, C, or Java. For instance, Emacs can be customized to interface with version control systems, execute shell commands, or read man pages.

Major Mode

In major mode, Emacs is an integrated development environment (IDE) for programming or scripting languages. It offers specialized features such as indentation and formatting, automatically interfacing with debuggers and compilers, applying color syntax highlighting, and presenting language-specific menu options.

Examples of major modes:

  • Java-mode

  • Html-mode

  • Python-mode

  • C-mode

  • Text-mode

  • Shell-script-mode

  • Perl-mode

For example, you can write a "Hello Mustapha" application in Python mode.

Enter the following commands within the Terminal:

Emacs identifies the file extension .py, and initiates python mode. Within the main buffer, input the subsequent phyton code:

print "hello Mustapha!\n"

Color syntax highlighting will highlight the keywords. The mode you're currently in will be displayed in the status line above the mini buffer. A separate entry specifically for Python will also appear in the menu bar:

Change the major mode from within Emacs by pressing Alt+x. Input your response into the mini buffer to enter another mode.

Minor Mode

A Minor mode provides distinct features, unlike "Major mode." It can co-exist with a "Major mode" or exert a system-wide effect regardless of the "major mode." Moreover, multiple "minor modes" can concurrently remain in effect while functioning as switches: certain ones are activated by default, while others are not. If a minor mode is already toggled on, invoking it will deactivate it and vice versa.

For example, you can activate the Linum-mode, which is a minor mode, in your emacs editor by pressing Alt+x, and then inputting Linum-mode ( Type Linum, press the spacebar, and then type mode).

This mode activates line numbers along the left edge of the editor. When you invoke a minor mode, it functions as a toggle switch. Invoking the same command will deactivate the line numbers.

Explore additional examples of minor modes below:

  • Menu-bar-mode: Activate or deactivate the menu bar.

  • Line-number-mode: Toggles the current line number to display in the status bar.

  • Column-number-mode: This indicates the position of the cursor on the status bar.

  • Overwrite-mode: As you type, it will replace the text to the right of the cursor.

  • Auto-save-mode: Enables the Toggling of the auto-saving property, which periodically saves the content of the "main buffer" in the background.

Conclusion

This comprehensive guide provides insights into Emacs, covering topics such as the installation of Emacs, familiarization with Emacs-specific terminology, basic to advanced Emacs usage, and exploration of various modes.

To deepen your comprehension, consider delving into the GNU Emacs manual.