100% found this document useful (2 votes)
389 views27 pages

Hacking Emacs

The document discusses customizing and enhancing the Emacs text editor. It describes installing packages, enabling package repositories, setting user details, and removing unnecessary UI elements from Emacs. Various tweaks and customizations are explained to improve Emacs functionality and usability.

Uploaded by

Jethro Kuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
100% found this document useful (2 votes)
389 views27 pages

Hacking Emacs

The document discusses customizing and enhancing the Emacs text editor. It describes installing packages, enabling package repositories, setting user details, and removing unnecessary UI elements from Emacs. Various tweaks and customizations are explained to improve Emacs functionality and usability.

Uploaded by

Jethro Kuan
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 27

Hacking Emacs

Jethro Kuan
August 8, 2016

Contents
1 Preface

2 Introduction
2.1 Installing Emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .
2.2 Terminology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

4
4
4

3 Taming the Beast


7
3.1 Customizing Emacs . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
3.2 Theming . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
4 Managing the Workspace
11
4.1 Winner-mode . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.2 WindMove . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
4.3 Ace-window . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
5 Thought-speed Motion
5.1 Moving Across Lines . . . .
5.2 Moving Within Visible Text
5.3 Moving Within the Buffer .
5.4 Registers . . . . . . . . . . .
5.5 Bookmarks . . . . . . . . .
5.6 Ivy, Counsel and Swiper . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

12
12
12
12
13
14
14

6 Thought-speed Editing
6.1 Moving Text Around
6.2 Selecting Regions . .
6.3 Zap-to-char . . . . .
6.4 Multiple-cursors . .
6.5 Templating . . . . .
6.6 Autocompletion . . .

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

.
.
.
.
.
.

16
16
17
18
19
19
19

7 Project Management
7.1 FFIP . . . . . . . .
7.2 Projectile . . . . .
7.3 Using Ag or Grep .
7.4 Magit . . . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

21
21
21
23
23

.
.
.
.

8 Icing on the Cake


8.1 golden-ratio . . . . .
8.2 aggressive-indent . .
8.3 which-key . . . . . .
8.4 volatile-highlights . .
8.5 firestarter . . . . . .
8.6 git-gutter+ . . . . .
8.7 Honourable Mentions

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

24
24
24
24
24
25
25
25

9 Miscellaneous Goodies
9.1 Minimizing Startup Time . . . .
9.2 Micro-optimizations with keyfreq
9.3 Remapping Capslock . . . . . . .
9.4 Ergonomic Keybindings . . . . .

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

.
.
.
.

26
26
27
27
27

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

.
.
.
.
.
.
.

1 Preface
Emacs is a nice operating system, but what it lacks, in order to compete with Linux,
is a good text editor. Thomer M. Gil

Today, you begin your journey with Emacs, the extensible, customizable, self-documenting real-time
display editor.
Because of its complexity, Emacs will seem difficult to grok. Rest assured that learning a select
few features and packages more than suffices. This material is titled Hacking Emacs, not only
because a great deal of customization will be made, but also because youll be learning packages
that have been handpicked, to greatly boost your productivity with the least amount of learning
time.
The tinkerer will marvel at the masterpiece which is Emacs. We hack on Emacs because we can;
every facet of Emacs is extensible and customizable. Emacs is not for the faint of heart. Embrace
the challenge, but most importantly enjoy the ride. I encourage you to be curious and playful
throughout this course.
Atom users, go grab yourselves another cup of coffee while you wait for it to load up :P.
Jethro Kuan

2 Introduction
2.1 Installing Emacs
If on a Linux distribution, Emacs should be available through your respective package managers.
For OSX users, I recommend Emacs for OSX.
Refer here if you have further doubts.
This course assumes a recent Emacs version (of version >24.0) has been installed. You can check
your Emacs version from the command line with emacs --version.

2.2 Terminology
2.2.1 Windows, Frames and Buffers
The text you are editing in Emacs resides in an object called the buffer.
A window is a container for a buffer. A window can contain one and only one buffer.
A frame is a container for windows. While inaccurate, one can think of it as the window configuration for Emacs.

Figure 1: A pictorial representation of windows, frames and buffers. In this picture, there are 1
frame, 3 windows and 3 buffers.

2.2.2 Killing, Yanking and the CUA


The table below shows analogous terminologies between Emacs clipboard system and modern standards:

Modern

Emacs

Cut
Paste
Copy

Kill
Yank
Save To Kill Ring

The Emacs terminology had been set in stone decades ago, long before the terms cut, copy and
paste (derived from the CUA, or Common User Access) were formed.
I will demonstrate in a later chapter why the Emacs way is better for text-editing.

2.2.3 Modes, Major Modes and Minor Modes


Major modes control how buffers behave. Each buffer will have one and only one major mode.
Most major modes tend to be language-specific. For example, when opening a Python file foo.py,
the central Emacs register will figure out that this file is a Python file and load the Python major
mode.
Major modes often offer the following functionality:
1. Font locking (aka syntax highlighting)
2. Indentation engines
3. Language-specific keybindings (for refactoring etc.)
In the scenario where the Emacs central registry for file extensions should fail to associate the file
with a major mode, Emacs will scan the first portion of the file and infer one.
Minor modes can be thought of as extensions, adding functionality to a buffer. These are optional,
and can be added locally on a per buffer basis, or globally affecting all buffers.
An example of a popular minor mode is the aggressive-indent mode, which keeps text in a buffer
properly indented at all times.

2.2.4 Modeline
The bottom bar in Emacs is called the modeline. Each window has a modeline, which presents
useful information about the buffer it displays. The first item in brackets is the major mode, and
the others are all minor modes.
Note that some minor modes can be configured to not appear on the modeline (a.k.a diminished).
To see the full list of modes activated, run M-x describe-mode, or C-h m.

Figure 2: A typical modeline for Emacs

2.2.5 Keybindings and Elisp Functions


Keybindings are combinations of keys that invoke functions when pressed. The origins of these
functions can be one of three: it could come out-of-the-box, be provided by an installed package,

or be self-written.
These functions are defined in a language called Emacs Lisp, also referred to in short as Elisp.
Emacs Lisp files have the file extension .el.
The full list of functions are browsable and invokable with M-x.

3 Taming the Beast


Vanilla Emacs works in a variety of unfortunate ways. These defaults have grown a resistance to
change over the decades.
We perform tweaking on Emacs minutiae, and simultaneously learn how Emacs is customized.

3.1 Customizing Emacs


During initialization, Emacs attempts to load an init file. This init file is an Emacs Lisp file, and
is processed top-down.
PROTIP: To load vanilla Emacs, run emacs with the command-line switch -q. This
will come in useful when your configuration file breaks.
Emacs searches for init files in several locations:
1. ~/.emacs
2. ~/.emacs.el
3. ~/.emacs.d/init.el
The 3rd option ~/.emacs.d/init.el is recommended. Having a dedicated folder for Emacs-related
configuration simplifies versioning.
If you havent done so, create a blank file init.el in ~/.emacs.d.
The tweaks are listed in order of importance. To enable them, copy them into the init.el file.

3.1.1 Enabling Package Archives


MELPA is the de-facto package archive for Emacs. Because it is not enabled by default, we add it
to the list of package-archives.
Similarly, we enable the Org-mode repository, which contains the most up-to-date version of orgwith-contrib.

1
2
3
4
5

(when (>= emacs-major-version 24)


(require 'package)
(add-to-list 'package-archives '("melpa" . "http://melpa.org/packages/") t)
(add-to-list 'package-archives '("org" . "http://orgmode.org/elpa/") t)
(package-initialize))
The more security conscious will note that packages are fetched using HTTP, instead of HTTPS.
HTTPS, however, did not work for me. Refer here for the reasons why you might want to do so,
and how to do it.

3.1.2 Setting User Details


These variables are used in some parts of Emacs, such as email.

1
2

(setq user-full-name "John Appleseed"


user-mail-address "john@me.com")

3.1.3 UI Cruft
All these UI cruft take up precious screen estate, and should be removed.

1
2
3
4
5
6

(tooltip-mode -1)
(tool-bar-mode -1)
(menu-bar-mode -1)
(scroll-bar-mode -1)
(setq inhibit-splash-screen t)
(setq inhibit-startup-message t)

3.1.4 Use-package
use-package is a macro which allows you to isolate package configuration in an organized and
performant fashion. It was created by John Wiegley, the current Emacs maintainer.

1
2
3

(unless (package-installed-p 'use-package)


(package-refresh-contents)
(package-install 'use-package))

4
5
6
7
8
9
10
11

(eval-and-compile
(defvar use-package-verbose t)
(require 'cl)
(require 'use-package)
(require 'bind-key)
(require 'diminish)
(setq use-package-always-ensure t))
Here, we set use-package-always-ensure to true, so if a package is found missing, it will be
installed automatically.

3.1.5 y/n
It is easier to type y/n than to type yes/no.

(defalias 'yes-or-no-p 'y-or-n-p)

3.1.6 Custom Files


Emacs comes with a built-in interface to customize all parts of Emacs. To persist the changes
youve made, Emacs saves them (by default) into your init.el file, which can cause it to grow out
of control.
I like to keep such customizations saved in a separate file.

1
2

(setq custom-file "~/.emacs.d/custom.el")


(load custom-file)
Try to put this at the bottom of your init.el file, so it overrides any configuration you might have
added in your init.el file.

3.1.7 Backup Files


Backup files are important, but they litter your directories with temporary files. I movs the temp
files to the system temp directory.

1
2
3
4

(setq backup-directory-alist
`((".*" . ,temporary-file-directory)))
(setq auto-save-file-name-transforms
`((".*" ,temporary-file-directory t)))
When added to your init.el, Emacs will scan the temp directory and purge old backup files on
startup.

1
2
3
4
5
6
7
8

(let ((week (* 60 60 24 7))


(current (float-time (current-time))))
(dolist (file (directory-files temporary-file-directory t))
(when (and (backup-file-name-p file)
(> (- current (float-time (fifth (file-attributes file))))
week))
(message "%s" file)
(delete-file file))))

3.1.8 Overwriting Text (Optional)


Im used to having text being overwritten when highlighted. These always saves me a few keystrokes.

(delete-selection-mode +1)

3.1.9 Default Font (Optional)


Because I love Fira Code.

1
2

(add-to-list 'default-frame-alist
'(font . "Fira Code-12"))

3.1.10 Tabs vs Spaces (Optional)


Im a fan of the 2 spaces rule.

1
2

(setq-default tab-width 2)
(setq-default indent-tabs-mode nil)

3.2 Theming
There are a myriad of themes available for your picking. Here I list the better ones:
1.
2.
3.
4.
5.
6.

Zenburn
Solarized
Leuven (has an impressive org-mode theme)
Monokai
Tomorrow by Sanityinc
Darkorai

Im currently using tao, a monochrome theme, with personal customizations for org-mode.
To enable a theme, find the relevant name of the theme on MELPA and add in the following snippet
of code:

1
2
3

(use-package tao-theme
:init
(load-theme 'tao-yang t))
At this point you should have quite a hefty amount of modification done. Remember to save your
configuration directory into version control.

4 Managing the Workspace


Its common to want to create new windows in your Emacs frame to maximize screen estate and
make editing easier.
Key
C-x
C-x
C-x
C-x

Window
0
1
2
3

Delete current window


Maximize current window
Split current window horizontally
Split current window vertically

4.1 Winner-mode
Winner-mode is a global minor mode. When activated, it allows you to undo and redo changes
in the window configuration.
Key

Action

C-c left
C-c right

winner-undo
winner-redo

The keybinding for switching between windows is C-x o, which I find overly complex for such an
essential key.

4.2 WindMove
WindMove is a library included in Emacs starting with version 21. It lets you switch between
windows using Shift + arrow keys. To activate it on startup, add the following piece of code in
your init.el.

1
2

(when (fboundp 'windmove-default-keybindings)


(windmove-default-keybindings))

4.3 Ace-window
ace-window lets you quickly switch between windows. Its the one Im currently using, and Im
very happy with it.

1
2

(use-package ace-window
:bind (("M-q" . ace-window)))
Id bind it to M-q, or anything else you find convenient.

5 Thought-speed Motion
With a more usable Emacs configuration, well begin navigating around Emacs, installing helper
libraries where relevant.
I recommend printing this refcard, and refer to it when necessary.
The first rule to moving around quickly is to never leave the keyboard. This concept is pervalent
across all efficient text editors, be it Vim or Emacs. In Emacs, key combinations are the gateway
to text-editing nirvana.

5.1 Moving Across Lines


The most common line-movement operations are listed below.
Key

Movement

Emacs Function

C-e
C-a
M-m

End of line
Start of line
first non-whitespace of line

(end-of-line)
(beginning-of-line)
(back-to-indentation)

PROTIP: To check what a key combination is bound to, press C-h k kbd. Alternatively, M-x describe-keybindings lists all defined keys and their definitions in order
of precedence.

5.2 Moving Within Visible Text


avy is a package for jumping to visible text using a char-based decision tree.
keystrokes, youre able to get to any visible point in the buffer.

1
2
3

Within three

(use-package avy
:bind* (("C-'" . avy-goto-char)
("C-," . avy-goto-char-2)))
PROTIP: To jump back to your previous location, use C-u C-space.

5.3 Moving Within the Buffer


5.3.1 isearch
isearch is short for incremental search. On several occasions you find yourself wanting to move to a
different location of the document, knowing the textual content in the area. You can move to the
location using the isearch, bound to C-s. To move to the next matching search result, press C-s
again. The search can also be performed in the reverse direction, and this is bound to C-r.

5.3.2 moccur
moccur is short for multi-occur. Some find this useful, but I personally feel like Swiper (introduced
below) is sufficient for my day to day operations. The key benefit of moccur is that a buffer for
search result matches is created, and this can be used to move to the matched locations again.

5.3.3 imenu
imenu is short for interactive menu. Imenu offers a way to find the major definitions in a file by
name. For example, in an Emacs Lisp (.el) file, you can navigate around with imenu to variables,
and function definitions. In org-mode, you can navigate to title headers with imenu. Because of its
utility, I bind it to M-i.

(bind-key* "M-i" imenu)


To use bind-key, you need use-package installed. Skip this step if you intend to install counsel,
described below.

5.4 Registers
NOTE: Before I begin, note that while I introduce registers here, registers are not just
for moving around the buffer.
Registers are compartments where text, rectangles, positions, window configurations and many
more can be stored. Think of it as a temporal bookmarking system; these registers get wiped at
the end of the Emacs process. Each register is denoted by a single character (eg. ?r or ?1). The
register ?a is different from the register ?A.
Whatever you store inside a register persists until it is overwritten by something else, or until the
Emacs process is killed.
Store a file in a register is simple:

(set-register r '(file . name))


Do this for all your bookmarks, and you can quickly jump to them with C-x r reg.
To make things simpler, bind jump-to-register to a more accessible key:

(bind-key* "C-o" 'jump-to-register)


Putting these in your init.el file ensures that they will always be available. I encourage you to
play around with the other forms of registers.

5.5 Bookmarks
Bookmarks are similar to registers, but they are persisted in a file.
To create a bookmark, type C-x r m bookmark-name. Similarly, bind bookmark-jump to a more
accessible key:

(bind-key* "C-o" 'bookmark-jump)


To change the file in which you store your bookmarks, invoke M-x customize-variable book
mark-default-file.

5.6 Ivy, Counsel and Swiper


Ivy is a generic completion mechanism for Emacs. It aims to be smaller, simpler and more highly
customizable.
Counsel provides a collection of Ivy-enhanced versions of command Emacs commands, including
find-file, describe-function and M-x.
Swiper, the ivy-enhanced version of isearch.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28

(use-package counsel)
(use-package swiper
:bind*
(("C-s" . swiper)
("C-c C-r" . ivy-resume)
("M-a" . counsel-M-x)
("C-x C-f" . counsel-find-file)
("C-c h f" . counsel-describe-function)
("C-c h v" . counsel-describe-variable)
("C-c i u" . counsel-unicode-char)
("M-i" . counsel-imenu)
("C-c g" . counsel-git)
("C-c j" . counsel-git-grep)
("C-c k" . counsel-ag)
("C-c l" . counsel-locate))
:config
(progn
(ivy-mode 1)
(setq ivy-use-virtual-buffers t)
(define-key read-expression-map (kbd "C-r") #'counsel-expression-history)
(ivy-set-actions
'counsel-find-file
'(("d" (lambda (x) (delete-file (expand-file-name x)))
"delete"
)))
(ivy-set-actions
'ivy-switch-buffer
'(("k"

29
30
31
32
33
34
35

(lambda (x)
(kill-buffer x)
(ivy--reset-state ivy-last))
"kill")
("j"
ivy--switch-buffer-other-window-action
"other window")))))
For a powerful preconfigured alternative, consider helm and its companion tutorial here. For
something like Swiper, look at helm-swoop.
For a simpler in-built alternative, look at ido-mode, Mickey Petersen has a great write-up about
it here.

6 Thought-speed Editing
6.1 Moving Text Around
Earlier, I introduced the terminology Emacs uses for its clipboard system. I missed one vital piece,
because I felt it was more appropriate to introduce here to keep things fresh.
Text that gets killed is erased, and then stored inside the kill ring. This stored text is then
retrievable by yanking. There is only one kill ring, global to Emacs.
A clear distinction has to be made between killing and deleting. Deleting text removes it from
the buffer, but does not store it in the kill ring. Therefore extra caution has to be made when
performing deletions.

6.1.1 Deleting Text


Here are the more useful text deletion commands:
Key

Action

Function

M-\
M-SPC

Delete spaces and tabs around point


Delete spaces and tabs around
point, leaving one space
Delete blank lines around current
line
Join two lines by deleting intervening newline, along with indentation

(delete-horizontal-space)
(just-one-space)

C-x C-o
M-^

(delete-blank-lines)
(delete-indentation)

6.1.2 Killing Text


Here are the more useful text killing commands:
Key

Action

Function

C-k
C-w
C-x DEL
M-k

Kill
Kill
Kill
Kill

(kill-line)
(kill-region)
(backward-kill-sentence)
(kill-sentence)

line
region
back to beginning of sentence
to end of sentence

NOTE: By default, a sentence is delimited by a period, followed by two spaces. This is


so that Emacs can differentiate between abbrieviations (M. J. for example), and actual
sentences. It is recommended that you follow the two space convention, but if you insist,
(setq sentence-end-double-space nil) should do the trick.

6.1.3 Yanking Text


Here are the more useful text killing commands:

Key

Action

Function

C-y
M-y
M-w
C-M-w

Yank last killed text


Replace last killed text with an earlier batch of killed text
Save region as last killed text without performing the kill
Append next kill to last batch of killed text

(yank)
(yank-pop)
(kill-ring-save)
(append-next-kill)

You can think of the kill ring as a stack, so you could continuously pop the kill ring to obtain earlier
batches of killed text.

6.1.4 browse-kill-ring
I often defer to browse-kill-ring to access my kill-ring history. I bind it to M-y, replacing (yankpop). Try it out, and see if it suits your workflow.

1
2

(use-package browse-kill-ring
:bind ("M-y" . browse-kill-ring))

6.2 Selecting Regions


6.2.1 The Mark, the Point and the Region
Many Emacs commands operate on an arbituary, contiguous part of the buffer, also known as the
region. A region is delimited by two objects: the mark and the point.
The point is where your cursor (keyboard) is currently placed. C-SPC creates a mark at the current
position of point, activating it, as well as activating the region. The region is the text between the
point and the mark, regardless of which direction. To deactivate the mark, simply quit with C-g.
Some common region commands include kill-region.

6.2.2 Rectangular Region


Rectangle commands operate on retangular areas of text. This may seem rather esoteric, but it
occasionally presents itself as the correct tool.
C-x SPC creates a rectangular mark. The following presents commonly used rectangular commands,
all prefixed with C-x r, operate on rectangular regions:
(Region-rectangle is short-formed as RR)

Key

Action

Function

C-x r k

Kill text in RR, saving its contents into


last-killed rectangle
Save text in RR into kill-ring
Delete text in RR
Yank last killed rectangle
Clear RR, replacing all text with spaces
Replace rectangle contents with string on
each line

(kill-rectangle)

C-x
C-x
C-x
C-x
C-x

r
r
r
r
r

M-w
d
y
c
t string RET

(copy-rectangle-as-kill)
(delete-rectangle)
(yank-rectangle)
(clear-rectangle)
(string-rectangle)

6.2.3 Expand Region


expand-region is one of those packages that you can live without, but as you use it more often, you
find yourself repeatedly going back to it. Heres a great overview of expand-region.

1
2

(use-package expand-region
:bind (("C-=" . er/expand-region)))

6.3 Zap-to-char
As an ex-vim user, I miss the ct and dt key dearly. Fret not, for what vim can do, emacs can do
better.
zap-up-to-char does exactly what it says it does: it kills up to, but not including the ARGth
occurrence of CHAR.

1
2
3

(autoload 'zap-up-to-char "misc"


"Kill up to, but not including ARGth occurrence of CHAR."
'interactive)

4
5

(bind-key* "M-z" 'zap-up-to-char)


Lets play with some examples:
I think I love to eat pancakes and bananas.
We begin from the start of the sentence. Now lets say we want to kill up to think, Id do M-z t
RET. If I wanted to kill up to to, then I provide an argument value of 2 to zap-up-to-char by
pressing M-2 M-z t RET.
Remember that the text is killed, which means it gets saved into the kill ring and can be retrieved
at a later point in time through yanking.
If you use avy, perhaps youll find zzz-to-char to your liking. It uses the avy interface to select
which letter to zap up till.

(use-package zzz-to-char

:bind (("M-z" . zzz-up-to-char)))

6.4 Multiple-cursors
Multiple cursors would be familiar functionality to Sublime Text users. Its the perfect tool for
many things, including editing variable names with visual feedback.

1
2
3
4

(use-package multiple-cursors
:bind (("C->" . mc/mark-next-like-this)
("C-<" . mc/mark-previous-like-this)
("C-c C-<" . mc/mark-all-like-this)))
I use it in conjunction with expand-region: expand-region to select the keyword (variable names,
for example), and use C-c C-< to select all instances of the variable, and simply type over it.

6.5 Templating
yasnippet is a templating system, allowing you to type an abbrieviation and automatically expand
it into function templates with <TAB>. This feature is similar to the one offered by Textmate; in
fact, the templating language is inherited from it.

1
2
3
4
5

(use-package yasnippet
:diminish yas-global-mode yas-minor-mode
:defer 5
:init (add-hook 'after-init-hook 'yas-global-mode)
:config (setq yas-snippet-dirs '("~/.emacs.d/snippets/")))
Andrea Crotti maintains an official repo for yasnippet templates. It supports many languages and
major-modes. I recommend forking the repository as I did and cloning it as a git submodule
under ~/.emacs.d: this way you can add your own templates and version control them. I had set
the yas-snippet-dirs to ~/.emacs.d/snippets, so following that configuration:

git submodule add git@github.com:foobar/snippets.git ~/.emacs.d/snippets

6.6 Autocompletion
Text completion in Emacs has Emacs users split between two major factions: autocomplete and
company-mode. Both have similar feature sets, but it is generally argued that company-mode is
more feature-rich.
The following snippet installs company-mode.

1
2

(use-package company
:defer 5

3
4
5
6
7
8
9
10
11
12
13

:diminish company-mode
:init (progn
(add-hook 'after-init-hook 'global-company-mode)
(setq company-dabbrev-ignore-case nil
company-dabbrev-code-ignore-case nil
company-dabbrev-downcase nil
company-idle-delay 0
company-begin-commands '(self-insert-command)
company-transformers '(company-sort-by-occurrence))
(use-package company-quickhelp
:config (company-quickhelp-mode 1))))
One thing that people miss from autocomplete is documentation popups. We add that functionality
with company-quickhelp. Another notable setting made was to set the delay for autocomplete to
0. Play around with the numbers and see what youre comfortable with.
Note that company-mode is merely a framework for autocompletion. To enable autocompletion for
various languages, youd need to install various company backends.

7 Project Management
In most cases, your work is not limited to a single file. Instead, its comprised of multiple files
residing in a parent directory, or perhaps even version-controlled with Git or the likes.
While Emacs does not ship with project management tooling, there are a few quality libraries that
help you with that.

7.1 FFIP
find-file-in-project, or ffip in short, provides quick access to files in a directory managed by versioncontrol (git/svn/mercurial). Its intentionally kept simple. It uses GNU find under the hood, which
makes it suitable even for large codebases. The default interface has been recently changed to ivy
(introduced earlier). Look no further than ffip for a simple project-management tool.

1
2
3
4

(use-package find-file-in-project
:bind (("s-f" . find-file-in-project)
("s-F". find-file-in-current-directory)
("M-s-f" . find-file-in-project-by-selected)))
The functions are so useful they deserve a short keybinding: s-f is what Id go with.

7.2 Projectile
Projectile is a different beast, leveraging a variety of tools to be a performant project interaction
library. While ffip aims to be a minimalistic and fast file-switcher for projects, projectile aims to
be the all-encompassing project-management tool. It has certainly proved to be the only one youll
need.
Here are some handpicked features Projectile has to offer, as seen on the Github page:

jump to a file in project


jump to files at point in project
jump to a project buffer
jump to a test in project
toggle between files with same names but different extensions (e.g. .h <-> .c/.cpp, Gemfile
<-> Gemfile.lock)
toggle between code and its test (e.g. main.service.js <-> main.service.spec.js)
switch between projects you have worked on
replace in project
regenerate project etags or gtags (requires ggtags).
run make in a project with a single key chord

I bind the projectile keymap to C-x p. If you use ivy, set the projectile-completion-system to
ivy, and install counsel-projectile, which adds more ivy-friendly functions for projectile.

1
2
3

(use-package projectile
:demand t
:init (projectile-global-mode 1)

4
5
6
7
8
9
10
11
12

:bind-keymap* ("C-x p" . projectile-command-map)


:config
(require 'projectile)
(use-package counsel-projectile
:bind (("s-p" . counsel-projectile)
("s-f" . counsel-projectile-find-file)
("s-b" . counsel-projectile-switch-to-buffer)))
(setq projectile-use-git-grep t)
(setq projectile-completion-system 'ivy))
Projectile also has a little known feature: projectile-commander. The default action upon switching projects is find-file, and that might not be desirable. Give yourself a choice between doing
a find-file, a git-fetch, or even language specific things like starting a REPL.
First, set the projectile to utilize projectile-commander:

(setq projectile-switch-project-action #'projectile-commander)


Next, define the methods you want:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31

(def-projectile-commander-method ?s
"Open a *eshell* buffer for the project."
(projectile-run-eshell))
(def-projectile-commander-method ?c
"Run `compile' in the project."
(projectile-compile-project nil))
(def-projectile-commander-method ?\C-?
"Go back to project selection."
(projectile-switch-project))
(def-projectile-commander-method ?d
"Open project root in dired."
(projectile-dired))
(def-projectile-commander-method ?F
"Git fetch."
(magit-status)
(call-interactively #'magit-fetch-current))
(def-projectile-commander-method ?j
"Jack-in."
(let* ((opts (projectile-current-project-files))
(file (ido-completing-read
"Find file: "
opts
nil nil nil nil
(car (cl-member-if
(lambda (f)
(string-match "core\\.clj\\'" f))
opts)))))
(find-file (expand-file-name
file (projectile-project-root)))
(run-hooks 'projectile-find-file-hook)
(cider-jack-in))))

Append all these code into :config for the projectile package.

7.3 Using Ag or Grep


Projectile ships with functions that make use of grep and ag. Grep and Ag are both command-line
tools used for searching code. You use projectile-ag (C-x p s s) or projectile-grep (C-x
p s g) to perform a project-scoped search, and use the search results to navigate to the relevant
locations. Ag is more performant, but does not come installed with most systems. In most cases,
grep is sufficiently fast.
Alternatively, if you had installed counsel by following the instructions here, youd have access to
the function, counsel-ag, counsel-git, and counsel-git-grep. counsel-git-grep (C-c j) is
especially great for projects, because it prunes out files captured by .gitignore.

7.4 Magit
Magit is an interface for Git. It is an absolute joy to use, and is one of the main reasons I stuck
with Emacs after a period with Vim.

1
2
3
4
5

(use-package magit
:bind (("C-x g" . magit-status)
("C-x M-g" . magit-blame))
:init (setq magit-auto-revert-mode nil)
:config (add-hook 'magit-mode-hook 'hl-line-mode))
Surely you can figure out the basics like adding remotes, fetching, and committing with such a
simplified interface. Heres a great tutorial on how to perform rebases, squashes and the like easily
with Magit.

8 Icing on the Cake


Here I introduce packages Ive installed that are not a must, but are definitely nice to have.

8.1

golden-ratio

Give the window youre working in more screen estate.

1
2
3
4
5

(use-package golden-ratio
:diminish golden-ratio-mode
:config (progn
;;(add-to-list 'golden-ratio-extra-commands 'ace-window)
(golden-ratio-mode 1)))
If youre using ace-window, uncomment the line for golden-ratio to function properly.

8.2

aggressive-indent

Keep your code nicely aligned while you hack away at more important stuff. Remember to disable
this for languages that depend on indentation for syntax, like Python.

1
2
3

(use-package aggressive-indent
:diminish aggressive-indent-mode
:config (add-hook 'prog-mode-hook 'aggressive-indent-mode))

8.3

which-key

Which-key is a godsend when youre first starting out using Emacs. I still refer to the list of
keybindings it shows from time to time.

1
2
3

(use-package which-key
:diminish which-key-mode
:config (add-hook 'after-init-hook 'which-key-mode))

8.4

volatile-highlights

Volatile-highlights provides visual feedback for operations such as yanking by highlighting the
relevant regions.

1
2
3

(use-package volatile-highlights
:diminish volatile-highlights-mode
:config (volatile-highlights-mode t))

8.5

firestarter

firestarter lets you execute commands (including shell commands) on save. Example use cases
include compiling SASS files, and compiling a program.

1
2
3

(use-package firestarter
:bind ("C-c m s" . firestarter-mode)
:init (put 'firestarter 'safe-local-variable 'identity))

8.6

git-gutter+

I use git-gutter+ primarily for showing on the left side what parts of my files have changed. It also
has additional features like staging hunks for commits, but I use Magit for that. You can take a
look at the Github page for more details.

1
2
3
4
5
6
7
8

(use-package git-gutter+
:init (global-git-gutter+-mode)
:diminish git-gutter+-mode
:defer 5
:config (progn
(setq git-gutter+-modified-sign "==")
(setq git-gutter+-added-sign "++")
(setq git-gutter+-deleted-sign "--")))

8.7 Honourable Mentions


1. hydra
2. electric-align

9 Miscellaneous Goodies
9.1 Minimizing Startup Time
9.1.1 Emacs Daemon
One way to avoid all perceived boot time, is to start emacs during the system boot as a daemon.
This is the option I have gone with.
All you need to do add the Emacs daemon to auto-start:

emacs --daemon
I use systemd instead. For this option, create a user systemd service file with the following content:
To enable the service on startup, just do systemd enable --user emacsd.service.

9.1.2 Profiling with esup


Esup can perform a profile of your current configuration. Esup is obtainable over MELPA, so go
ahead and use use-package like we normally do:

1
2

(use-package esup
:defer t)
Next, just execute esup with M-x esup. A separate emacs process will start, and the profiling
results will be returned in a separate window, which would look like this:

Figure 3: esup profiling results


You can take note of the packages that take the longest amount of time to initialize, and weigh
their alternatives. For example, I might contemplate removing git-gutter+ or replacing it with a
more lightweight alternative.

9.2 Micro-optimizations with keyfreq


Once youve determined your Emacs style, you begin to use the same keybindings again and again.
Understanding which functions are invoked most often, allows you to optimize your workflow by
binding them to shorter, more accessible key combinations.
keyfreq monitors your keypresses during daily Emacs usage.

1
2
3
4

(use-package keyfreq
:config
(keyfreq-mode 1)
(keyfreq-autosave-mode 1))
After a period of Emacs usage, run M-x keyfreq-show. Perform micro-optimizations based on the
results. After which, M-x keyfreq-reset to rinse and repeat.

9.3 Remapping Capslock


Without doubt, the capslock key is one of the most underused keys (that is if youre normal). Do
yourself a favour and remap it to something more useful I recommend the elusive Ctrl key. On
the Mac, you can remap it in the keyboard preferences pane.

9.4 Ergonomic Keybindings


Anyone who spends enough time at the keyboard is at risk of repetitive strain injury, or RSI. Spend
some time reflecting on how often you stretch out your pinky or move your thumb into awkward
positions to press a key.

9.4.1 M-x
Lets face it. M-x is actually pretty damn hard to hit. x is highly inaccessible, not even on alternative
keyboard layouts like Dvorak.
In prelude, M-x is bound to C-x C-m. I bind M-x to M-a, which is originally bound to backwardsentence, which I dont use much at all. Both are viable options.

9.4.2 ergoemacs
ergoemacs was developed to bring familiar keys to Emacs, as well as to reduce risk of RSI. While
you could follow the instructions on the webpage to have it installed, I recommend studying their
keybindings and adopting the ones you think youll like.

You might also like

pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy