emacs Command: Tutorial & Examples
Edit text files efficiently using the Emacs text editor from the command line
Emacs is a highly extensible and powerful text editor widely used on Linux servers and other Unix-like systems. It provides a
versatile environment for editing text files, programming, project management, and even email, all accessible from the command line. This
article explains the emacs
command, focusing on its usage in server environments, essential commands, configuration, scripting, and practical examples to help
administrators and developers manage files and tasks efficiently.
What Emacs Is And Why It Is Important
Emacs is more than a basic text editor; it is a customizable ecosystem that integrates editing, scripting, and workflow tools. Originally developed in the 1970s, Emacs was designed to provide users with a flexible and extensible editing experience. It uses its own scripting language, Emacs Lisp, to enable automation and customization.
For Linux server administrators, Emacs is important because it can run entirely inside a terminal, requiring no graphical interface. This makes it ideal for remote management over ssh or on headless servers. Its powerful editing capabilities, extensive package ecosystem, and integrated shell support allow complex tasks to be performed without leaving the editor.
Compared to other terminal editors like vim
or nano
, Emacs offers a more integrated and programmable
environment, suitable for users who prefer extensive customization and automation.
How Emacs Works: Core Concepts And User Interface
Emacs operates around a few fundamental concepts that define its user interface and workflow:
Buffers: In-memory containers holding text content. Buffers may represent files, process outputs, or temporary scratch text. Multiple buffers can be open simultaneously, and you can switch between them. For example, when you open a file, Emacs creates a buffer for it.
Windows: Subsections of an Emacs frame displaying buffers. Windows can be split vertically or horizontally to view multiple buffers side-by-side, allowing you to work on several files or views simultaneously.
Frames: The top-level windows managed by the windowing system or terminal. In terminal mode (with
-nw
), typically only one frame is visible, but in graphical mode, multiple frames can be open.Minibuffer: A single-line input area at the bottom of the frame used to enter commands, file names, or other information. For example, when opening a file with
Ctrl+x Ctrl+f
, the minibuffer prompts for the file name.
These elements create a flexible and programmable editing environment, allowing you to customize how information is displayed and manipulated.
Starting Emacs From The Command Line And Command Line Options
To start Emacs and open or create a file, use the following syntax:
emacs filename.txt
If filename.txt
does not exist, Emacs will create a new buffer for it.
To run Emacs entirely inside the terminal without a graphical window, use the -nw
(no window) option:
emacs -nw filename.txt
This mode is useful when working on servers without graphical environments or over slow network connections.
To open Emacs without loading any file, simply run:
emacs
This opens Emacs with an empty *scratch*
buffer where you can type or evaluate Emacs Lisp code.
You can open multiple files at once by listing them:
emacs file1.txt file2.txt
Emacs will open each file in a separate buffer.
Common Command Line Options
Emacs provides many command line options to control its behavior. Some common and useful parameters include:
-nw
: Run Emacs in the terminal without a graphical window.-Q
: Start Emacs without loading any initialization files (useful for troubleshooting).--batch
: Run Emacs in batch mode for executing scripts or processing files without opening the editor or displaying UI.--daemon
: Start Emacs as a background server process, allowing clients to connect quickly.-l FILE
: Load a specific Emacs Lisp file during startup.--version
: Display Emacs version information.--help
: Show usage information and command line options.
Example: Start Emacs daemon in the background:
emacs --daemon
Then connect to it with:
emacsclient -nw filename.txt
This allows fast loading and shared sessions.
Basic Usage And Common Keybindings
Emacs is primarily controlled via keyboard shortcuts (keybindings). Commands typically involve pressing one or more modifier keys followed by letters or other keys. Here are essential ones for daily use:
Save the current buffer (file): Press
Ctrl+x
thenCtrl+s
Open a file: Press
Ctrl+x
thenCtrl+f
Cut (kill) selected text: Press
Ctrl+w
(after selecting a region)Copy (kill-ring save) selected text: Press
Alt+w
Paste (yank) text: Press
Ctrl+y
Undo last change: Press
Ctrl+/
orCtrl+x u
Search forward: Press
Ctrl+s
Search backward: Press
Ctrl+r
Switch to another buffer: Press
Ctrl+x b
Split window vertically (below): Press
Ctrl+x 2
Split window horizontally (right): Press
Ctrl+x 3
Move cursor to other window: Press
Ctrl+x o
Exit Emacs: Press
Ctrl+x
thenCtrl+c
How To Exit Emacs Safely
Exiting Emacs properly is essential to avoid losing unsaved changes. To exit:
Press
Ctrl+x
thenCtrl+c
.If there are unsaved buffers, Emacs will prompt you to save them:
Press
y
to save the current buffer.Press
n
to discard changes.Press
Ctrl+g
to cancel the exit.
If you want to quit Emacs without saving changes to all buffers, run:
emacs -Q -nw
and then exit, or use the prompts to discard changes.
Selecting Text (Setting The Region)
To select text in Emacs:
Move the cursor to the start position.
Press
Ctrl+Space
to set the mark.Move the cursor to the end position.
This highlights the region, which can then be cut or copied with the keybindings above.
Keybinding Cheatsheet Example
Saving a file:
Ctrl+x Ctrl+s
Opening a new file:
Ctrl+x Ctrl+f
Cut, copy, paste:
Ctrl+w
,Alt+w
,Ctrl+y
Undo:
Ctrl+x u
Search and replace:
Ctrl+s
,Ctrl+r
Split window:
Ctrl+x 2
(vertical),Ctrl+x 3
(horizontal)Switch buffer:
Ctrl+x b
Exit Emacs:
Ctrl+x Ctrl+c
Configuring Emacs And Installing Packages
Emacs is highly customizable via Emacs Lisp code placed in configuration files, typically ~/.emacs
or ~/.emacs.d/init.el
.
Example: Enable line numbers globally by adding the following line to your config file:
(global-display-line-numbers-mode t)
To install and manage packages, Emacs includes a built-in package manager. The typical workflow:
Start Emacs and refresh the package list by running:
M-x package-refresh-contents
Install a package by running:
M-x package-install RET package-name RET
For example, to install magit
(a Git interface):
M-x package-install RET magit RET
You can automatically load packages by adding appropriate Emacs Lisp code to your init file, for example:
(require 'magit)
Practical Examples Using Emacs
- Editing Configuration Files
Use Emacs to edit important system files, for example:
sudo emacs -nw /etc/ssh/sshd_config
- Using Org-Mode for Notes and Task Management
Emacs includes org-mode
, a powerful tool for organizing notes, TODO lists, and project planning. To use it, open or create a file with the .org
extension:
emacs -nw notes.org
- Git Integration with Magit
After installing magit
, start it with:
M-x magit-status
This command opens an interactive Git interface within Emacs.
- Managing Multiple Buffers
Open several files and switch between them:
emacs file1.txt file2.txt
Switch buffers with:
Ctrl+x b
- Splitting and Navigating Windows
Split the current window vertically or horizontally:
Ctrl+x 2 (split window below)
Ctrl+x 3 (split window right)
Navigate between windows with:
Ctrl+x o
Introduction To Emacs Lisp And Scripting
Emacs uses its own scripting language called Emacs Lisp, which allows deep customization and automation of editing tasks.
You can write Emacs Lisp code in your config files or scripts to extend functionality.
Example: Define a function to insert the current date at the cursor position:
(defun insert-current-date ()
"Insert the current date at point."
(interactive)
(insert (format-time-string "%Y-%m-%d")))
Bind this function to a key combination by adding to your init file:
(global-set-key (kbd "C-c d") 'insert-current-date)
You can execute Emacs Lisp scripts in batch mode without opening the UI:
emacs --batch -l script.el
Example script.el
that inserts the date into a file:
(with-temp-buffer
(insert (format-time-string "%Y-%m-%d\n"))
(write-file "date.txt"))
Running this will create or overwrite date.txt
with the current date.
Scripting And Automation
Emacs can be scripted and automated for repetitive tasks or complex workflows.
- Running Emacs Lisp Scripts in Batch Mode
Use the --batch
option to process files or run commands without the interactive editor:
emacs --batch -l your-script.el
- Using emacsclient For Faster Interaction
Start an Emacs server with:
emacs --daemon
Then connect quickly to the running server with:
emacsclient -nw filename.txt
This avoids the startup delay of launching a new Emacs instance and allows sharing one editing session.
- Writing Simple Automation Functions
Create custom functions in Emacs Lisp and bind them to keys for quick access, as shown in the previous section.
Common Errors And Troubleshooting
If Emacs appears unresponsive or stuck, press
Ctrl+g
to cancel the current command.To quit Emacs without saving changes, press
Ctrl+x Ctrl+c
and when prompted, typen
to discard changes.If you accidentally close a buffer, recover it by pressing
Ctrl+x b
and typing the buffer name.Emacs autosaves files to
~/.emacs.d/auto-save-list/
which can be used to recover unsaved work after crashes.If startup hangs or behaves unexpectedly, try starting with
emacs -Q
to bypass configuration files.On slow or unreliable SSH connections, running Emacs with
-nw
is recommended to avoid GUI overhead.If you see errors installing packages, ensure that your network connection is active and package archives are reachable.
Common pitfalls when using Emacs remotely:
Forgetting to use
-nw
can cause slow or broken GUI forwarding over SSH.Not starting an Emacs server can cause longer startup times.
Configuration files may not load if permissions are incorrect.
Performance Considerations
Emacs is relatively lightweight but can consume more memory when running many buffers or packages.
Monitor resource usage on low-powered servers using tools like
top
orhtop
.Starting Emacs as a daemon reduces startup overhead and improves workflow efficiency.
Security Considerations
Running Emacs as root (e.g., with
sudo
) should be done cautiously to avoid security risks or configuration conflicts.Emacs supports encryption modes for sensitive files and can be configured to use secure protocols when integrated with tools like
git
.Avoid running untrusted Emacs Lisp code to prevent potential code execution vulnerabilities.
See Also
vim
– another popular terminal-based text editornano
– simple command-line text editorsudo
– running commands with elevated permissionsssh
– remote terminal accessgit
– version control system/etc/ssh/sshd_config
– SSH server configuration file/etc/fstab
– filesystem configuration file
Further Reading
Bash Cookbook by Carl Albing, J.P. Vossen (partner link)
Wicked Cool Shell Scripts by Dave Taylor, Brandon Perry (partner link)
Black Hat Bash by Nick Aleks, Dolev Farhi (partner link)
Bash Pocket Reference by Arnold Robbins (partner link)
The Linux Command Line by William Shotts (partner link)
Learning the Bash Shell by Cameron Newham (partner link)
Mastering Linux Shell Scripting by Mokhtar Ebrahim, Andrew Mallett (partner link)
Linux Command Line and Shell Scripting Bible by Richard Blum, Christine Bresnahan (partner link)
Shell Scripting by Jason Cannon (partner link)
As an Amazon Associate, I earn from qualifying purchases.