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 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.
Emacs Workout

Emacs and Scrivener

I heard a lot of people talking about Scrivener so I downloaded a trial copy (on Windows, there’s no Linux version, sadly…) and gave it a try.

It seems like a suitable tool for writers to use, it comes with a nice tutorial, and I’d recommend that anyone give the free 30 day trial a go, (this despite the fact the company behind it are called Literature and Latte).

I still prefer Emacs, though. Most of the features that Scrivener offers are easily replicable in Emacs. If you’ve been following my Emacs Writing Tips you’ll have been doing something similar anyway.

One thing I did like about Scrivener was the corkboard, a place where you could pin synopsis cards and move them around whilst you’re putting your ideas in order. This is a really good idea, and one thing that Emacs can’t replicate so well.

Here’s a work around

The idea is quite straightforward

1. Write your synopsis in headings
2. Move them up and down using M-<up> and M-<down>

It’s not as nice as the corkboard, but if you want a graphical interface, you’re using the wrong program.

It’s also worth mentioning org-tree-to-indirect-buffer, here. This allows you to replicate the document map in Microsoft word. It’s easiest to try this out for yourself

1. Open an org file in Emacs
2. Navigate to the subtree you want to edit
3. C-x 3 to split the window vertically (org-tree-to-indirect-buffer defaults to a vertical split)
4. C-c C-x b to open the narrowed subtree in the other frame

It all sounds rather complicated, but it’s really quite straightforward, and very useful…

Emacs Workout

Calc Mode 2: Two’s Complement

Emacs provides a method for working out numbers in two’s complement form

M-x calc        Turn on calc mode
O d2            Turns on two's complement binary
b w 8           Sets the word length to 8 bits
d z             Displays leading zeroes

Now you can enter numbers. Don’t forget to use underscore for negative numbers

_3 (-3) gives 2##11111101

You can press y to yank the result back into the last buffer.

Quick Conversions

if you want to quickly convert between binary, denary and hex you can use quick calc mode:
To convert 17 from Denary to Binary

C-x * q         Enter quick calc mode
17              Hit enter
Result: 17 =>  17  (16#11, 8#21, 2#10001, "")

To convert 1100 from Binary to Denary (or Hex)

C-x * q         Enter quick calc mode
2#1100          Enter in minibuffer.  Use 16# to enter a Hex number
Result: 12 =>  12  (16#C, 8#14, 2#1100, "")

See Also

Emacs Workout

Finding my Place

(This post appears as part of the document My Emacs Writing Setup: a guide to how I write novels and short stories using Emacs Org Mode)

It can be a nuisance finding where things are even when writing a short story. When writing a novel, it’s easy to get lost amongst the story, the notes, the character sketches…

Fortunately, Emacs and Org-Mode have a number of features to help you find your way around.

The most basic and most useful method, of course, is Emacs search. I’ve written more about this here.

Similar to search are

M-x             occur, and
C-c / r         org-occur

These highlight all occurrences of the search string. This can be handy, for example, when searching to see which chapters a character appears in.

Quite often I find myself jumping up and down a file, adding text here and there. You can use the standard mark-ring commands:

C-<SPC> C-<SPC>         Set the mark to the mark ring
C-u C-<SPC>             Move point to where the mark was

… but org-mode has two commands that respectively push your current position to the mark-ring and jump to the last position on the mark ring. For convenience, I’ve bound them to the f7 key as follows.

(global-set-key (kbd "<f7>") 'org-mark-ring-push)
(global-set-key (kbd "C-<f7>") 'org-mark-ring-goto)

Now, I simply hit f7 to remember my position before heading off to edit elsewhere in the file, then hit C-f7 to return to where I started.


I’m assuming you already know how to use bookmarks, but if you don’t, here’s a link to the Emacs Wiki for a crash course.
As I write on multiple machines, I keep my bookmarks file on Dropbox so that I have a consistent set of bookmarks wherever I happen to be working. I’ve added the following command to my .emacs file to let Emacs know where my bookmarks are.

(setq bookmark-default-file "~/Dropbox/common/emacs/bookmarks.bmk" bookmark-save-flag 1)

I’ve got into the habit of having a bookmark named here. I try to set this mark when I finish working. When I start work, I simply jump to here.

Emacs Workout

Calc Mode 0: Basics

Having seen it written on a blackboard in the Simpsons, I wanted to check if

398712 + 436512 = 447212

thus disproving Fermat’s Last Theorem. My pocket calculator confirmed the expression to be true, but those are big numbers, and the calculator lacks precision.

This seemed like a perfect opportunity to use calc mode.

M-x calc        to enter calc mode

First enter the left hand side

12 ^
12 ^

Both numbers are now there in the stack:

--- Emacs Calculator Mode ---
2:  16134474609751291283496491970515151715346481
1:  47842181739947321332739738982639336181640625

Hit + to add them together. Now to enter the right hand side.

12 ^

Now the left and right sides of the original expression are there in the stack, and you can see that whilst they may be sufficiently equal to fool a pocket calculator, they can’t fool Emacs.

--- Emacs Calculator Mode ---
2:  63976656349698612616236230953154487896987106
1:  63976656348486725806862358322168575784124416

Hit  to see the difference:


d g to group the number, then hit y to yank the number back into the current buffer.


… as I just did there.

See Also

Calc Mode 1: Binary Numbers

Emacs Workout

Regexp Exercises

You might want read the post on Regexp Builder before attempting these…

Here’s an example of a British Postcode: OL1 3SQ. It has the format 2 letters and a digit, space, 1 digit and two letters. The following emacs regex finds this type of postcode:

“[A-Z]\{2\}[0-9] [0-9][A-Z]\{2\}”

  1. Write a regex to find postcodes of the type W1 1AA
  2. Write a regex to find postcodes of the type RM12 4JJ
  3. Write one regex that finds all three types of postcode: OL1 3SQ, W1 1AA and RM12 4JJ
  4. Write a regex that finds simple email addresses of the form
  5. Now extend the regex to find email addresses of the form
  6. Now write a general email regex that will find all properly formed email addresses
  7. Google the form of an ISBN (There are two standards). Write a regex to find ISBNs
  8. Write a regex that can find unnecessary white space in a line of text

This      line     has              unnecessary      white space    .
|              So does this line   |
This line does not.


“He said ‘Have you got the time?’” “Why didn’t he look at his watch?”
Write a regex that can find the left single quotes: ‘and right double quotes: ” in the above conversation.

Emacs Workout

Dired Tricks #2

Here are some random Dired mode tips:

1 Want to include the names of files in a document?

w       copies names of marked files to kill ring.
C-0 w   copies absolute file name
C-u     copies names relative to Dired’s current directory

Here’s an example of this in action:

Bob Hall is a leading British boogie-woogie pianist. Here are the tracks off his album What Goes Round

  1. I Can’t Get My Ass in Gear.mp3
  2. Road of No Return.mp3
  3. Running with the Blues.mp3
  4. Bloodhound Blues.mp3
  5. What Goes Round Comes Back.mp3
  6. The All Star Medicine Show.mp3
  7. Backwater Blues.mp3
  8. Alone with the Blues.mp3
  9. One More Road.mp3
  10. Back on the Valley.mp3
  11. Same Old Place.mp3

2 Fed up with deleting Dired buffers as you navigate through structures?

Pressing a rather than enter will close the current dired buffer as Emacs opens the next one.

3 Hiding Uninteresting Files

Here’s a partial view of a directory:

-rw-rw-r--  1 ***** *****  110537 Mar 24 13:07
-rw-rw-r--  1 ***** *****   60688 Sep  3  2013
-rw-rw-r--  1 ***** *****   60688 Sep  3  2013
-rw-rw-r--  1 ***** *****  112046 Mar 18 16:37
-rw-rw-r--  1 ***** *****  112079 Mar 18 16:40
-rw-rw-r--  1 ***** *****  112133 Mar 18 16:55
-rw-rw-r--  1 ***** *****  112133 Mar 18 16:55
-rw-rw-r--  1 ***** *****  112196 Mar 20 15:16

As I use force backups on all my files, all those ~backups clutter things up. I used to do the following remove them:

% m ~   Mark all backup files
k       Remove them from view

Then I discovered dired-omit-mode, part of dired-x.

Place the following in your .emacs file

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

Now hit M-o to toggle uninteresting files like backup files on and off.

4 And finally…

Something that I always forget when I need it: to create a new file with non existent parent directories from current directory:

M-x make-directory RET RET

Related Posts

Dired Tricks #1

Emacs Emacs Workout

Mouse and Emacs

Okay, if you’re using Emacs properly you won’t be using the mouse. You know that you waste time moving your hand from the keyboard to the mouse and back again.

But there will be times when you have the mouse in your hand anyway, so whilst it’s there you might want to remember these handy shortcuts…


Ctrl and mouse 1 brings up the buffer list. Slide that mouse down context menu to quickly change buffer

Selecting Text

The following are worth remembering:
  • Double clicking on a parenthesis selects up to the matching parenthesis
  • Double clicking on a word selects it
  • Triple clicking selects a line

Mouse-1, Mouse-2, Mouse-3

I’m right handed. On my computer, Mouse-1 is left click, Mouse-2 is the scroll wheel and Mouse-3 is right click
Mouse-1 sets the point
Dragging the mouse not only sets the region, it also copies it to the Primary Selection, ready to be inserted by Mouse-2
Mouse-3 extends the current selection up to the point clicked. Mouse-3 a second time deletes the selection. This doesn’t work in all modes, however.