Creative writing with Emacs

Introduction

Why am I using Emacs, a truly ancient program, for creative writing, instead of using Scrivener or Google Docs or Word, like everyone else? Is it because I am just as much a dinosaur, or is it because Emacs has something really unique to offer, that justifies my unconventional choice of writing environment?

Motivation

This article is heavily inspired by the article WordStar: A writer’s word processor on Ars Technica.

wordstar-under-vdosplus-800x495

Writing in the good old days of yonder

I grew up in a time without personal computers. Telephones were plugged in and not something you would carry around with you, and books were physical. And the internet was decades away.

I began to keep a journal and write poems when I was eight years old. The only typewriter in our house was my father’s electrical typewriter which he used to fill out forms for his job as a forester. So I used pen and paper.

But one glorious summer, while staying at my grandparent’s house, I used a portable typewriter for writing poems. It stood on a writing desk in an office where the walls were lined with bookshelves, and was very inspirational to me. The office was a writer’s dream, and it has been on my wish list ever since.

typewriter

Later on, when I went to high school, I wrote on a Commodore 64: notes, assignments, and papers. Using special commands, I could format the text – make it bold, italic or underlined – or insert page breaks and the like. I could show and hide the format codes, but they were never hidden from me.

commodore64

After graduating in 1992, I no longer owned a computer to write on, and I didn’t even have a portable typewriter, so it was back to pen and paper. But I did invest in a Parker fountain pen, and used it quite extensively for journaling.

Finally, in 1994, I managed to acquire a used PC at an affordable price and bought Word Perfect 5.1 in a big, blue box. The box contained 13 floppy disks and two huge books: a manual and a user guide. I studied those books religiously, and I learned practically everything that Word Perfect could do. I knew all the commands and keyboard shortcuts. My machine could run Word Perfect, but not much else, so there was nothing to distract me from writing.

wordperfect

Three years later, I had a 486 machine with Windows 95, and the good old days of writing were drawing to a close. I didn’t like Microsoft Word, didn’t appreciate that I had to fight with invisible formatting, or the fact that I even had to worry about formatting at all, so I went back to my fountain pen and good old paper for writing.

Writing in this day and age

These days we are not starved for choice when it comes to tools for writing. There are very capable general case programs, like Word, that can do everything a writer could want, and a whole lot more. There are specialized writer’s programs, like Scrivener, and its open source cousin Manuskript.

There is a myriad of text only programs, mainly Markdown based, where there is only minimal formatting, and where the format is pure, unadulterated text, as opposed to proprietary formats. Some of these minimal programs are especially made for creative writing; FocusWriter is one of them. Then there are several online writing environments, from Google Docs to the Hemingway Editor. There are even quite a few people who are using their smart phones to write with.

focuswriter

I did not use WordStar back in the day; I was using a text editor on the Commodore 64, and then WordPerfect. But WordStar was an extremely efficient text editor. Even though G.R.R. Martin is allegedly still using WordStar today, on an old DOS machine, there are practically zero users. There must be something that is close to WordStar, but modern, surely?

Remember the WordStar article I linked to? The conclusion is:

“For me, it’s clear: WordStar offers a more productive approach at its most fundamental design level than does its competition.”

WordStar didn’t survive, I am not sure if it even made it to the 1990’s, but the same thing can be said about Emacs: it is fundamentally designed to be productive. Emacs does share the steeper learning curve with WordStar, but I think it is well worth the effort.

Build your own text editor

Emacs started life in the 1970’s at the AI Lab at MIT (Massachusetts Institute of Technology) where Richard Stallmann added the ability to run macros to the TECO (Text Editor and Corrector) editor. A large collection of custom macros, whose names often ended in MAC or MACS, soon accumulated. And Guy Steele and Richard Stallmann worked to streamline the editing environment with a system called EMACS, for Editing MACroS or E with MACroS, in late 1976. By 1979, Emacs was the main editor used in MIT’s AI Lab and its Laboratory for Computer Science.

Richard_Stallman_at_MIT_dancing_1970s

In 1985 Stallmann released the first Emacs as free software, and the rest – as they say – is history.

Emacs is highly customizable, extensible and self-documenting. It is a text editor that can be driven wholly by the keyboard.

GNU_Emacs_23.1.1

In Emacs, everything is a command. Written in either C or Emacs Lisp:

“Almost all of the functionality in Emacs, including basic editing operations such as the insertion of characters into a document, is achieved through functions written in a dialect of the Lisp programming language. The dialect used in GNU Emacs is known as Emacs Lisp (ELisp). The ELisp layer sits atop a stable core of basic services and platform abstraction written in the C programming language. In this Lisp environment, variables and functions can be modified with no need to recompile or restart Emacs.” (From Emacs Wikipedia article).

The fact that you can make Emacs do pretty much anything, and exactly how you want it to, combined with the fact that you command the editor with keystrokes rather than mouse movements, is one of the reasons why Emacs is still popular, especially among programmers.

However, there are many people who use Emacs for creative writing. The rest of this blog post is a whirlwind tour that hopefully show you what the Emacs environment has to offer.

In practice

Emacs

The following is going to be a whirlwind tour of Emacs. There is going to be much too much information to take in – feel free to skip parts of it – but I think it is really important to really dig into what it’s like to be using Emacs for creative writing.

You can always revisit the content here in more detail. The whole point is to give you an accurate picture of how you use the beast that is Emacs.

A note about notation

In the following, “C” means “Control”, “M” means “Meta”, and “S” means “shift”. For instance, the keyboard shortcut “C-x 1” means to hold down the “Control” key and press “x” and then “1”, and likewise, “C-x C-c” means to hold down “Control” and press x and then c. “Meta” means the “Alt” key on Windows and Linux, and the “Command” key in OSX. “Meta” was a key on the ancient SpaceCadet Lisp machine keyboard upon which Emacs was born. Often I will show the corresponding command/function in parenthesis after the shortcut, like this: C-p (previous-line).

space-cadet.jpg

SpaceCadet keyboard by Retro-Computing Society of Rhode Island – Own work, CC BY-SA 3.0, https://commons.wikimedia.org/w/index.php?curid=3388741

Everything is a command

Most Emacs commands, except for movement commands and help commands, are generally invoked by means of the key combination C-x or C-c followed by the command. The most used commands use C-x, and the lesser used commands uses C-c, simply because the reach is smaller for C-x than C-c. For instance, to kill the current buffer, you would press “C-x k” to invoke the Emacs command “kill-buffer”. Instead of using the keyboard command, you can run the command directly by pressing M-x (execute-extended-command) and type “kill-buffer” into the mini-buffer when prompted. Luckily, the most used commands does have a keyboard sequence, so you won’t have to execute the command directly most of the time. And Emacs often uses mnemonics, like C-x C-s which means execute (x) the command save (s), making it easier to remember the keyboard shortcuts.

Frames, windows, files and buffers

In Emacs, the topmost graphical window that contains Emacs is called a frame. When you load a file into Emacs, it is loaded into a buffer. This buffer can be viewed in one or more windows. A frame, in other words, can have one or more windows, and those windows displays a buffer. You can have a lot of buffers loaded into memory, even if you are only working with a buffer in a single window. Think of open tabs in other programs, except that the “tabs” is not visible in Emacs. You can switch between buffers using the C-x b command, or display the buffer list by pressing C-x C-b. Emacs have several built-in buffers, like the Messages buffer and the Scratch buffer. The Scratch buffer is a place where you can store temporary text for later use, it is not going to survive an Emacs restart. When you are done working with a buffer, you can kill the buffer by pressing C-x k.

bufferlist

There are things that you can do in the buffer list window that might come in handy. You can navigate the buffer list by using C-p and C-n and choose the buffer by pressing return. Pressing “s” on a buffer will flag it to be saved, and pressing “d” will flag it to be killed. When you are done marking the buffers this way, press “x” to execute all the queued actions. I often use this method to quickly kill unwanted open buffers. The only buffers I recommend keeping open are Scratch and Messages. Finally, to get out of the buffer list, press “q“.

To open a file into a buffer in Emacs, press C-x C-f (find-file) and the Emacs directory editor, dired, opens so that you can choose a file to open. If the file doesn’t exist, it is created, and that is how you create a new file in Emacs. If you are successful, the file is now loaded into a buffer and shown in the current window. If you make changes to the buffer, you can save it by pressing C-x C-s (save-buffer).

findfile

You can split the main window into two windows by pressing C-x 2 to split horizontally, or C-x 3 to split vertically (side by side). To move between open windows, press C-x o (o for other). To close all windows except the one you’re in, press C-x 1, or you can close the window you’re in by pressing C-x 0. I have customized Emacs, so that when you have two windows open you can make them wider or taller, narrower or smaller, by holding down Control and press one of the arrow keys. Each of those windows can then be further split, if need be.

twopane

You can toggle read-only for a buffer by pressing C-x C-q. A great way to prevent accidentally editing a buffer that you only have open for reading. The buffer status indicator (normally a “-” for not modified and a “*” for modified) changes to a “%” to signal that the buffer is read-only.

Moving around

C-n and C-p moves the cursor to the next line and the previous line, respectively. C-f and C-b moves the cursor forward and backward. C-a and C-e moves the cursor to the beginning of the line, and to the end of the line. M-f and M-b moves forward and backward by word. M-a and M-e moves to the end of a sentence and to the beginning of a sentence. My Emacs is set up to follow the American Typist’s convention of ending a sentence with a period and two spaces, but that setting – like everything else in Emacs – can be changed in the configuration. This convention does make it easy to differentiate between periods ending a sentence and periods used in abbreviations.

There are also commands for movements across larger distances. If I want to move the cursor to the top, center or bottom, I can press M-r (mnemonic “reposition”). C-v is page down, M-v is page up. M-> moves the cursor to the end of the buffer, and M-< moves to the beginning of the buffer. And, finally, you can move between paragraphs – or elements, rather, but a paragraph is an element in text-mode – by means of M-{ and M-}.

Because search is performed interactively inline, I am using it to quickly navigate the document. I can use C-s to search forward and C-r (“reverse”) to search backward. When I press C-s I go into interactive search and when I type characters the search is highlighted as I type. I can choose the next match by pressing C-s again, until I’ve reached my destination, and then all I have to do is press Return and I am placed at the end of the word I want to go to. The same idea applies to C-r, reverse search. If I can see where I want to go, I am using interactive search to get there, saving myself a lot of navigation.

Honorable mention goes to the command M-m (back-to-indentation) which I use a lot: when I am standing on a line, and I want to go to the beginning of the line, after the indentation, without having to first go to the beginning of the line and then navigate to the beginning of the first word. Since I am using the convention of indenting paragraphs, that small command is saving me from a lot of unnecessary work.

Scrolling

C-l (mnemonic “line”) will reposition the current line in the buffer to the center, top or bottom of the window. A very useful command that I use all the time. That prevents me from grabbing the mouse to scroll the text whenever I have written myself to the bottom of the current window, a single C-l brings me back to the center of the window or, if I press C-l again, to the top.

I can also use the commands scroll-up-line and scroll-down-line to scroll up or down by one line. I have assigned those two commands to C-M-p and C-M-n. With those commands I can make further adjustments to the position of the current line in the window after using C-l. All this makes it highly unlikely that I ever would want to reach for the mouse to scroll the text.

Editing

Once you have mastered the movement, it is time to master the editing. Fortunately, Emacs is excellent at handling text, all without you having to have your fingers leave the home row.

Mark and the kill-ring

Marking a region is Emacs speak for making a selection. To set the mark press C-SPACE where you want the selection to begin and then just navigate to the place where you want the selection to end. For example, if I wanted to select the first sentence of this paragraph, I would go back three sentences (M-a three times), press C-SPACE to set the mark, and then press M-e once to select to the end of the sentence. To cancel a selection, press C-g (keyboard-quit) that will unset the mark. You can jump between the end of the region and the start of the region by pressing C-x C-x (exchange-point-and-mark).

region

Since you can perform incremental search after setting the mark, you can use this to select (mark a region) very quickly. This is especially handy if you want to select only a portion of a sentence or a paragraph. For instance, to create a region of the first sentence up to and including the first comma, we would have to press M-a three times, press C-SPACE once, and then press C-s and “,” and then return.

In addition to setting the mark manually, you can create a region (select something in modern terms) in various other ways. For instance, pressing M-@ will select the next word. Pressing M-@ repeatedly will select additional words. M-h marks a paragraph and C-x h marks the entire buffer.

Before we talk about what to do with a marked region, we need to discuss the terminology Emacs uses for deleting, copying and pasting text. Emacs was created a long time before there were any standards with regards to this, so both the shortcuts and the terminology is different from what you would expect.

When you cut text, you kill text, in Emacs terminology. When something is killed it is moved to the kill-ring, the Emacs equivalent of a clipboard. To copy is called copy to the kill-ring. C-w moves the selected text to the kill-ring, kills it, and M-w copies to the kill-ring. When you want to paste something from the kill-ring Emacs calls it to yank. C-y yanks the last item put in the kill-ring. If you then press M-y you will cycle the kill-ring. In other words, killing the sentence we spoke of earlier puts it in the kill-ring. Imagine that we kill a couple of words and a line after that, but now we want to paste that sentence into our document. That’s easy, just press C-y to yank the last thing killed, then press M-y repeatedly until we get back to the item in the kill-ring that we want.

That Emacs has a completely different terminology with regards to copy, cut and paste might make you uncomfortable, and the fact that it doesn’t use the familiar C-c, C-v and C-x key combos might make you hate it, but it is not that bad. The kill-ring does have it’s benefits, especially the way you can cycle it, giving you the option of killing text and yanking it back into the document exactly how you want to, instead of having to either rely on third-party clipboard managing programs or have to do the cut/paste routine several times. In Emacs, you can just kill your darlings – quite literally kill them – safe in the knowledge that they will be put into the kill-ring, and that you can get any of them back again by yanking the last thing killed and then cycle through the kill-ring until your beloved darling is safely retrieved from kill-ring purgatory.

Killing, and deleting, things

There are commands in Emacs which lets you delete characters and kill words, lines and sentences, without having to set the mark and create a region first.

To delete characters forward use C-d and to delete backwards use BACKSPACE. Characters are deleted, not killed. Which means that they will not end up in the kill-ring.

To kill by word, use M-d to kill word forward and M-BACKSPACE to kill word backward. C-k will kill to the end of line forward, and M-0 C-k will kill line backward. To kill sentences, use M-k forward and C-x BACKSPACE backward. Words, lines and sentences are properly killed, not deleted, and will thus be found in the kill-ring.

Just like for movement, where there is a correspondence between C-f and M-f and so on, it is easy to remember the relationship between C-d and M-d, and C-k and M-k.

A very handy command is M-z (zap-to-char) which will kill up to and including a character. For example, to turn “interrelated” into “related” stand on the beginning of it and press M-z r to zap (kill) the first “inter” part of the word. Zap to character will also work for longer things, just keep in mind that it will zap to and including the first occurrence of the character.

Case change

M-u will change the word you are in to uppercase, M-l will make it all lowercase and M-c will capitalize the word. Conversely, C-x C-u will uppercase a region, and C-x C-l will lowercase a region. There is even a command to change case of the last word written: press M– (Meta minus) and the corresponding case-change function. For instance, M– M-c capitalizes the last word written and leaves the point where it were so that you can quickly continue your sentence.

White-space

A big portion of editing deals with white-space, so it would be no surprise that Emacs has got us covered. Pressing Return inserts a newline, as you would expect, but pressing C-o will insert a newline on the line below. That is an ergonomic alternative to pressing return followed by a C-p (previous line) or the up arrow. C-x C-o will remove all empty lines except one, a good alternative to repeat C-k (kill-line). M-i will indent current line to the first TAB stop, normally 4 spaces. Pressing M-/ will remove all spaces and tabs around point, while M-SPACE will remove all spaces except one. M-j (join-line) will join one line to the previous line, and C-M-o will split current line from point. The latter command is slightly less useful than just doing a RETURN somewhere in the sentence, since it keeps the indentation, but it is there when you need it.

Transposing

To transpose two characters press C-t while standing on the second character. I rarely use it, because it is much easier to just delete and retype. M-t (transpose-words) is much more useful: it will swap two words, transpose them, when you are standing on the second word. For instance, to transpose the words “second first” we need to be standing on the second word and then press M-t. This operation should result in “first second” if executed properly. C-x C-t will transpose lines, but I don’t find it useful when writing prose. I would rather use the function “transpose-sentences” instead. I have added an alias to the command, so I can run M-x ts to swap two sentences around. Similarly, the command “transpose-paragraphs” I have mapped to “tp“. Note that because I haven’t assigned a keyboard shortcut to those commands, I need to invoke the commands directly using M-x (execute-extended-command). That’s not a big deal since the command is so short and so useful. One caveat when working with the transpose commands: if you want to transpose back, you need to move back one unit (character, word, sentence or paragraph) because the command puts you after the elements you transposed, setting you up to continue writing. I have often found myself transposing the wrong things because I forgot to reposition if I wanted to swap back.

Searching and replacing

We have already touched on searching, but let’s cover the topic in more detail. To search forward press C-s (forward incremental search) and to search backward press C-r (reverse incremental search). The search engine uses incremental search (isearch) which means that Emacs begins to search as soon as you start typing the characters you want to search for, narrowing the results as you type. If you make a mistake, use BACKSPACE to fix it. To navigate to the next search result, press C-s or C-r again. Once you have found what you searched for press return which will place you at the end of the search result. To exit the search prematurely press C-g C-g. Since performing a search makes Emacs insert the value of the point into the mark-ring, you can return to where you were in the document prior to the search by pressing C-u C-SPACE (jump to last mark). Since searching is done inline, you can use search in conjunction with creating regions, as I briefly touched on in a previous section. In fact, search is my primary means of navigating a document, if I know what to search for.

searching

You can also do search and replace in Emacs. Press M-% (query-replace) to enter search and replace, enter the term to search for and what to replace with and click return. Then press “y” to replace or “n” to skip as Emacs goes through the list of replacements. If you want to do an unconditional search and replace, you can run M-x replace-string, but Emacs will then replace every match without asking. Again, pressing C-u C-SPACE should return you to the point where you were before you searched and replaced.

Spell-checking

M-x ispell-buffer will check the current buffer for spelling errors interactively. SPACE ignores error, “i” adds the word to your custom dictionary, and “q” quits the spell check. To correct a spelling error, choose among one or more suggestions by choosing their respective number. To change the dictionary, use M-x ispell-change-dictionary. I have setup F12 to run the spell checker. If you want to check spelling errors as you type, you can turn on flyspell mode by running M-x flyspell-mode, and it will then flag spelling errors as you type them. It will not process the whole buffer, though. To make flyspell do that, you can run M-x flyspell-buffer. I have setup my Emacs to use Hunspell, which is the same spell checking engine that LibreOffice and Firefox uses.

spellchecker.png

Before you spellcheck your document using org-mode it would be a good idea to expand all nodes – S-TAB (SHOW ALL) – because the spellchecker is not intelligent enough to deal with hidden text. If you made a mistake like that, just hit “q” to exit the spellchecker and try again. Also, don’t forget that if you have marked a region the spellchecker will only check that.

Follow-mode

If you have a widescreen monitor, then you might appreciate follow-mode. You split the document into two vertical windows – C-x 3 – and enter the command M-x follow-mode while standing in the first window. Emacs will then make the second window follow the first, in other words: the text will be continuous across the windows, they follow each other.

followmode

This is a super useful minor mode!

Registers

Registers are places in memory where you can store text, positions or other things for later use. Only one kind of thing can be held in a register at any time. The registers can be accessed numerous times, and disappears when you quit Emacs. Each register has a name corresponding to a single character or number.

The first thing we can save in a register is text. Mark a region and press C-x r s to copy the text into a register. Emacs will prompt you for a character or number. I usually give them alphabetically increasing characters, starting from “a”. Pressing C-x r i will insert from a register. You should be given a list of the available registers, and if you’ve saved the text in the register “a”, press “a” and the contents of the register will be inserted into the text. If you are performing major surgery on a piece of text, you can copy text into a register, kill the text, mark and insert more text into a register, kill it, and do this numerous times until you end up with a number of registers with text in them. Now you can insert the text in the registers in the order you like, even numerous times. This is a great alternative to be cycling the kill-ring, especially since the kill-ring often is full of unrelated kills.

The second thing we can store in a register is the position of the point. Press C-x r SPACE to store the position of the point into a register. I tend to use numbers for registers containing positions. Then you can press C-x r j to jump to a stored position. Storing positions in registers and jumping to them is a lightweight alternative to be using bookmarks. However, bookmarks will survive an Emacs restart, and registers will be lost. Also, bookmarks can be named using words instead of just characters or numbers.

Bookmarks

Bookmarks are related to registers, and that is evident if we look at the keyboard shortcuts for dealing with bookmarks: they also start with C-x r.

Using the function C-x r m (bookmark-set), which I have bound to C-F5, we can set a bookmark. Either accept the standard name or give it a name and press return. The command C-x r b (bookmark-jump), bound to F5, will jump to a named bookmark. The command list-bookmarks, bound to S-F5 (shift F5), list all the bookmarks. In the list you can press “k” or “d” to kill or delete the bookmark. Press “x” to execute the command and save the bookmarks. Press “q” to exit the bookmark list.

I have configured my Emacs to store the bookmarks file in my Dropbox directory. That means that I can use the same bookmarks on all my machines. I don’t think the keyboard shortcuts for bookmarks makes much sense. I mean, what does the “m” in C-x r m stand for? Similarly, what is the deal with C-x r b? I know that “b” stands for “bookmark” but why is it assigned to bookmark-jump and not bookmark-set? Normally Emacs tries to be intuitive, but here it is not intuitive at all. Fortunately, you can assign keyboard shortcuts easily in Emacs, so I have chosen to assign them to F5, C-F5 and S-F5.

Dabbrev mode

Dabbrev mode, dynamic abbreviation expansion mode, is a useful mode that will expand abbreviations as you type. I often found myself tiring of having to write the names of my characters over and over, but now I just add an abbrev and type a whole lot less.

To add an entry into the global abbrev table just type the word you want to add an abbreviation for and press C-x a g. Now type the abbreviation. For instance, to add an abbreviation for the name “Ondolemar” I would write it out, press C-x a g, enter the abbreviation “ondo” and press return. Now, whenever I type “ondo“, it will expand to “Ondolemar” when I end the abbreviation by inserting a space or a punctuation. Sometimes you don’t want to expand, and in that case just run the command M-x unexpand-abbrev and it will undo the last expansion.

When you add an entry to the global abbrev table (C-x a g) that uses the same abbreviation as an already existing entry, Emacs will ask you if you want to redefine it.

To edit or view the list of abbreviations use the command M-x edit-abbrevs. A special Abbrevs buffer will open. Navigate to the global abbrev table. If you have added any abbreviations, they should be listed here. The entry for “Ondolemar” looks like this: “ondo” 3 “Ondolemar”. The first string is the abbreviation, the number is the number of times the abbreviation has been expanded, and the last string is the expansion. That Emacs keeps track of how many times an abbreviation has been used is quite helpful, it allows you to delete any abbreviations you don’t use. The Abbrevs buffer can be edited like any buffer, so if you made any changes remember to save (C-x C-s) and kill the buffer when you are done with it (C-x k).

Getting out of trouble

Emacs has several commands that will abort, undo, redo, terminate and recover. It is important to know how to get out of trouble, especially in Emacs, since the editor can be quite unforgiving.

C-g will abort a partially completed command, for example if you mistype a keyboard shortcut. C-g will also abort a search, and various other things. If in doubt, press C-g.

C-/ or C-x u performs an undo. C-g C-/ or C-g C-x u will perform a redo. Technically it will abort an undo, but the result is the same. Emacs is quirky.

Pressing “q” will often close special buffers, like buffer list, help buffers and the like. Sometimes you need to switch to the window (C-x o) before you can use “q”.

Running the command M-x revert-buffer will restore a buffer to its original contents.

If you are panicking, you can exit Emacs by pressing C-x C-c. I have quit Emacs in rage and panic numerous times. It takes a while to get comfortable with it. It’s okay.

And finally, if you have crashed you can recover files lost due to a system crash (or at least attempt to) by entering the command M-x recover-session.

Getting help

Emacs has an extensive help system, it prides itself in being self-documenting.

C-h r will launch you into the Emacs manual. And pressing “q” will get you out of it. The manual is divided into many sections and it is quite extraordinary, especially considering that Emacs is open source software. It will be evident in some places that the primary audience of Emacs is programmers, but it could be worse.

help

C-h k will tell you what a certain keyboard shortcut does. Very useful if you are in doubt. For instance pressing C-h k C-n will inform you that the keyboard command C-p will run the command “previous-line”. You can exit the help window by pressing “q”. I often use C-h k whenever I am in doubt, to save me from myself.

If you don’t know exactly what you want, but you know sort of what you want, you can try C-h a (apropos) to try and narrow it down to the thing you want. For instance, performing apropos on “bookmark”, C-h a bookmark, should yield a list of commands related to bookmarks. To remove the search result window, press C-x o to go to other window, and then press “q” to quit it.

If pressing “q” doesn’t get you out of a help window, C-x 1 probably will. Sometimes the window will try and be helpful and tell you what to do to get rid of it.

Emacs even has an interactive tutorial. Press C-h t to enter the tutorial.

tutorial.png

I highly recommend that you run this tutorial as many times you need. And, yes: it is normal to quit the tutorial in a panic, at least until you’ve got a handle on how Emacs operates. Take it slow, and you will get the hang of it. Emacs does feature a therapist, no surprise here, just run the therapist from the Help menu – if the menu bar isn’t visible, do M-x menu-bar-mode first – and now you are in a therapy session. Enjoy. Should you need to exit the therapy session, please press C-x k to kill the buffer, thank you.

Miscellaneous

Whitespace-mode

If you want to view the white-space for the current buffer run the command M-x whitespace-mode to toggle whitespace visualization. When whitespace mode is active, you will see spaces represented as dots, end of line represented by a dollar sign and paragraphs represented by purple color text, and tabs represented by ». Useful if you are trouble shooting a text. To turn it off, run M-x whitespace-mode again.

whitespace

Inserting special characters

To insert a foreign character into your text press C-x 8 and a character:

C-x 8 Y gives ¥ (Yen)

C-x 8 L gives £ (Pound)

C-x 8 o gives ° (Degree)

C-x 8 R gives ® (Registered)

C-x 8 C gives © (Copyright)

C-x 8 c gives ¢ (Cent)

C-x 8 S gives § (Dollar)

C-x 8 P gives ¶ (Paragraph)

You can also write accented characters, for example C-x 8 ‘ e gives é.

If you enter C-x 8 and press Return you can have Emacs autocomplete Unicode by name. For instance, you can insert a . by entering RIGHTWARDS ARROW.

In addition to the above, you can call C-x 8 with decimal or hexadecimal codes.

See Xah Lee’s Emacs : Unicode Tutorial

Diff

Often you find yourself with a modified buffer wondering exactly what is the difference between the buffer and the file saved on disk. Well, Emacs has you covered. Open the buffer list by pressing C-x C-b and put yourself on the line that corresponds to the modified buffer, signified by a leading star (*), and press “=” to run diff. Ediff, the Emacs version of diff, then compares the contents of the buffer against the contents of the file on disk and displays a diff. In the diff view, green areas have been added and red areas have been deleted. Ediff will inform you if the buffer and the file are identical, i.e. no changes. Press “q” to exit the diff view and “q” again to exit the buffer list.

diff

A word about modes

Emacs has a thing called “editing modes” that alters its behavior in certain ways. They are divided into major modes and minor modes.

To view a list of modes currently active press C-h m (help for modes) and a small Help window will appear.

Major modes

From the Emacs manual: “Major modes provide specialized facilities for working on a particular file type”. There can only be one major mode active for each buffer. Examples of major modes are text-mode, outline-mode and org-mode. The latter will get special treatment below, because it is a mode that is great for writers.

Minor modes

“Minor modes are optional features which you can turn on or off, not necessarily specific to a type of file or buffer.” A buffer can have many minor modes active at the same time, each one providing special features. For instance, “Abbrev mode” provides abbreviations, “Display-Time mode” shows current time in the mode line, and “Visual-Line mode” enables word wrapping, to name three minor modes. We already discussed “whitespace-mode” in a previous section that toggles visualization of white-space, and we also mentioned “menu-bar-mode” which toggles the menu-bar on and off.

Org-mode

Org-mode is a major mode. It builds upon outline-mode, which again builds upon text-mode. The file extension used by org-mode is *.org. From outline-mode org-mode inherits features to navigate, toggle visibility and edit a structured tree. It also features tasks, to-dos, tags, dead-lines, calendars, support for tables, export to various formats, and a whole host of other things.

org-mode-present

There are a lot of people who seem to be living their entire lives inside of org-mode because of the features it provides. It is a very capable organizer, hence the name, and works closely with the Emacs calendar (you shouldn’t be surprised at this point about Emacs featuring a calendar).

For creative writing, we are mostly interested in the features related to outlining, although being able to export to various formats is also going to be quite handy. So, lets take a look at what org-mode can bring to our table.

Structure

So, what is an “org-file”? It is a file with the org extension and it contains a number of headings. Those headings can have text and other headings. The headings in org-mode starts with one or more asterisks (*) followed by one space, one asterisk for a level one heading, two asterisks for a level two heading, and so on.

Let’s create a simple test org-file. Press C-x C-f, enter “test.org” and press Return. In the new buffer press C-Return to create a new heading. Give the name of “First”. Hit C-Return another time, name it “Second”. Press M-Right to “demote” the heading to a lower level heading. What we should be left with is “Second” being a child heading of “First”.

Now we want to add a third heading, so navigate to the first heading (C-p) and press C-Return. You should be creating a third header at the same level of the first heading. Name the new heading “Third”. We should end up with an org-file that looks like this:

test_one

Run the command M-x text-mode to see the file in text mode:

test_two

Switch back to org-mode by running M-x org-mode. Notice how the second headline disappeared:

test_three

The three dots after the first headline indicates that it has children. Move the point so that it becomes the current line and press TAB to toggle visibility of the children.

Let’s enter some text to our tree:

test_four

Experiment with pressing the TAB key on the various headlines. Watch how it cycles visibility. S-TAB (S for shift) will rotate the entire buffer between states. Those states are: OVERVIEW, CONTENTS and SHOW ALL.

After this brief introduction, let’s dive into how to use org-mode proper.

Editing

Inserting new headings

Press C-Return to insert a new heading at current level. C-Return will respect any content and subheadings, so if you press it when standing on a heading with content, text or children, it will insert the new heading after the sub-tree.

If you need to insert a new heading without respecting content, you can use M-Return to create a new heading at current level without regards for content or sub-trees.

One additional way of inserting a heading is to do it manually. Since a heading is simply one or more asterisks followed by a space and a title, you can simply type one or more *’s and press space once. Org-mode will convert into a heading.

Finally, we can use C-c * to turn an item or line into a heading. Pressing C-c * again will turn the heading back into plain text.

Promote and demote

When standing on a heading M-Right will demote the heading, meaning that if you do this to a level one heading it will become a level two heading. To promote a heading press M-Left.

If you want to promote/demote a heading, including the sub-tree, you need to use M-S-Left or M-S-Right. Be careful when using those two commands as it can behave slightly unpredictable. Be sure to save before engaging it. M-x revert-buffer might come in handy here if you messed up your sub-tree promotions/demotions.

Move headings and sub-trees up and down

M-Up and M-Down will move a heading up and down, including content and sub-tree if any. Since you can only move headings up and down at the same level, you might need to promote/demote it first if you want to transcend the boundaries of the parent.

orgmode

Mark, clone and copy

M-h will mark the element at point, and pressing M-h multiple times will mark additional elements.

C-c @ will mark a sub-tree. Useful if you want to export or count words in only a portion of the document.

In addition to M-h and C-c @ there are commands to clone, kill, copy and yank a sub-tree.

C-c C-x c will clone a sub-tree. C-c C-x C-w will kill a sub-tree. C-c C-x M-w will copy a sub-tree to the kill-ring. C-c C-x C-y will yank (paste according to standard speak) a sub-tree.

Navigation

C-c C-n and C-c C-p will navigate next and previous heading. C-c C-f and C-c C-b will navigate next and previous heading at the same level. And C-c C-u will navigate up to a higher level heading.

If you need to get to a specific heading, you can use C-c C-j to jump to it, using a special org-mode version of incremental search.

Narrowing

Narrowing means focusing on a specific portion of the document, making the rest temporarily inaccessible. Emacs itself does support narrowing, but since org-mode adds the ability to narrow to sub-tree, I have decided to defer covering the topic of narrowing to this section.

C-x n s will narrow to current sub-tree. Everything else appears to have disappeared. This allows you to focus your attention completely. To widen the view again, press C-x n w.

The regular Emacs narrowing functions also exist, although I rarely use them. C-x n n will narrow to region. C-x n p will narrow to page. C-x n e will narrow to element, which is going to be current paragraph most often. Again, pressing C-x n w will widen the view again.

I am using narrowing all the time. So useful! Especially if I find myself in a large document, perhaps a novel? I narrow to the subtree where the scene I am writing resides and everything else disappears.

Links and images

Org-mode supports links to other files and images. To insert a link, press C-u C-c C-l. If it is an image, it will be rendered in the document. To toggle the display of inline images, use the command C-c C-x C-v. Pressing C-c C-o to open the link at point.

The image format looks like this:

#+CAPTION: This is the caption for the next figure link (or table)

​#+NAME: fig:SED-HR4049

[[​./img/​cat.jpg​]​]

Either write the code directly, or use the C-u C-c C-l command. I haven’t figured out how to tell Emacs to size/resize images, so you need to resize the images externally if they are too big.

Basic markup

Org-mode does support basic markup of text, if you want to use it to add a bit of textual richness to your document.

Quoting the org-mode manual: “You can make words ‘*bold*’, ‘/italic/’, ‘underlined_’, ‘=verbatim=’ and ‘~code~’, and, if you must, ‘+strike-through+’. Text in the code and verbatim string is not processed for Org mode specific syntax; it is exported verbatim.”

To read more about the various options for formatting text and paragraphs, there are a lot of options, see the Org-mode “info” page – press C-h i to access the top level Info page where you can find the org-mode link.

Comments

Any line starting with a # character will be treated as a comment, and will not be exported. Similarly, you can make a sub-tree a comment sub-tree, and it will also not get exported. To toggle the COMMENT state for any element, press C-c ; – a green and italic COMMENT should have been prepended to the heading title. You can either delete it manually or press C-c ; again to remove it.

Capture and refile

Org-mode has functionality to be able to quickly capture new ideas (and tasks), and file them away somewhere safe to be processed later, without disrupting your workflow.

To run org-capture press C-c c. Choose a template by pressing a letter.

capture_start

Org-mode then inserts a new org-mode node into the capture file and shows an indirect buffer narrowed to that entry. Now you can enter the information you want, and press C-c C-c (org-capture-finalize) to close the entry and return to exactly where you were.

capture_enter

I have set up a very simple capture template and told org-mode to use a file called “notes.org”, located in my home directory. The contents of an entry looks like this:

capture_file

The entry has a heading, a description, a date and a link to where the capture was invoked.

Allegedly, you should now be able to use org-refile to process those entries and put them where you want them, and you can archive done items. I haven’t gotten this far in my Org-mode capture and refile journey, because the documentation is quite over my head. Once I figure it out, I will most probably write a blog post about it. But even now, with that simple capture template, I enjoy being able to quickly associate thoughts, to-do’s and ideas with specific places in the documents that I am writing, in a very out-of-the-way fashion.

Capturing is a great way to jot down ideas associated with your writing in a very organized way, without having to worry about where to put it. Visiting the notes file later, reading the entries and following the links will give you a great overview. Different templates can be used to capture different items, like ideas, research, unfinished additions, etc. I will probably revisit the topic in a later blog post.

Export

C-c C-e will trigger the export dialog. From this dialog, you can choose what format you want to export to. For creative writing, text and OpenOffice formats are probably the most interesting formats.

export

For instance, to export your org document to a plain, utf-8 encoded text file, you would do C-c C-e t u, and to export to ODT (OpenOffice), you would press the sequence C-c C-e o o.

Extras

Emacs is made to be configured and tweaked, and is quite disappointing “out of the box”. The configuration uses Emacs Lisp (Elisp) like most things in Emacs, but it can be configured to load and parse org-files. I have configured Emacs that way, and it means that I can edit my Emacs configuration in org-mode.

I am using a feature called “use-package” which will automatically download and install packages before they are configured. Because, yes: Emacs features a package manager. The editor has a lot of things built-in, but there is a wealth of packages available. Everything from themes and look-and-feel, programming language support and productivity helpers, to email clients and web browsers, Twitter clients and games.

packages

What follows is a selection of the extra things that I have enriched my Emacs with to try and make it my dream writing environment.

 

Look and feel

Emacs looks like shite without any themes installed. I have configured my installation to use the Zenburn theme, with my customizations. I am also using a package called Spacemode which changes the mode line (that’s the horizontal thingie with the yellow arrow-shape), and also org-bullets which makes the org-mode headings use fancy bullets.

withtheme

This is how Emacs looks when I remove all my look-and-feel customization:

notheme

Darkroom

I am using Darkroom mode for a distraction-free writing environment. There are other modes for this, like olivetti-mode and writeroom-mode, but I’ve settled on Darkroom because it is lightweight and configurable.

From the Darkroom description:

“Remove visual distractions and focus on writing. When this mode is active, everything but the buffer’s text is elided from view. The buffer margins are set so that text is centered on screen. Text size is increased (display engine allowing) by ‘darkroom-text-scale-increase’.”

I have configured Emacs to toggle Darkroom when I press F6, and I am using Writeroom to toggle the mode-line on top of the document.

Darkroom is excellent, especially in conjunction with full-screen. I have configured my Emacs to toggle full-screen when I press F11.

Writeroom

Transparency

This is a custom script that I have written – or lifted from the Internet – that changes the alpha of the main frame, makes it transparent. I can toggle transparency by pressing C-c t.

This feature works best if Emacs is full screen (F11) and uses Darkroom (F6), and when the desktop has been configured to auto-hide the toolbar.

darkroom_transparent

Draft mode

Draft-mode is very useful minor mode that prevents you from using going back to edit. Just enter M-x draft-mode, and you are not able to correct any mistakes. If you find yourself using too much time to correct typing errors, draft-mode to the rescue.

One caveat, though: since activating draft-mode makes the entire buffer read-only and moves the point to the end, you need to use narrowing to use it in an already existing document. I often narrow to sub-tree (C-x n s) and then activate draft-mode.

Wc-mode

This is a small minor mode that keeps track of word count and displays a summary in the mode-line. It is activated by running M-x wc-mode. To set the word goal, by default 500, you can use C-c C-w w. Pressing C-c C-w c will show how many lines, words and chars there are in the document. And you can reset wc-mode by running M-x wc-reset.

The word-count indicator in the mode-line looks like this: WC[original-wordcount+words-written/total-wordcount] For instance, my current wc-mode line reads: WC[519+125/644], and that means that I started with 519 words and have written 125 for a total of 644 words.

wc-mode-1.png

The word count reported is the word count of the buffer, and I have narrowed to a sub-tree, so I need to take that fact into consideration. I have written a small helper function to count words, and it reports 8067 words for my document so far.

I also discovered that wc-mode does not know what to do when you call widen to remove the narrowing. It currently think that I have written 7586 words this session, but that is because I have widened the buffer with wc-mode active.

To reliably count words I am using my custom function, M-x novel-count-words, and I often use it after selecting the sub-tree where my to-be-exported text resides. But wc-mode is useful as a motivational boost when you are trying to reach a word count goal.

Writeordie

I have modified a small Emacs package that I found on the Emacs Wiki and which provides functionality similar to the WriteOrDie web page.

The idea is that, once the mode has been turned on and started, if you don’t keep on writing, the script will automatically start deleting one word per second until you start writing again. I have configured it to toggle the mode when I press F8. I can then use F9 to start the session and M-F9 to stop it.

When WriteOrDie mode is turned on, there will be a “Write!” mode indicator in the mode-line. Once I press F9, the mode-line will feature a section like this: [0 of 500, TIMER: 1200, 1]. The last number is the status indicator. “1” means we are okay, and we are writing, “2” means a warning that WriteOrDie will soon start deleting words if you don’t get the cork out and write something, and “3” means WriteOrDie is busy deleting your words.

The script is still under development, and I would like to implement the ability to set the session length and the word-count goal, and change the status indicator to be a bit more enlightening than merely showing the status number. But it does the job, it keeps me writing.

Chronos

Chronos is a package that provides timers. To add a timer we use the command M-x chronos-add-timer. We enter the amount of minutes and the message. Once the time is up, a small notification appears in the notification area and a dialog pops up.

Chronos runs in a buffer called Chronos. Once the timer has expired, we need to delete it in the Chronos buffer. Simply press “d” and it is killed. You can also kill a timer that is running by the same method. The Chronos buffer is just like any other buffer, you can close or kill it by pressing C-x k.

timer

I use Chronos for word sprints. I often split the window horizontally and load the buffer into the new window so that I can see the Chronos timer running when I work.

Winner-mode

This is a small helper minor mode that is configured to start with Emacs. It keeps track of all windows that I open, split and close. Every time I make a change to the windows and the buffers within them, winner-mode keeps track of it.

By pressing C-c Left I can undo the last window configuration, and by pressing C-c Right I can redo it. This is extremely handy if you find yourself switching from two vertical windows and one window, or whatever number of windows you use. Pressing C-c and left or right will bring you back (and forward) in the window history.

Speed-type

I installed speed-type because why the heck not?

speedtype

It lets me practice my touch typing within Emacs. If I enter M-x speed-type-text it will download text from Project Gutenberg and then I type over the text. Once I am done, I am rewarded with a summary of my performance. This is not really a feature that I desperately need, but it’s fun – I can procrastinate a bit and still feel that I do something related to writing.

Manuskript and the cork-board

One of the things that I miss from Scrivener is the cork-board. Not often, because I quite like how I can promote/demote and move headings in org-mode, but once in a while I am in a cork-board kind of mood.

Fortunately, there is this program called “Manuskript” that does pretty much everything that Scrivener does, and it is free and open source and available for all major platforms.

The only thing that I don’t like about Manuskript is the editor. Well, I don’t like all editors besides Emacs, but I have found a way to have the best of both worlds: simply import Markdown from within Manuskript, use the cork-board and export Markdown. And since the only practical difference between org-mode and Markdown is that org-mode uses “*”s for headings and Markdown uses “#”s for headings, then the process is going to be semi-automatic and straight forward.

  1. Edit a copy of the org-file.
    • Save a copy of your document. C-x C-w, and give it a *.md extension.
    • Remove the header and all other comments.
    • Replace all *’s with #’s. M-% * #. You can use M-x replace-string to do this unconditionally, but sometimes there is an asterisk somewhere outside of a heading.
    • Make sure that there is one empty line before the first heading.
  2. Import Markdown into Manuskript.
    • Start Manuskript and create a new empty project.
    • Import Markdown by pressing F7, choose the file to import, Preview and Import.Manuskript_import
    • If the preview doesn’t look right, fix the Markdown file and try again.
    • Go to the Editor and you should see your document imported into the cork-board.
  3. Use the cork-board.
    • You can drag and drop and rearrange the sections of your document just like in Scrivener.Manuskript_imported
  4. Generate Markdown.
    • Press F6 to open the Generate dialog, choose Markdown and Preview. If it looks alright, press the Export button.Manuskript_export
  5. Convert the Markdown into org-mode.
    • Put the header back in and replace all “#”s with “*”s.

The next logical step would be to implement an org-mode importer/exporter for Manuskript. That should make the process a lot smoother.

Conclusion

I haven’t touched on everything – that is not possible when working with Emacs, there is always more to learn – but I hope I managed to convey to you that Emacs is quite a full-featured text editor. And I find myself to be extremely efficient. I am a touch typist, so I like to keep my hands on the keyboard.

The secret about Emacs is that it is driven by muscle memory, just like a musical instrument. It takes some time to get there, but once you do, you can operate it instinctively. Programs which makes use of the mouse and menus can’t compete with that.

Another thing that beats the competition is the configurability. Instead of having to adapt to a fixed set of features provided by some program, I adapt Emacs to me. And I change it from time to time as my needs change. I appreciate this adaptability. It makes me productive. And there is something magical about the whole thing.

If you are curious, or perhaps want to give Emacs for creative writing a try, you can find my Emacs configuration at Github: https://github.com/jacmoe/emacs.d

If you are interested in learning how to use Emacs, then know this: you can’t learn the Emacs commands by night. The best way to start is to download and print an Emacs reference card – here is one for Emacs 22 (I will update the link when I find a newer one) – turn on the menubar (M-x menu-bar-mode) and then write down the commands that you want to know in a homemade Emacs cheat sheet. Do the tutorial, but above all: use Emacs to write! You will learn more and more commands and keyboard shortcuts as you need them. And you will probably be grokking the reference card over and over. But it’s fine, really. The effort pays off in the end.

8 thoughts on “Creative writing with Emacs

  1. I started reading and immediately thought my husband would enjoy. Your writing is interesting and informative! For the guys like my dh, you should write a book!

    Liked by 1 person

    1. Thank you, Rachael 🙂

      This blog post almost is a book ;D
      Kudos to your husband if he manages to read it all in one sitting!

      My future blog posts are not going to be as contentful. I spent two weeks writing it. The luxury of being without an internet connection.

      Like

  2. Thanks for this, hadn’t come across the narrowing functionality before. For moving around in text on screen I can really recommend ace-jump, combine it with key chording to call it and you can navigate anywhere from the home row 🙂

    Liked by 1 person

    1. I did look into ace-jump and avy-*something*, but I found it to be too busy. Will probably take a look at ace-jump, because I jumped right past it to avy when I evaluated the choices. Thanks 🙂

      And, yes: narrowing is really great. It helps me focus on what I am working on.

      Like

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.