Emacs Workout

C-x r

I wrote in this post on Evil Emacs about some of the things that vi does well. One feature I particularly like is the ability to store a mark in a register q using the key combination mq. You can then jump back to that point using `q

Compare that with the equivalent Emacs key combinations: C-x r <space> q to store a point in a register, and C-x r j q to jump back.

There are lots of useful, and by me at least, underused Emacs features that begin with C-x r

A handy trick to see them is all to enter

C-x r C-h
which opens a buffer listing all the commands beginning C-x r

Here are the four we’re interested in for the moment

C-x r space q         Store point in register q
C-x r j q               Jump to point stored in register q
C-x r s q               Store region in register q
C-x r i q              Insert text from register q

Could that key sequence be shortened? Well, here’s one way…

C-x r calls the ctl-x-r-map prefix keymap

Adding the following to your .emacs will save you a keystroke: now C-</strong> is the same as hitting <strong>C-x r</strong>.
<pre class="example">(global-set-key (kbd "C-
“) ctl-x-r-map)

Now the key combinations for storing points and regions are as follows

C-` space q        Store point in register q
C-` j q              Jump to point stored in register q
C-` s q              Store region in register q
C-` i q             Insert text from register q

Is it worth it? Well, it makes it easier for me to remember the key combinations, it also makes me more likely to use them. An added bonus is it also makes it easier to remember the rectangle commands.  See this post on rectangles for more details.

Incidentally, this saving of one keystroke and how it makes all the difference is what my wife calls this a Pierre Victoire event. You can see what she means here on my blog

Emacs Workout

Evil Emacs 1

There’s no denying that vi has a great set of keybindings. For pure editing rather than writing I’ll often use Evil mode – an extensible vi layer for Emacs (See below for installation). Vi key combinations are often easier on the fingers: hitting dd to kill a line is easier than C-S-Backspace any day. I also find navigating with hjkl preferable to C-p, C-f and so on.

That got me thinking. What is it about the vi commands that make them so good for editing? What’s more, as I edit in a different way using vi, can any of those methods make my Emacs use more efficient?

I took a break a moment ago to reflect on what I’d just written and came to the conclusion that I really am as boring as my wife keeps telling me. But what the heck. I find it fun, and the fact that you’re still reading shows that you think this is interesting too.

So here goes.

One vi feature I use a lot is f . to find the end of a sentence. Now I know that you can jump to the end of sentence using M-e, but this only works if there are two spaces after the full stop, and fewer and texts follow this convention nowadays.
You can replicate this in Emacs using C-s . The thing is, I never thought of doing that until I stopped to think about my vi habits. That led me to using M-z . to delete to the end of the sentence (this is similar to df . in vi).

I’ve written elsewhere about using C-s more often. The fastest way I know to jump to a word I can see on the page is to C-s (word).

Bearing that in mind, there’s a nice trick in vi where you c/pattern to clear up to a pattern. So if I wanted to clear all the words from here to this 34 I’d hit c/34
Thinking about that has led me to doing the following in Emacs

C-Space C-s 34 Enter C-w

In other words

C-Space to set the mark; C-s 34 to jump to 34 and then C-w to clear. More keystrokes, true, but you’re not constantly shifting between modes.

There are advantages to modes, of course. I love the fact that jumps back to the last edit in vi. You can partially replicate this in Emacs using C-Space C-Space to push a point to the mark ring, and then you can jump back using C-u C-Space. It’s not the same, but it will do.


(setq set-mark-command-repeat-pop 't)

in your .emacs file allows you to just keep hitting C-Space after that initial C-u C-Space. The mark ring is set to 16 by default. With this setting you can go round and round your last 16 marks as many times as you care to hit C-Space

Installing Evil

You can install Evil using the package manager. Placing the following in your .emacs file enables it by default, and replicates visual-line-mode type navigation.

(require 'evil)
(evil-mode 1)
(define-key evil-normal-state-map (kbd "<remap> <evil-next-line>") 'evil-next-visual-line)
(define-key evil-normal-state-map (kbd "<remap> <evil-previous-line>") 'evil-previous-visual-line)
(setq-default evil-cross-lines t)
Emacs Workout

Simple Version Control

About once every six months or so I spend the morning happily overwriting an existing piece of work. Either that or I unwittingly delete whole sections, only to discover my mistake later that day or worse, later that week or even month.

That’s were Emacs simple version control comes in handy. Add the following to your .emacs file: (courtesy of the Emacs Wiki)

(setq version-control t ;; Use version numbers for backups
       kept-new-versions 16 ;; Number of newest versions to keep
       kept-old-versions 2 ;; Number of oldest versions to keep
       delete-old-versions t ;; Ask to delete excess backup versions?
       backup-by-copying-when-linked t) ;; Copy linked files, don't rename.
 (defun force-backup-of-buffer ()
   (let ((buffer-backed-up nil))
 (add-hook 'before-save-hook  'force-backup-of-buffer)

You can probably deduce from the comments what the above does, but as an illustration, here’s a sample of what the file I’m currently writing looks like under version control:

-rw-rw-r--  1 XXXX XXXX 29816 Aug 11  2014
.rw-rw-r--  1 XXXX XXXX 29816 Aug 11  2014
-rw-rw-r--  1 XXXX XXXX 28844 Aug 11  2014
-rw-rw-r--  1 XXXX XXXX 29322 Aug 11  2014

The last 16 versions of the file are kept, the versions indicated by ~ ver ~
Having all of those versions can sometimes make it difficult to find files under dired. Fortunately, dired-x has a mode that omits uninteresting files. Add the following to .emacs

(require 'dired-x)
(setq dired-omit-mode t)

Now just hit C-x M-o (or M-o on older versions of Emacs) to omit those files.
16 past versions combined with my regular backup routine have proven enough for me to find the accidentally deleted text.  For a more in depth discussion  see

Emacs Workout


When writing a worksheet for students, I always include the answers, as follows:

Figure 1 shows the contents of a memory location
#+CAPTION: Figure 1
What is the denary equivalent of the contents of
this memory location if it represents an unsigned
binary integer? (1 mark)
ANS: 167
What is the denary equivalent of the contents of
this memory location if it represents an unsigned
binary fixed point number, with 4 bits before and
4 bits after the binary point? (2 marks)
ANS: 10.4375
What is the denary equivalent of the contents of
this memory location if it represents a two's
complement binary integer? (2 marks)
ANS: -89
What is the hexadecimalequivalent of the binary
pattern shown in Figure 1? (1 mark)

When I’ve finished I save a copy of the sheet and then remove the answers, leaving me with a worksheet and the answer sheet. Emacs makes it easy to remove the answers using

M-x flush-lines  ^ANS:

As it says in the documentation, flush-lines deletes lines containing matches for REGEXP.

Use flush-lines to delete blank lines as follows:

M-x flush-lines ^$

flush-lines is part of replace.el. There are some nice functions in replace.el As it says in the introductory comments:

This package supplies the string and regular-expression replace functions documented in the Emacs user’s manual.

M-x keep-lines is the inverse of flush-lines, handy if you want a sheet with the answers only

M-x how-many returns the number of occurrences of REGEXP following the point. Handy for counting how many ANS: there are.

M-x occur opens a buffer showing all lines in the current buffer containing a match for REGEXP.  See this post on stylesheets for more on this.

Lastly, map-query-replace-regexp will replace a matches for a regexp in rotation. As a simple example, suppose you want assign a group to a collection of students:

gp: Adam
gp: Bella
gp: Carol
gp: Danuta
gp: Ed
gp: Fran

Select the names and

red: blue: green:


red: Adam
blue: Bella
green: Carol
red: Danuta
blue: Ed
green: Fran

Related Posts

Emacs Workout


I never knew of the existence of stylesheets until the copyedit came back for my first novel. They struck me as such a good idea that ever since I’ve tried (and failed) to keep one up to date as I’m writing a novel.

The reason why they fail is that I change my mind as to what style to use as I’m writing. For example, I couldn’t decide whether the antagonists in DREAM PARIS were pierrots or Pierrots. In COSMOPOLITAN PREDATORS!, I couldn’t decide whether a character was named young man or Young Man.

I came about the solution by using the occur function.

M-x occur pierrot

occur lists lines containing a regexp in a separate buffer. Since Emacs regexps are case insensitive by default, the above finds both pierrot and Pierrot. It opens a buffer rather like the one in the self referential example below:

7 matches in 5 lines for "pierrot" in buffer:
     16:The reason why they fail is that I change my mind
     as to what style to use as I'm writing.  For
     example, I couldn't decide whether the antagonists
     in my most recently completed novel, DREAM PARIS
     were pierrots or Pierrots.  In COSMOPOLITAN
     PREDATORS!, I couldn't decide whether a character
     was named young man or Young Man.
     21:M-x occur pierrot
     24:Emacs regexps are case insensitive by
     default, so the above finds pierrot and Pierrot. It
     opens a buffer rather like the example below:
     31:M-s h l pierrot
     34:highlights lines with pierrot in.

Clicking or hitting enter on a line in the Occur buffer jumps you to the original location in the text.

A big advantage of occur is that you can look at the words in situ before deciding on the final style and running a query-replace-regexp to replace them all.

Another useful mode in when looking at styles is hi-lock mode.

M-s h l pierrot

The above highlights lines containing the regexp pierrot.

A really useful feature of hi-lock mode is that it highlights on the fly, highlighting lines as you type in the words. I use this feature to act as a reminder of whether I’m typing in the right (or wrong) style.

As a bonus, hi-lock mode allows you to choose from a pallete of colours. Use M-n and M-p to scroll through the choices, or enter your own choice – very useful when tracking more than one style.

Emacs Workout

fill-paragraph and visual-line-mode

I’ve got so used to using visual-line-mode in Emacs that I sometimes need reminding there are other ways of setting out work.  Well, that’s what the Emacs Work-Out is all about…

visual-line-mode wraps words at the boundaries of the editor, rather like a word processor does. This can sometimes be a nuisance, particularly when embedding source code in documents.

One solution is to go back to using fill-paragraph. I’m going to set the fill column to 50, for no good reason.

C-x f 50        Set fill column to 50
Now write or copy some text into Emacs.  I'm going
to use this paragraph.  When I finish typing this
sentence I hit M-q right about now...

..and the paragraph is automatically wrapped at the extent of the fill column. You’ll notice I didn’t hit M-q for this paragraph.

What about all those extra carriage returns that get added? Well, if they bother you that much you can use this function and key definition written by Stefan Monnier to unfill-paragraphs.

The chances are, however you won’t need it very often. Most of the stuff I write is exported using org-export before it’s published (see My Emacs Writing Setup for more details)

Export ignores single returns so


becomes a b c on export. In other words, filled paragraphs are exported as, well, paragraphs.

If you can’t be bothered hitting M-q all the time, try setting auto-fill-mode or refill-mode.

Don’t forget you can use whitespace-mode to see non-printing characters and get a better idea of what’s going on.

M-x refill-mode
M-x whitespace-mode
Fill prefixes are an old fashioned method of
;; writing comments in code.  I've set a fill
;; prefix of ;; on this paragraph and hit M-q.
;; Note how the first line isn't prefixed
C-x .      Set fill prefix as text up to the point.
C-o        Add fill prefix to line

Lastly, you can left, right, fully and centre justify paragraphs, rather like this, if you really see the need.

M-x set-justification-full
M-x set-justification-left
M-x set-justification-center
M-x set-justification-right
M-x set-justification-none
Emacs Workout


Sacha Chua writes here about developing microhabits. It’s an article close to my heart, in fact, it’s the reason that I write the Emacs workout. Sacha’s article was inspired in turn by this tweet from Frederik Appelburg

Using transpose-chars is a litmus test. If you care enough to save keystrokes to internalize C-t, then you must be a power user.

I agree with Frederik: I use C-t all the time for that very reason (in fact I’ve written elsewhere that my litmus test is do you use M-c to capitalise words?).
But Frederik got me thinking about M-t. How often do I have to transpose a word?

Transpose two lines, yes, transpose a sentence. Well, when I’m editing stories, I do this a lot. But I rarely find myself transposing words.
Emacs has five built in transpose commands:

C-t transpose-chars Transpose the two letters.
M-t transpose-words Switch two words.
C-x C-t transpose-lines Switch two lines.
transpose-sentences Switch two sentences.
transpose-paragraphs Switch two paragraphs.

The trouble is, there is no key binding for the last two, the ones I’m most likely to use. Well, Emacs was made to be customised, it says so in the name. I could have added a couple of extra key bindings, but for various reasons I chose to use aliases, and so I added the following code to my .emacs file.

1 (defalias 'ts 'transpose-sentences)
2 (defalias 'tp 'transpose-paragraphs)

Now I just move the cursor between two sentences or paragraph, hit M-x ts or M-x tp and that’s it.

It’s such a simple customisation, and one I should have done years ago. But there you go: you have to work hard to be lazy.

Emacs Lisp Emacs Setup Emacs Windows

Only One .emacs

I keep my Emacs init files on Dropbox – that way I only have to maintain one set of files no matter how many machines I run Emacs on. My local .emacs file simply loads the init files on Dropbox.

One minor problem is that Dropbox can have a different path according to the operating system.

This is easily resolved using the system-type variable. For my set up, I’m only interested in whether I’m running on a ‘gnu/linux or a ‘windows-nt system.
The following code sets the path of my Dropbox folder and then uses the format function to append the appropriate init files to that location. The individual files are then loaded. I’ve split my .emacs file across several files for tidiness and convenience. Even so, it still manages to degenerate into a mess when I’m not watching it.

1: (if (eq system-type 'windows-nt)
2:     (setq dot-emacs-files "c:/Users/username/Dropbox/emacs")
3:   (setq dot-emacs-files  "~/Dropbox/emacs")
4: )
6: (load (format "%s/%s" dot-emacs-files "packages-dot-emacs.el"))
7: (load (format "%s/%s" dot-emacs-files "org-dot-emacs.el"))
8: (load (format "%s/%s" dot-emacs-files "common-dot-emacs.el"))
9: (load (format "%s/%s" dot-emacs-files "elisp.el"))
Emacs Workout

YASnippet and Babel

Org-mode allows you to use Babel. As it says in the manual:
Babel is Org-mode’s ability to execute source code within Org-mode documents

Here’s a bit of Java, wrapped up in Babel

#+BEGIN_SRC java :classname example
    public class example
            public static void main (String args [])
                System.out.println("Go Babel!");

Put the point in the block and

C-c '      to edit the code
C-c C-c     to run the code

In the past, I never used Babel as often as I should, mainly because I could never quite remember the syntax.

Then I had the idea of adding Babel to YASnippet.  I added the following to my org-mode snippets:

# -*- mode: snippet -*-
# name: jbabel
# key: jbabel
# --
#+BEGIN_SRC java :classname $1
    public class $1
            public static void main (String args [])

… and now I just have to type jbabel and hit tab to have my Babel block ready to go.

It works with ditaa too. As I could never quite remember all the codes when I needed them, I just put a few of ones I used most frequently in a YASnippet example:

# -*- mode: snippet -*-
# name: ditaa babel
# key: dbabel
# --
#+begin_src ditaa :file $1.png
| Things to do    |        +-----+
| cGRE            |    |{s}  |
| o Cut the grass *-+----->|     |
| o Buy jam       |    |     |
| o Fix car       |    +-----+
| o Make website  |

And here’s what it looks like when converted (if you’re reading this on Google+, you might want to head over to my website: to see the image)

Emacs Workout

Deleting Whitespace

A whole workout on deleting whitespace? It’s worth it…

You might want to start by enabling whitespace mode: M-x whitespace-mode

Let’s start with closing the gap between lines…

M-^      Join a line with the previous line
C-x C-o       Delete white space after current line up to next line.

What’s great about the above two commands is that the point can be anywhere on the line when you call them.

The next two commands aren’t quite so quick to use, the point needs to be in the whitespace you’re trying to delete.

M-SPACE   Delete all spaces but one between two characters
M-\            Delete all whitespace between two characters

Don’t forget the rectangle commands:

C-x r k      Kills the rectangle between the point and the mark.

Find out more about how to use that command in this workout.
Lastly, removing line breaks. Use

C-M-%  query replace regex
Use C-q C-m or C-q C-j to find the line breaks.