This project provides a tiny init.el
file to set up Emacs quickly.
This document provides a detailed description of how to set it up and
get started with Emacs.
Further this project also provides a tiny convenience command named
em
to start Emacs server and edit files using Emacs server. This
helps in using Emacs efficiently. This script and its usage is
explained in detail later in the Emacs Server and
Emacs Launcher sections. Here is how the Emacs
environment is going to look after setting up this project:
If you are already comfortable with Emacs and only want to understand
the content of init.el
or em
, you can skip ahead directly to
the Line-by-Line Explanation section that
describes every line of these files in detail.
Contents
- Who Is This For?
- Features
- Get Started
- Step-by-Step Usage
- Useful Terms
- Line-by-Line Explanation
- Opinion References
- Channels
- License
Who Is This For?
Are you an absolute beginner to Emacs? Are you so new to Emacs that
you do not even have ~/.emacs.d
on your file system? Have you come
across recommendations to use starter kits like Doom Emacs, Spacemacs,
etc. but then you wondered if you could use vanilla Emacs and
customize it slowly to suit your needs without having to sacrifice
your productivity in the initial days of using Emacs? Do you also want
your Emacs to look sleek from day zero? If you answered “yes” to most
of these questions, then this project is for you.
The init.el
file in this project provides a quick way to get
started with setting up your Emacs environment. This document explains
how to do so in a step-by-step manner. This document also explains the
content of init.el
and em
in a line-by-line manner.
Note that many customizations in the Emacs initialization file
available in this project are a result of the author’s preferences.
They may or may not match others’ preferences. They may or may not
suit your taste and requirements. Wherever applicable, the pros and
cons of each customization and possible alternatives are discussed in
this document. You are encouraged to read the line-by-line explanation
that comes later in this document, understand each customization, and
modify the initialization file to suit your needs.
Note: If you want to use Emacs specifically for programming in Common
Lisp, please see Emacs4CL first
to quickly set up a Common Lisp (CL) development environment using
Emacs. Once you have set up your CL development environment using
Emacs4CL, you can then come back to this project and pick more ideas
and Emacs Lisp code to enhance your Emacs setup from being a CL
development environment to being a more general purpose editing and
programming environment.
Features
This project provides a file named init.el
that offers the
following features:
- Disable some UI elements to provide a clean and minimal
look-and-feel. - Show current column number in the mode line.
- Load a dark color theme named Wombat.
- Customize the color theme to accentuate the cursor, search
matches, and comments with different shades of orange. - Enable and configure Ido mode to find files and switch buffers
efficiently. - Enable Fido mode for automatic completion of minibuffer input.
- Show trailing whitespace at the end of lines clearly.
- Show trailing newlines at the end of buffer clearly.
- Show missing newlines at the end of buffer clearly.
- Always add a newline automatically at the end of a file while
saving. - Use single spacing convention to end sentences.
- Use spaces, not tabs, for indentation.
- Configure indentation settings as per popular coding conventions.
- Highlight matching parentheses.
- Move auto-save files and backup files to a separate directory to
keep our working directories tidy. - Do not move original files while creating backups.
- Automatically install configured packages when Emacs starts for
the first time. - Install Markdown mode for convenient editing of Markdown files.
- Install and configure Paredit for editing S-expressions
efficiently. - Install and configure Rainbow Delimiters to color parentheses by
their nesting depth level. - Provide a minimal example of a user-defined custom command and a
few custom key sequences. - Start Emacs server automatically, so that terminal users can use
Emacs client to edit files with an existing instance of Emacs.
Additionally, this project also provides a convenience command named
em
that is a thin wrapper around the emacs
and emacsclient
commands. It offers the following features:
- Start a new instance of Emacs when requested.
- Open files in an existing Emacs server if a server is running
already. - Automatically start a new Emacs server if a server is not running
already.
All of these features along with every line of code that enables these
features are explained in the sections below.
Get Started
This section helps you to set up Emfy quickly and see what the end
result looks like. Perform the following steps to get started:
-
Install Emacs.
On macOS, enter the following command if you have
Homebrew:brew install --cask emacs
On Debian, Ubuntu, or another Debian-based Linux system, enter the
following command:sudo apt-get install emacs
For other environments, visit https://www.gnu.org/software/emacs/
to see how to install Emacs. -
Copy the Emacs initialization file
init.el
provided here to
your home directory. Here is an examplecurl
command that does
this:Here is another alternative that copies the initialization file to
an XDG-compatible location as follows:Emacs can automatically load the Emacs initialization file from
any of the paths used above. See section The Emacs Initialization
File of the Emacs manual for more details about
this.Copy the Emacs launcher script
em
provided here to some
directory that belongs to yourPATH
variable. For example, here
are a few commands that download this script and place it in the
/usr/local/bin/
directory:The usefulness of this launcher script will be explained in the
section Emacs Launcher later.Start Emacs:
On macOS, you may receive the following error message in a dialog
box: ‘“Emacs.app” can’t be opened because Apple cannot check it for
malicious software.’ To resolve this issue, go to Apple menu >
System Preferences > Security & Privacy > General and click ‘Open
Anyway’.It may take a minute or so for Emacs to start the very first time.
When it starts the first time with the new Emacs initialization
file obtained in the previous step, it installs the packages
specified in it. This is only a one-time activity. The next time
you start Emacs, it will start instantly. We will see how
init.el
takes care of it in the line-by-line guide later.Now that your environment is setup, read the next section to learn how
to use this environment in more detail.Step-by-Step Usage
Use Emacs
Emacs is a very powerful and extensible editor. It comes with over
10,000 built-in commands. A small section like this can barely scratch
the surface of Emacs. Yet, this section makes a modest attempt at
getting you started with Emacs and then provides more resources to
learn further. Perform the following steps to get started:-
Start Emacs:
-
Within Emacs, enter the following command to open a file, say,
hello.txt
:A new buffer to edit
hello.txt
is created. If a file with that
name already exists on your file system, then it loads the content
of the file into the buffer.Note that in the Emacs world (and elsewhere too), the
notationC-
denotes the ctrl modifier key. ThusC-x
denotes ctrl + x.The notation
RET
denotes the enter or return
key.Typing consecutive
C-
key sequences can be optimized by pressing
and holding down the ctrl key, then typing the other
keys, and then releasing the ctrl key. For example, to
typeC-x C-f
, first press and hold down ctrl, then
type x, then type f, and then release
ctrl. In other words, think ofC-x C-f
asC-(x f)
.
This shortcut works for other modifier keys too. -
Now type some text into the buffer. Type out at least 3-4 words. We
will need it for the next two steps. -
Move backward by one word with the following key sequence:
Remember from the previous section that
M-
denotes the meta
modifier key. The above command can be typed with
alt + b or option + b or
esc b.If you face any issue with the alt key or the
option key, read Emacs Wiki: Meta Key
Problems. -
Now move forward by one word with the following key sequence:
-
The
C-g
key sequence cancels the current command. This can be used
when you mistype a command and want to start over or if you type a
command partially, then change your mind and then you want to cancel
the partially typed command. Try out these examples: -
Save the buffer to a file on the file system with this command:
-
Quit Emacs:
Now you know how to start Emacs, open a file, save it, and quit. Improve
your Emacs knowledge further by taking the Emacs tutorial that comes
along with Emacs. In Emacs, typeC-h t
to start the tutorial.The key bindings to perform various operations like creating file,
saving file, quitting the editor, etc. may look arcane at first, but
repeated usage of the key bindings develops muscle memory soon and after
having used them for a few days, one does not even have to think about
them. The fingers do what the mind wants effortlessly due to muscle
memory.While you are getting used to the Emacs key bindings, keep this GNU
Emacs Reference Card handy. Also, if you are using it in
GUI mode, then the menu options can be quite helpful.Use Paredit
Paredit helps in keeping parentheses balanced and also in performing
structured editing of S-expressions in Lisp code. It provides a powerful
set of commands to manipulate S-expressions in various ways. Perform the
following steps to get started with Paredit:-
Run Emacs:
-
Open an Emacs Lisp source file:
-
Type the following code only:
At this point, Paredit should have inserted the two closing
parentheses automatically. The code should look like this:The cursor should be situated just after the parameter
x
. The
underbar shows where the cursor should be. -
Type the closing parentheses now. Yes, type it even if the closing
parenthesis is already present. The cursor should now skip over the
first closing parenthesis like this:Of course, there was no need to type the closing parenthesis
because it was already present but typing it out to skip over it
is more efficient than moving over it with movement commands. This
is, in fact, a very nifty feature of Paredit. We can enter code
with the same keystrokes as we would without Paredit. -
Now type
enter
to create a new line just before the
last parenthesis. A newline is inserted like this: -
Now type only this:
Again, Paredit would have inserted the closing parenthesis
automatically. The code should look like this now:(defun square (x) (* x x)) -
There is a lot more to Paredit than this. To learn more, see The
Animated Guide to Paredit.Note: While many Lisp programmers find Paredit very convenient and
powerful while manipulating S-expressions in Lisp code, there are a few
people who do not like Paredit because they find the Paredit behaviour
intrusive. See the Opinion References section for
more discussion on this topic.Execute Emacs Lisp Code
The previous section shows how to write some Emacs Lisp code and how
Paredit helps in keeping the parentheses balanced. In this section, we
will see how to execute some Emacs Lisp code.-
Run Emacs:
-
Open an Emacs Lisp source file:
-
Enter the following code:
(defun square (x) (* x x))
-
With the cursor placed right after the last closing parenthesis,
typeC-x C-e
. The name of the function defined should appear in
the echo area at the bottom. This confirms that the function has
been defined. -
Now add the following code to the Emacs Lisp source file:
-
Once again, with the cursor placed right after the last closing
parenthesis, typeC-x C-e
. The result should appear in the echo
area at the bottom.
Use Rainbow Delimiters
There is not much to learn about using Rainbow Delimiters. In the
previous sections, you must have seen that as you type nested
parentheses, each parenthesis is highlighted with a different color.
That is done by Rainbow Delimiters. It colors each parenthesis
according to its nesting depth level.Note: Not everyone likes Rainbow Delimiters. Some people find
parentheses in multiple colors distracting. See the Opinion
References section for more discussion on this
topic.Useful Terms
In this section, we clearly state the various terms that we use later
in this document.-
Frame: The Emacs manual uses the term frame to mean a GUI
window, or a region of the desktop, or the terminal where Emacs is
displayed. We do not call it window in Emacs parlance because the
term “window” is reserved for another element discussed further
below in this list. -
Menu bar: An Emacs frame displays a menu bar at the very top. It
allows access to commands via a series of menus. -
Echo area: An Emacs frame displays an echo area at the very
bottom. The echo area displays informative messages. -
Minibuffer: The echo area is also used to display the
minibuffer, a special buffer where we can type and enter arguments
to commands, such as the name of a file to be edited after typing
the key sequenceC-x C-f
. -
Tool bar: On a graphical display, a tool bar is displayed
directly below the menu bar. The tool bar contains a row of icons
that provides quick access to several editing commands. -
Window: The main area of the frame between the menu bar or the
tool bar (if it exists) and the echo area contains one or more
windows. This is where we view or edit files. Each window displays
a buffer, i.e., the text or graphics we are editing or viewing.
By default, only one window is displayed when we start Emacs. We
can then split this main area into multiple windows using key
sequences likeC-x 2
,C-x 3
, etc. and then open different
files or buffers in different windows. -
Mode line: The last line of each window is a mode line. It
displays information about the buffer. For example, it shows the
name of the buffer, the line number at which the cursor is
currently present, etc. -
Scroll bar: On a graphicaly display, a scroll bar is displayed
on one side which can be used to scroll through the buffer.
There are many other peculiar terms found in the world of Emacs such
as the term point to refer to the current location of the cursor,
the term kill to cut text, the term yank to paste text, etc. but
we will not discuss them here for the sake of brevity. The meanings of
most such terms become obvious from the context when you encounter
them. The terms described above should be sufficient to understand the
line-by-line explanation presented in the next section.Line-by-Line Explanation
This section explains the
init.el
file provided here line-by-line.Tweak UI
The first few lines in our
init.el
merely tweak the Emacs user
interface. These are of course not essential for using Emacs. However,
many new Emacs users often ask how to customize the user interface to
add a good color scheme and make it look minimal, so this section
indulges a little in customizing the user interface.Here is a line-by-line explanation of the UI tweaks in
init.el
:-
When Emacs runs in a GUI window, by default, it starts with a menu
bar, tool bar, and scroll bar. Many (but not all) users like to
hide them in order to make the Emacs frame look clean and minimal.
The following lines disable the tool bar and scroll bar. The menu
bar is left enabled.(when (display-graphic-p) (tool-bar-mode 0) (scroll-bar-mode 0))
The
when
expression checks if Emacs is running with graphic
display before disabling the tool bar and scroll bar. Without the
when
expression, we get the following error on Emacs without
graphic display support:Symbol's function definition is void: tool-bar-mode
. An example of Emacs without graphics support is
emacs-nox
on Debian 10. Note that this is only an author’s
preference. You may comment out one or more of these lines if you
want to retain the tool bar or scroll bar.Some users like to hide the menu bar as well. To disable the menu
bar, include(menu-bar-mode 0)
as top-level-expression (i.e.,
outside thewhen
expression) in the initialization file. Even
with the menu bar disabled, the menu can be accessed anytime by
typing
. For beginners to Emacs, it is advisable to keep
the menu bar enabled because it helps in discovering new features. -
Inhibit the startup screen with the
Welcome to GNU Emacs
message
from appearing:(setq inhibit-startup-screen t)
If you are a beginner to Emacs, you might find the startup screen
helpful. It contains links to tutorial, manuals, common tasks, etc.
If you want to retain the startup screen, comment this line out. -
Show column number in the mode line:
By default, Emacs shows only the current line number in the mode
line. For example, by default, Emacs may display something like
L4
in the mode line to indicate that the cursor is on the fourth
line of the buffer. The above Emacs Lisp code enables column
number display in the mode line. With column number enabled, Emacs
may display something like(4,0)
to indicate the cursor is at
the beginning of the fourth line.
Customize Theme
In this section, we will choose a dark theme for Emacs. If you do not
like dark themes, you might want to stick with the default theme,
choose another theme, or skip this section.-
Load a beautiful dark color theme known as
wombat
:If you want to check the other built-in themes, type
M-x customize-themes RET
. A new window with a buffer named*Custom Themes*
appear. In this buffer, select any theme you want to
test. After you are done testing, you can close this new window
withC-x 0
.By default the Wombat theme looks like this:
In this theme, the cursor, search matches, and comments can often
be difficult to spot because they are all colored with different
shades of gray while the background is also gray. In the next few
points, we will customize this theme a little to make these
elements easier to spot. We color them differently to add more
contrast between the background and foreground colors of these
elements. In the end, our customized Wombat theme would look like
this: -
Choose a darker shade of gray for the background color to improve
the contrast of the theme:(set-face-background 'default "#111")
-
Choose a pale shade of orange for the cursor, so that it is easy
to spot on the dark gray background:(set-face-background 'cursor "#c96")
-
Highlight the current search match with a certain shade of orange
as the background and a very light shade of gray as the
foreground:(set-face-background 'isearch "#ff0") (set-face-foreground 'isearch "#000")
-
Highlight search matches other than the current one with a darker
shade of orange as the background and a darker shade of gray as
the foreground:(set-face-background 'lazy-highlight "#990") (set-face-foreground 'lazy-highlight "#000")
-
Use tangerine yellow to color the comments:
(set-face-foreground 'font-lock-comment-face "#fc0")
Personal note: I see that many recent color themes choose a dim color
for comments in code. Such color themes intend to underemphasize the
comments. I think comments play an important role in code meant to be
read by humans and should be emphasized appropriately. That’s why I
have chosen tangerine yellow for comments in the last point above, so
that the comments are easily readable.Minibuffer Completion
Emacs comes with Ido mode and Fido mode that help with opening files,
switching between buffers, entering commands, etc. quite efficiently.
Ido incrementally searches for file and buffer names as we type out
the names, list the matching names, and automatically completes the
minibuffer with the best match. Fido mode offers much of the same
functionality that Ido mode provides and additionally helps in
automatically completing inputs in all types of minibuffer prompts
(even those not related to files and buffers).Strictly speaking, it is not necessary to enable Ido mode if we are
going to enable Fido mode but both modes have their areas of
strengths, so we are going to enable both to get the best of both
modes.-
Enable Ido mode:
Note that the positive argument
1
is necessary. Without it, this
function call would simply toggle Ido mode on or off everytime it
executes. Say, we reload the Emacs initialization file withM-x load-file RET ~/emacs.d/init.el RET
, without the positive
argument, this function call would end up disabling Ido mode if it
was previously enabled. The positive argument ensures that Ido
mode remains enabled even if we reload the Emacs initialization
file.With Ido mode enabled, automatic completions appear while trying
to open files or switch between buffers withC-x C-f
orC-x b
,
respectively. For example, merely typingC-x C-f /et/ost
may
lead to Ido mode automatically completing the path to
/etc/hosts
, i.e., we may type partial substrings of the various
components of the path or a substring of the buffer name we want
to search and Ido mode would search the matching names and
automatically complete the minibuffer input. -
Enable Ido mode for all buffer/file reading:
Without this function call, Ido mode works for
C-x C-f
andC-x b
but not for other minibuffers that may involve entering file or
buffer names. For example, with this function call removed, if we
enterM-x ediff-files RET
, Ido mode does not perform completions
in theediff-files
minibuffer. But with this function call
present, Ido mode performs completions in theediff-files
minibuffer too. -
Enable flexible string matching for Ido mode:
(setq ido-enable-flex-matching t)
This variable setting allows flexible string matching while
searching files or buffers. For example, with this setting, if we
typeC-x C-f /ec/hst
, Ido mode may automatically complete the
file path to/etc/hosts
, i.e., Ido mode would automatically
complete names even if we omit a few characters while typing out
the name. Without this variable setting, the string we type must
always be a valid substring (with no characters omitted within the
substring) of the name we want to search. -
Perform automatic completions for all kinds of minibuffer inputs:
This mode allows us to perform automatic completions in all kinds
of minibuffer inputs, not just while finding files and buffers.
For example, typeM-x wspmod
and Fido mode should immediately
autocomplete the partial commandwspmod
towhitespace-mode
.
As explained at the beginning of this section, Ido mode is not really
necessary if we are going to enable Fido mode. But Ido mode has some
nice features for file name completion that Fido mode does not have.
That is why we enable both Ido mode and Fido mode in this section. For
example, Ido mode can search for visited subdirectories for file name
matches which can be quite convenient. Fido mode cannot do this.To test how Fido mode completes file names, first create a test
directory of files as follows:mkdir -p /tmp/a/b/; touch /tmp/a/b/foo.txt; touch /tmp/a/b/bar.txt
. Then comment out the
(ido-mode 1)
and(ido-everywhere)
lines in the Emacs
initialization file, save the file, and restart Emacs, so that Ido
mode is disabled and only Fido mode is enabled. Now typeC-x C-f /tmp/a/b/foo RET
. Then typeC-x C-f /tmp/bar
. Fido mode does not
automatically complete the partial input/tmp/bar
to
/tmp/a/b/bar.txt
.To test how Ido mode can be useful, now uncomment the
(ido-mode 1)
line in the Emacs initialization file, save the file, and restart
Emacs, so that Ido mode is enabled again. Now typeC-x C-f /tmp/a/b/foo.txt RET
. Then typeC-x C-f /tmp/bar
. Ido mode
automatically completes the partial input/tmp/bar
to
/tmp/a/b/bar.txt
. Once you are done experimenting like this,
remember to uncomment the(ido-everywhere)
line too in the end.Show Stray Whitespace
While writing text files, it can often be useful to quickly spot any
trailing whitespace at the end of lines or unnecessary trailing new
lines at the end of the file.-
Highlight trailing whitespace at the end of lines:
(setq-default show-trailing-whitespace t)
With this variable set, any stray trailing whitespace at the end
of lines is highlighted (usually with a red background) as shown
in the screenshot below:The screenshot above shows one stray trailing space in the second
line and two trailing spaces in the third line. These trailing
spaces can be removed with the key sequenceM-x delete-trailing-whitespace RET
. -
Show the end of buffer with a special glyph in the left fringe:
(setq-default indicate-empty-lines t)
Showing the end of the buffer conspicuously can be helpful to spot
any unnecessary blank lines at the end of a buffer. A blank line
is one that does not contain any character except the terminating
newline itself. Here is a screenshot that demonstrates this
feature:The screenshot shows that there are two blank lines just before
the end of the buffer. The tiny horizontal dashes on the left
fringe mark the end of the buffer. Note: This is similar to how
Vim displays the tilde symbol (~
) to show the end of the buffer.
The trailing blank lines at the end of a buffer can be removed
with the key sequenceM-x delete-trailing-whitespace RET
. -
Show buffer boundaries in the left fringe:
(setq-default indicate-buffer-boundaries 'left)
The buffer boundaries can be useful to check if the last line of
the buffer has a terminating newline or not. If the buffer does
not contain a terminating newline, then a top-right corner shape
(⌝
) appears in the fringe. For example, see this screenshot of a
file that does not contain a terminating newline:If there is only one line in the buffer and that line is
terminated with a newline then a left-bracket ([
) appears in the
fringe. If there are multiple lines in the buffer and the last
line is terminated with a newline then a bottom-left corner shape
(⌞
) appears in the fringe. Here is a screenshot of a file that
contains a terminating newline:To summarize, these shapes (
[
,⌞
, or⌝
) show where the last
newline of the buffer exists. The last newline of the buffer
exists above the lower horizontal bar of these shapes. No newlines
exist below the lower horizontal bar.
Require Final Newline
It is a good practice to terminate text files with a newline. For many
types of files, such as files with extensions.c
,.el
,.json
,
.lisp
,.org
,.py
,.txt
, etc., Emacs inserts a terminating
newline automatically when we save the file withC-x C-s
. Emacs
achieves this by ensuring that the major modes for these files set the
variablerequire-final-newline
tot
by default. However, there are
many other types of files, such as files with extensions.ini
,
.yaml
, etc. for which Emacs does not insert a terminating newline
automatically. We now see how to ensure that Emacs inserts a
terminating newline for all types of files.-
Always add a newline automatically at the end of a file while
saving:(setq-default require-final-newline t)
Many tools on Unix and Linux systems expect text files to be
terminated with a newline. For example, in a crontab entry, if the
final line is not followed by a terminating newline, it is ignored.
Similarly,wc -l
does not count the final line if it is not followed
by a terminating newline. That is why, in the above step we configure
Emacs to ensure that it always inserts a terminating newline before
saving a file.Single Space for Sentence Spacing
Emacs uses the rather old-fashioned convention of treating a period
followed by double spaces as end of sentence. However, it is more
common these days to end sentences with a period followed by a single
space.-
Let a sentence-terminating character (like a full stop, question
mark, etc.) followed by a single space be treated as end of
sentence:(setq sentence-end-double-space nil)
This little setting has significant consequences while editing and
moving around text files. We will discuss two such consequences
now with two tiny experiments:Experiment A: Moving By Sentences: To check the default
behaviour, first comment out the above line of Emacs Lisp code in
the Emacs initialization file, save the file, and restart Emacs.
Now copy the following text:Lorem ipsum dolor sit amet, consectetur adipiscing elit donec. Porttitor id lacus non consequat.
Then open a new text buffer in Emacs with
C-x C-f foo.txt RET
and paste the copied text withC-y
. Then typeC-a
to go to the
beginning of the line. Finally, typeM-e
to move to the end of
the sentence. Withoutsentence-end-double-space
set tonil
,
typingM-e
moves the cursor all the way to the end of the line
(i.e., after the
Leave a comment