Download

Dedication

To my keyboard.

Preface

This book serves a double purpose:

  1. It is a simultaneous introduction to both Vim and GNU Emacs, for those who have never ever dared using either of them; and

  2. A reflection of my own personal relationship with editors and keyboards.

Most of the tutorials and books about Vim and Emacs contain way too much information, and can be daunting to new users. What I found after using Vim for 15 years, and after 3 months of trying (and loving) GNU Emacs, is that they are actually very similar in many ways. And also, that one only needs a small amount of information to become very proficient in both, in a short amount of time.

Hence the idea of this book; to introduce both at the same time, giving the necessary pointers for readers to continue the exploration by themselves.

Even better, I want to provide you with a basic set of configurations, to make you feel comfortable off-the-box with these two editors. The bare minimum. Nothing else.

But as I said, this book is also my personal story around keyboards, editors and typewriters.

I have been using keyboards of different kinds for decades now, and I have very strong feelings regarding them. I use them every day, in lots of different tasks, and I have quite high expectations from them. In this book I will go through anecdotes and stories, all while talking about features of these two editors. And you will see, it all fits together quite nicely.

Tools shape us, just like we shape our tools.

There are a couple of features that I want to have in any writing environment that I use every day:

  1. Packages. Each of these editors provide such a wonderful amount of plugins, one has to have a clean working environment to make use of them.

  2. Git. I have to be able to commit and manipulate the local git repo where I am working from the editor.

  3. Multiple undo. Both editors allow me to go back and forth in time in my files, and I like to be able to access that functionality in the easiest possible way.

  4. File browser. I want to be able to access the folder where I am working from the editor.

  5. Line numbers. I have to have them.

  6. A distraction-free writing environment. When I write text in Markdown or Asciidoc, I like to be able to use these editors in a nice clutter-free environment.

  7. Bookmarks. Being able to jump from one location to another on the same document or on another document, in just a few keystrokes, is something I miss in pretty much every other editor out there.

Because most of what I do with Vim and GNU Emacs boils down to some basic things:

  • Long text writing and editing; Markdown and Asciidoc, mostly.

  • Some code writing, although I preferably use the major IDEs for each language for that; Xcode, Android Studio, Visual Studio, and some JetBrains goodies. In that sense, I use Vim and GNU Emacs as accessory editors.

  • Editing stuff on a remote server via SSH.

Both editors have been built around keyboards and touch-typists; the idea being that your hands never leave the keyboard. Whether that is a good or a bad thing, I do not care much. I just like to have my hands on the keyboard at all times, and to be able to work without using the mouse. It is just a personal choice.

This is why this book has absolutely no screenshots whatsoever, but lots of keyboard shortcuts like these: Meta+X, Esc, and J. The idea being that, as you read, you play with those commands on your own.

Knowing Vim and/or GNU Emacs is a useful skills to use any operating system in the world; both editors run perfectly well in Windows, Linux and macOS. They are stable, extremely solid and reliable pieces of software, and best of all, they are both 100% free, as in freedom and as in beer.

I am going to explain the basics, from the very beginning, and then I will teach you how to customize these editors until they fulfill those basic requirements.

This is a very, very opinionated book; advanced users of both editors might complain that I left this or that feature aside, but I think it is better this way.

Book Structure

This book is structured in such a way that users not familiar with neither Vim nor GNU Emacs can start customizing it and feel confortable with both of them. Because, let us be very frank about this: both Vim and GNU Emacs are extremely minimalistic out-of-the-box. They are usable, but they are so much more powerful than that, it is a pity not to customize them a bit.

Here you will not find tutorials about Emacs Lisp or Vim script; there are excellent books and websites for that. This book is geared as a simple introduction to both, and then you should jump to something more complete if you are hungry for more.

I also will not talk about XEmacs, Spacemacs, Aquamacs, or Neovim, but I wanted to mention them and link to their websites anyway. The communities around those projects are outstanding and they do a phenomenal job.

Requirements

You basically need a computer with Vim and Emacs installed; this means that you can use any version of the following operating systems: GNU/Linux, macOS, Windows, BSD, Solaris, MS-DOS, Raspbian, or OS/2.

However for the sake of simplicity, I will assume you are using macOS 10.14 "Mojave."

In terms of software, I wrote this book with Emacs 26.1 and Vim 8 in mind. I think most of what I talk about used to work in previous versions anyway, so you might be able to follow with whatever you have.

You can install them with the package managers of your platform, or downloading them from their corresponding websites.

Music

And yes, as you might have guessed from the table of contents, each chapter has a song as a title. In the age of streaming music, you can create a playlist with all these songs and read each chapter with that music as a background.

You can, of course. This book is like a movie, and the songs are the soundtrack.

Act I: Andante

Stallman’s EMACS was brilliant in the 1970s, but today we demand more, specifically Microsoft Word, which can’t be written over a weekend, no matter how much Coke you drink. Multinational corporations are themselves technology invented to get big things done, things that sustain us in the complicated modern world.

Unix and the Internet turn 30 this summer. Both are senile, according to journalist Peter Salus, who like me is old enough, but not too old, to remember. The Open Sores Movement asks us to ignore three decades of innovation. It’s just a notch above Luddism. At least they’re not bombing Redmond. Not yet anyway. (source)

— Robert Metcalfe about Emacs in 1999

1. Overture Cotton Avenue

This book is a confession. I have a text editor and keyboard fetish.

At the very beginning, writing my first lines of code in 1992, I did not know any better and ended up just using the version of Notepad bundled with Windows 3.1. Yes, I wrote code and prose in the dullest, simplest, most awkward, most limited text editor ever invented. It did not took me very long to understand that such a tool was fairly poor; even MS-DOS edit was a much better one, surprisingly coming from the same company.

As limited as Notepad was, it had however a cool feature: if you saved a text file starting with the characters .LOG, it would append the current date and time every time you opened it. I think I learnt that reading a copy of PC Magazine or something like that. Notepad became thus my first diary on a computer, decades before Day One.

During those first years, the most advanced code editors I used were Turbo Pascal 7, Visual Basic 3, and Delphi. They had line numbers, syntax highlighting, "Intellisense" and other cool features. I liked having those IDEs letting me know in real time if I had typed something wrong. Visual Basic even had an obnoxious dialog box that would appear every time I moved the cursor away from a line it did not like.

When I started working professionally in 1997, I needed something more powerful than Notepad for editing HTML and JavaScript content, so started fiddling with some specific editors, such as HoTMetaL and Macromedia Dreamweaver. Even Netscape had its own HTML editor bundled with the browser, called Netscape Composer (whose descendant is today’s SeaMonkey Composer.) But I found all of them needlessly heavy, clumsy, and slow. These were not tools that I could use with joy.

In 1998 I migrated my workflow to something much, much better: the recently released EditPlus. I quickly became a big fan of EditPlus. It was simple, small (the 64-bit version 5.1, available at the time of this writing, is just 2.2 MB!) It was (and still is) blazingly fast, and there is a myriad of different add-ons (syntaxes, autocompletions, etc.) for various programming languages, most of them contributed by users. I am glad to see that it is still available and up-to-date, 20 years after it became my tool of choice.

Back then the Windows Editor Wars were raging between EditPlus and UltraEdit, but for me EditPlus was the clear winner, hands down. I always thought UltraEdit was a lesser option. There is always an editor war raging somewhere in the developer community; this was the first one I got to witness.

I have always used both the command line and the window environment of whichever operating system I used. That meant that, as a Windows developer, I switched between edit and EditPlus quite a bit. There have always been things I can do faster on the command line, and there are always things I can do faster with the mouse. Using both I can work more efficiently and faster.

I used EditPlus without interruption for at least 9 years. With it I wrote VBScript, HTML, JavaScript, CSS, C++, Java, Transact-SQL and even C# code. It was the tool I would install first on any new PC.

By 2002, however, I got my first iBook with Mac OS X 10.2 Jaguar and I started, once again, the quest of a text editor, this time outside of work – at that time, Macs were absolutely impossible to spot in a Swiss workplace.

Back then the Mac was in the middle of a big transition, from the Classic environment to the new Unix-based operating system, and from the Carbon to the Cocoa APIs. Hence, the world of text editors was quite fragmented. There were a few commercial and really popular editors like TextWrangler and BBEdit, but I did not find them as good as EditPlus. Also, being apps from the Mac OS 9 era, they did not feel at home in the new Mac OS X, neither visually nor functionally. I also tried jEdit and, well, it did not fill the bill, either.

There is a strong sense of taste in the way I choose my tools. They not only have to look good, they have to feel right, and they have to be extensible.

But the major reason I had bought a Mac was to learn to use Unix. So with that objective in mind, I bought a book from O’Reilly called "Learning Unix for Mac OS X", and next thing I knew, I started using Vim regularly. Why Vim instead of GNU Emacs or GNU nano? Well, I actually do not remember. But in any case I got into the habit of using Vim, and I started cumulating settings in my .vimrc file, starting in 2002.

In 2003 I discovered Smultron, a great 100% Cocoa-based editor, and that was the first Mac editor I actually used a lot. It was fast, quite powerful, but sadly not extensible. In my opinion it was good but limited. So I kept using the command line, and learning every day something new about Vim.

By 2006 I started developing Ruby on Rails applications, and in one of the screencasts of David Heinemeier Hansson I discovered a text editor I had never seen before: TextMate. It was love at first sight. TextMate was exactly the kind of editor I wanted, it was extensible, fast, and 100% Cocoa. The transition was done, and I stopped using Smultron, Windows and EditPlus forever.

But of course nothing lasts forever. By 2009 it was painfully obvious that TextMate 2.0 was going to be delayed, and I (and many others) started looking for options. Many opted for switching to Sublime Text, but I never quite liked it. So I went back to the roots and decided to use Vim full time, including its GUI brother, MacVim.

What I loved the most of doing the switch to the Vim/MacVim combo was being able to use the same keyboard shortcuts in both environments. There is also such a long list of plugins and themes for Vim, that I could use it for pretty much anything. Including writing my first two books.

I had also gotten into the habit of using tmux on my iTerm2 terminal window. I felt that the more I used the command line, the more productive I got. Besides, using the command line regularly made me confortable whenever I logged into one of my Raspberry Pi, a virtual machine with Ubuntu, an EC2 instance with Amazon Linux, or a remote server with FreeBSD.

Finally, in 2018 I decided to take the leap and start using GNU Emacs. Most of my developer friends chuckle when I mention this, particularly in the age of Visual Studio Code and Atom, but again, I love the fact that I can switch from the command line to the GUI environment and that I can use the same gestures and keystrokes.

And what I discovered using GNU Emacs is that, in spite of its famous and heated rivalry with Vim, these two editors shared a lot of commonalities; they are both strongly keyboard-driven editors, extremely extensible and customizable, and with lots of commands. I find each to be a bit better than the other in some particular thing, so I keep switching from one to the other.

(Although some say the editor wars are over now, and Vim won, while somebody else says that Emacs is dead, although not in the way one thinks. Who knows.)

The GNU Emacs manual says that Emacs is "the extensible, customizable, self-documenting, real-time display editor." Well, I find that this description fits Vim as well.

And to train myself to use it, I started writing a book that would outline the path for a perfect beginner to both, to discover these editors. And, maybe, get confortable enough so as to start using them full time.

And now you are reading that book.

Looking back in time I wonder, could I have started using GNU Emacs or Vim back in 1997? After all, they both existed by that time, and had already for a long time.

The truth is, as a Windows developer who did not know any better, I was completely unaware of their existence. I just did not know anything about Unix, and I did not have anyone around me to enlighten me towards this path. My curiosity alone would take me from the crashing realms of Windows to the spartan lands of the Unix warlords in a journey without return (key.)

2. Mysterious Ways

I am often asked the question, "what is the first thing you need to know about Emacs or Vim?"

The answer is very simple. The first thing you need to know about both is…​ how to quit.

That is right. Neither Emacs nor Vim are intuitive enough for new users to find a way out, and I myself have stressed enough as to reboot a computer after launching them. Yes, been there, done that. I cannot blame people who just cannot find a way out of some piece of software, and just reboot their machine as a result.

So, let us begin by the basics:

First, open a terminal window. If you are in Windows, that is usually called a "Command Prompt." If you see something about Powershell, just do not even go there. In Linux and macOS and most other Unixes like Solaris, Raspbian or BSD, it is usually called "Terminal." In any case you should have a black window in front of you, with a blinking location where you can type commands and then hit enter to get them executed.

The most basic interface ever invented to control a computer, more than 60 years old, but still the most reliable and with the least amount of ambiguity. Users of Siri and other "intelligent assistants" know what I am talking about.

Then, launch either application; use the $ emacs or $ vim commands, and then hit the Enter key.

In this book I will use the $ sign to indicate a command that must be typed on the command line. We will call it "the command prompt" where you type commands to be executed.

Wait for the applications to launch, and do not touch the keyboard, at least not for the moment.

If you launched Vim, just hit :, then Q and finally Enter. Boom, you are out. Yes, there is a very popular answer on Stack Overflow that explains this. If you had touched the keyboard inadvertently before typing :q, then try hitting the Esc key, and then try typing that command again.

If you launched Emacs, you need to hold the Ctrl key on the keyboard, and then type in sequence X and then hit C (without stopping the pressure on the Ctrl key.)

That is right. To leave Emacs you need to twist your left hand so that your little finger keeps the Ctrl key down, and then your third and second fingers play a short arpeggio, going from the X to the C. It is very much like playing the piano, indeed. And yes, there is a page in the Emacs manual that explains this.

If for some reason you type something else and get lost, do not panic; hit Ctrl+G as many times as needed, and try again.

In both cases you should see your terminal prompt, just like before. You should repeat this simple exercise a few times, in either editor, until you feel comfortable with the sequences.

Hey, I told you that these editors were heavily keyboard-oriented. And hey, I told you that exiting these editors was a major "rituel de passage."

But now you know, at least, how to quit.

Both Vim and Emacs have the concept of commands. Type a command, and hit the Enter key. Just like the terminal that you used to open them, Vim and Emacs will let you enter commands, to load, modify and edit your text. There are a lot of commands in both editors. But you do not need to know more than a few in each.

As you can see, there are several keys that are extremely important in your keyboard and that probably you have not used that much until now.

Vim uses the Esc key all the time.

Emacs uses the Ctrl and Esc keys all the time. But the Esc key is usually referred to as Meta. We will see more about this later.

3. I Think I’m Paranoid

Another command that works in both Emacs and Vim is the one that tells you their current version. Think of it like the 70s idea of an "About Box."

In Vim, just :version while in Normal mode. In my machine that yields something like the text below, followed by the list of activated features and other informations:

VIM - Vi IMproved 8.1 (2018 May 18, compiled Oct 29 2018 06:55:58)

In Emacs, just Escape, X and then enter version at the prompt. This is what I see when I do that:

GNU Emacs 26.1 (build 1, x86_64-apple-darwin18.0.0) of 2018-08-19

Very, very, very recent versions. Both installed with Homebrew on my Mac.

4. Close To The Edge

The second most important thing that you need to learn when using either editor is how to actually write text in them.

Let us try a simple exercise: open GNU Emacs and try to type something on it. By default, it shows a copyright screen, which might even include a colorful Emacs logo on it, but you keep typing and no word appears on the screen.

In Vim, it is actually weirder, because no word will appear unless you happen to hit the I or A letters, at which point, whatever you write appears normally on the screen.

Let us see what is going on in each case.

For Emacs, the solution is to start a new "buffer". Because it was designed before Windows and Mac OS X, Emacs has rather unconventional meanings to common concepts; for example:

  • What you would call a "file" on any modern text editor, is called a "buffer" in Emacs.

  • What you would call a "window" on any modern operating system, Emacs calls it a "frame."

  • What you would call a "cursor" nowadays, Emacs calls a "point."

So, as mentioned above, we need to create a new buffer. How does one do that? Hang on tight and prepare your fingers to dance:

  • Hold the Control key with your left little finger and simultaneously hit X.

  • Leave the Ctrl key alone and hit B.

For the sake of convenience, we are going to refer to this combinations as Ctrl+X, B from now on. The comma indicates that you should withdraw your fingers from the keyboard before hitting the second sequence.

You should see a message appearing at the bottom of the Emacs screen starting with the text Switch to buffer. You can type a name for your new buffer there, hit enter, and voila, you can start writing now on a clean slate.

Now leave Emacs with the sequence that you already know, the (in)famous Ctrl+X, Ctrl+C. Boom, you are gone, and your changes are lost.

Not very nice from Emacs' part to leave without warning us of unsaved changes, if you ask me. We will solve this issue in a bit.

In the case of Vim, one has to understand that this editor works in "modes." Whenever a mode is activated, the whole keyboard reacts differently. And to know in which "mode" one is at any time, the bottom side of the window gives some visual cues.

When you start Vim it is, by default, in what is known as Normal mode. In this mode one does not write text, but operate on it; that means one can navigate it, delete it, copy it, paste it, insert it, save it to and load it from disk. Many keyboard keys are "wired" to perform these tasks by default, and for many others, there are specific commands one can type and execute.

For example, you already know the :q command, which is a shortcut of the :quit command, which basically makes Vim exit. To be able to write that command, one must be in the Normal mode; otherwise, your file would have the text :q inside it!

To actually enter text on a document, one must enter the Insertion mode; in that mode, the keyboard behaves basically just like in any other text editor.

How does one go from Normal to Insertion mode? Hitting the I key.

And how does one escape the Insertion mode and go back to Normal mode? Using the Esc key. The interesting property of the Esc key in Vim is that it is idempotent; that is, you can hit Esc many times, and you will stay in Normal mode.

Try it now; hit I and then enter some text.

Then hit Esc and you are back in Normal mode. Hit Esc again, and you are still in Normal mode.

Repeat this sequence a few times.

As a rule of thumb, every time I will ask you to type a command, you must remember to switch to Normal mode first, using the Esc key.

Then type :q and try to leave the editor: of course you cannot! Because you have modified the contents of the file, Vim asks you to save them. You would not want to lose data!

But we do not yet know how to save files, neither in Emacs nor in Vim, so we will leave our windows open until next chapter.

5. Protection

Let us not lose all of those hours of work, please.

In Vim, hit Esc to go back to Normal mode, and then type the command :w filename.txt. This will write the contents of the current buffer into a file, aptly named filename.txt. Where is this file located? Well, in the current working directory, of which Vim can tell us more about, typing the :pwd command.

In the case of Emacs, just hit the sequence Ctrl+X, Ctrl+S, and then enter a filename. The result is the same. And similarly, to know where on the disk the file has ended up, hit Esc and X key, and finally write pwd. You will see the same information.

In case you did not know, pwd stands for "present working directory."

Nice! The same commands in both editors yield the same ideas, because pwd is just a very well known command in Unix systems.

But wait, what was this Esc+X sequence? We will come back to that a bit later on.

In any case, now that we have saved our work, we can leave the editor safely. Just :q or Ctrl+X, Ctrl+C, whichever editor you happen to be using.

6. Ticket To Ride

Let us write a longer text. A couple of screenfuls of text, at least. You could probably copy the text of this chapter, for example.

Invariably, at some point your cursor will be unbearably low on the screen. That happens all the time. Despair not. I love to see the emptiness of the page in front if me, instead of a screen with lines and lines of text.

In Vim, go to Normal mode and hit the Z Z sequence on the keyboard. There you go, your cursor is in the middle. Want it on top? Z T then. Or again at the bottom to quickly review what you just wrote? Then Z B and you are done.

In Emacs, it is even simpler. Just Ctrl+L your way to the bottom, middle, top, and back to the center of the screen. I usually do this while listening to music.

7. I Like To Move It

But sometimes you actually want the cursor somewhere else in your text. For those situations, both editors have wonderful shortcuts to move around. Of course, you can use the arrow keys in your keyboard (but not in Vim’s Insertion mode!) but sometimes not leaving your hands from the keyboard is simpler and nerdier.

All of these tips work in Vim Normal mode, so make sure to hit Esc before you try them:

  • You can go to the beginning of the text at any time using G G, and Shift+G will do the exact opposite, taking you to the bottom.

  • You can move around the text using the H, J, K and L keys. That is right, the ones right below your right hand on the keyboard. J goes downwards, K goes upward, H goes to the left, L to the right. It takes a while to get used, but once you become confortable with them, you will always want to do this.

  • You can go faster, word by word, using the W key to go forward, and the B to go backwards.

  • And if you need to go super faster, like page after page, just use Ctrl+D to go down, and Ctrl+U to go up.

  • Go to the beginning of the line using 0 (that is the "zero" key!) and to the end of a line using $.

The same tips for Emacs, with somewhat different keystrokes:

  • You can go to the top of the document using Esc, <, and to the bottom of the document using Esc, >.

  • You can move around the text using the Ctrl+N and Ctrl+P (to go up and down) and Ctrl+F and Ctrl+B (to go forward and backward).

  • To move word by word, try Esc, F and Esc, B to go forwards and backwards, word by word.

  • To move in pages, Ctrl+V goes down, while Esc, V goes up.

  • Go to the beginning of the line using Ctrl+A, and to the end using Ctrl+E.

I know, I should probably make this chapter more interesting than just a few bullet points, but these shortcuts are just stuff you have to learn by heart. So type some text, and navigate around it using these keystrokes. Rinse and repeat until you feel comfortable. There is no other way.

8. The Power Of Love

The biggest advantage of using a computer as a typewriter is, without any doubt, the invention of undo and redo. It is the closest thing we have so far that looks like traveling in time, making us able to change previous actions and make better things.

In the case of Emacs, just Ctrl+/ (forward slash) to undo, and Esc, _ (that is an underscore down there) to redo. Yeah, I know, weird shortcuts.

To undo in Vim, go to to Normal mode and hit U. Then hit U again to redo. Undo, redo, undo, redo. Easy.

Wait, what? Just one single level of undo? This is 2019, for life’s sake.

Well, yes, the thing is that Vim, by default, runs in compatible mode. Compatible to what, you ask? Well, compatible to vi, a text editor created in 1976 by Bill Joy, one of the cofounders of Sun Microsystems, now part of Oracle. The name "Vim" actually stands for "vi improved"; but by default, Vim sticks to the behaviour of vi.

How does one get Vim to actually drop that compatibility? Well, go to Normal mode, and type the :set nocompatible and you are done.

Having done that, try to undo several times hitting the U command. Nice, huh? To redo, just use Ctrl+R. Undo, undo, undo, redo, redo, redo. Much better.

But as soon as you exit Vim, the nocompatible setting is lost, and you have to remember to set that up again every time you launch the app, which is sad and boring and stupid. Cannot one just set that in an initialization file and get done with it?

Why yes, of course you can.

Act II: Crescendo

People sometimes ask me if it is a sin in the Church of Emacs to use vi . Using a free version of vi is not a sin; it is a penance. So happy hacking.

— Richard Stallman

9. Are You Gonna Go My Way

Just like any other well-behaved Unix tool, both Vim and Emacs have their respective configuration files, where one can dump commands to be executed at startup.

In the case of Vim, it is called ~/.vimrc.

In the case of Emacs, it is called ~/.emacs.

Anything you add into those files will be executed at startup. But what should one write in those files?

In the case of Vim, one must use a programming language called "Vim script" or VimL. In the case of Emacs, one must use another programming language called Emacs Lisp. Both are fully fledged programming languages, each with a manual and lots of tutorials online.

Learning these programming languages is outside of the scope of this book; you are more than welcome to learn them if you want. Instead, I am going to show you what instructions you should add to your init files so that the editors do what you want.

So let us create a ~/.vimrc file with this command: $ vim ~/.vimrc. And then enter the following:

set nocompatible

Close and reopen Vim, and voila, undo and redo work just the way they should in 2019 every time you open Vim.

10. Hyper-Gamma Spaces

I have this rule of thumb: if an editor is used to write code, it must show a gutter with line numbers on the left side. This is the thing that I always enable first in pretty much every single code editor I come across. What I do not understand is why this setting is usually turned off. It should be always turned on. Always.

And Vim and Emacs are no different. The line numbers are not visible by default. Seriously? Seriously?

For Emacs we are going to create our initialization file, using Emacs: $ emacs ~/.emacs. Then write the following:

(global-linum-mode t)
I leave as an exercise to the reader to try to $ vim .emacs and $ emacs .vimrc. It is even better with alcohol or some forbidden substance in your blood. Nah, I am kidding. Do not do drugs. Seriously.

If you close and open Emacs now, what you see is quite disappointing; the line numbers sticking to the text! Really ugly. Any possibility to fix that? Of course!

(global-linum-mode t)
(setq linum-format "%4d ")

The second command adds some space between the line numbers and the text.

For Vim, it is much, much simpler:

set number

And now we have a nice code editor with line numbers.

11. The Great Escape

By now it must be obvious that both Vim and Emacs have this love affair with the Esc key.

For Vim it is quite obvious what it does, offering a way to jump to the Normal mode. But I admit that for Emacs it is kind of clumsy to have to type it, then remove the finger, and then type another command to do something.

Let us fix that in our new .emacs configuration file:

(setq mac-option-key-is-meta nil
      mac-option-modifier 'none
      mac-command-key-is-meta t
      mac-command-modifier 'meta)

The lines above tell Emacs to use the Command key of the Mac keyboard as the Meta key. This means that now, instead of typing Esc, X we can do Command+X, which is a bit easier to type. You can try with the previous commands you learnt, they all work both ways.

This particular combination of keys will be henceforth referred to as Meta+X; memorize it, because you will use it quite often.

You could map the Option key instead, but the problem is that in the Mac one can use this key to enter characters such as ™, £, ® and µ. Hence, the Command key mapping. instead. We do not want to lose the possibility of typing weird characters in our documents.

12. No Line On The Horizon

But that is not all; I also want to highlight the current line I am currently editing. These visual cues are always useful when I return to the editor from another application.

In Emacs, just

(global-hl-line-mode 1)

Thankfully for Vim it is just as simple:

set cursorline

You can also jump from line to line: in Emacs hit Meta+G, G and type the line number. In Vim, type the line number and hit Shift+G. And we are done.

13. The First Cut Is The Deepest

These editors are made to be used with the keyboard; this means that one has to learn to select some text with the keyboard, and then perform some action with the keyboard to cut, copy and paste the text with the keyboard. With the keyboard.

To select some text on Vim, just go the Normal mode and hit the V key. This will put Vim into a third, yet unknown mode called "Visual"; in this mode, one can select parts of the text.

To select the text, just move the cursor with the movement keys, the H, J, K, and L combo. Then you can cut it with X, copy it with Y, and paste it after the cursor with P. You can also use Shift+P to paste before the cursor.

If you change your mind and want to leave the Visual mode, just hit Esc and you will be back in Normal mode.

Remember how Emacs had different words for file, window and such? Well, the reason Vim uses the Y to copy is because it refers to the word "yank." This word is relatively unknown to non-native English speakers, so here is a definition:

yank | jaŋk | informal
verb [with object]
pull with a jerk: her hair was yanked, and she screamed | he yanked her to her feet | [no object] : Liz yanked at her arm.
noun [in singular]
a sudden hard pull: one of the other girls gave her ponytail a yank.
ORIGIN
late 18th century (as a Scots word in the sense ‘sudden sharp blow’): of unknown origin.
— Source: macOS 10.14 "Mojave" Dictionary

In the case of Emacs, hit Ctrl+Spacebar. Move your cursor, select text, and then Ctrl+W will cut, Meta+W will copy, and Ctrl+Y will paste it. The y in this case does not mean yanking. No idea what that means, actually.

Now you know how to repeat blocks of text ad nauseam. Now you know how to repeat blocks of text ad nauseam. Now you know how to repeat blocks of text ad nauseam. Now you know how to repeat blocks of text ad nauseam.

One last tip: if you need to select the whole text of the buffer, Emacs requires you to use Ctrl+X, H, while Vim will do that for a G, G, V, Shift+G. In the latter case, one is litteraly telling Vim to "go to the top, get in visual mode, and then go to the bottom." Which does the trick.

14. Yuri Writes A Poem For Lara

When I was a kid I used to go to my mum’s job after school, and sometimes spend the afternoon there.

She was an executive assistant in a public company in Argentina in the 80s, and she could type more than a hundred words a minute on her IBM Selectric 196C typewriter (the Sandstone Beige version.) She was so fast, she was one of the few in her company to take dictations from her boss on the fly, directly on the typewriter, without needing a dictaphone, and I thought that was insanely cool.

The Selectric was quite an advanced electric typewriter when it was introduced. Instead of using the usual "hammers" used since the end of the nineteenth century, IBM had invented a "typeball." This device had one particularly impressive quality: being unable to jam the typewriter, by design. It also produced a very distinctive typing sound, one I can still hear today in my memory.

In 1989 I took touch-typing lessons in school. My class had rows and rows of quite old mechanical typewriters of various manufacturers, some of which were true relics of the 1930s and 40s. They were 100% mechanical, most of them had jammed keys, and it would really hurt our hands to use them. The noise in the room was unbearable, and our teacher was constantly watching us, to make sure nobody in the class looked at their hands while typing.

We were graded both by the correctness of our writing, and by the time we took to finish our exercises. After 8 months of training, I became a touch typist, but not as fast as my mother, at least not on those old typewriters.

Once or twice, however, I trained my fingers on her Selectric typewriter. The feeling was unparalleled. That machine could fly. And it was loud. Pages would look extremely elegant, and you could even change the font (by replacing the ball) and even delete characters! There was a "backspace" key on them. I still want one of those machines. One day I will have it.

Sensing the evolution of times, my mum took MS-DOS, WordStar and Lotus 1-2-3 lessons in 1986. But we did not have a computer at home; they were insanely expensive in Argentina back then, and during times of economic crisis one focuses more in the lower levels of the pyramid of Maslow.

I still have her notes and her Xeroxed copy of the MS-DOS book she brought home. I actually used it to learn how to operate MS-DOS in my first PC, when we moved to Switzerland and she could afford to buy me one in 1992.

At that time, IBM PC keyboards were inspired on the Selectric typewriter – and were as noisy.

I now use a Das Keyboard Ultimate at home, and it is the best keyboard I have ever had. But my wife closes the door of my office when I am typing. It is really, really noisy.

The command line was present in 1986 and 1992. There were commands to manipulate text in WordStar. There were commands to manipulate numbers in Lotus 1-2-3. There are commands to manipulate words, lines and paragraphs on Emacs or Vim.

WordStar had lots of famous users. I can understand them. Famous coders use Emacs and Vim daily, like Steve Yegge. Some tools stand the test of time and become classics. Emacs and Vim definitely belong to those; maybe the fact that they were free and open software saved them from oblivion.

You can still download WordStar and Lotus 1-2-3 and install them in a VirtualBox virtual machine and relive those days. I do that as a hobby sometimes. I know, I know.

In my mind, interacting with a computer will forever consist of typing a command, and hitting the Enter key.

15. Letter From Home

By the way, ever wondered why the J and F keys in most western keyboards have a small notch? It is because you are supposed to rest the index fingers of both hands on top of them while you are not writing. That little feeling when your indexes move back to the home row (that is, the row starting with A S D F G…​") means that…​ well, your hands are home again.

What I never understood, on the other hand, is why the keys are vertically twisted; that is, why is it that the T is not exactly on top of the G, itself not exactly on top of the B? Why the twisted angle? Never quite got that.

I understand that the twisting had a reason to exist at the time of the mechanical typewriter; but no more these days. This is why the ErgoDox EZ and the Keyboardio Model 01 look like excellent ideas to me.

And they are ergonomic keyboards, too; but I will talk about that in chapter "Shape Of My Heart."

16. Queremos Pastel

Just like using good old scissors on paper, one can cut rectangular portions of text quite easily with these editors.

For Vim, just use Ctrl+V to get into "Visual Block" mode. Then move your cursor, cut and paste. Just hit Esc if this is not what you want.

For Emacs, the sequence is Ctrl+X, Spacebar. Move your cursor, and voila. To stop this operation at any time, use the usual Ctrl+G sequence.

17. Piano Bar

The newest laptops from Apple have two absolutely horrendous features for Vim and Emacs users:

  1. The Touch Bar. Like, seriously.

  2. The "butterfly" keyboards.

Mac laptop keyboards already had a big problem before the butterfly mechanism, anyway: the Fn key, occupying the location where the Ctrl key must be. This is an old problem for all machines since 2000 at least.

In the case of butterfly keyboards, I admit the 2018 version is much better than the first iteration in 2016. But still not good. It is a matter of taste, and this is a purely subjective opinion. You are free to skip to the next chapter if you do not agree with me. Please do not tweet me of mail me to tell me that you disagree, by the way. I could not care less. It is a shitty keyboard, end of the story.

Its major problem is its very short key travel. And when those keys get stuck it is even worse. Which is absolutely ridiculous when you pay such a price for a computer. It is even more infuriating because Macs had quite good keyboards until 2012; since the Retina displays their quality has been going down.

The Touch Bar is ridiculous and not geared towards "pro" users. It might be useful for editing video or adding emoji to your documents, but other than that they have major implications for touch typists:

  1. The function buttons are gone. You can thankfully set the bar to always display the row of function buttons, though, which is what I have done.

  2. You cannot "feel" the buttons anymore with your fingers, which is precisely the whole point of a keyboard. Touch typists do not look at the keyboard, they feel it as they type. With Vim and Emacs, not being able to feel the Esc key is a real problem.

These days I wish I had a Lenovo ThinkPad. Now that is a nice laptop keyboard – and of course, its design goes back to…​ IBM. Once again, setting the standards of how a keyboard should work.

In any case, since I am still working in the field of iOS applications, I have to have a Mac. As powerful as the latest iPad Pro is, and in spite of everything that Apple says, one cannot use them for application development. At least not yet.

Maybe the future of writing in the world of Apple does not include keyboards at all; maybe we will have to talk to Siri to get things done (imagine that in an open space office.) Will be dictate code to Siri? Can you imagine dictating C++ code?

– Hey Siri!
*Siri sound*
– Create a new C++ file
– OK, file created. Dictate the contents and whistle twice when you are done.
– Hash include iostream, new line, new line. Create function int main, no parameters. Function body is cout pipe pipe string Hello World. Semicolon, new line. Return zero, semicolon. End of function body.

And then you whistle twice, Siri compiles the file and executes it. Boom, you can program on an iPad. Or maybe we will have to draw the characters with our fingers?

In any case, I hope to switch to FreeBSD by then, to get rid of GUIs driven by companies without respect for keyboards. Maybe I should start an association in defense of keyboards. Or a keyboard museum?

I even dropped Apple’s Bluetooth trackpads for a good old plain Microsoft mouse, worth 30 Swiss francs. I went back to real basics. Apple’s designers have completely lost touch with developers and touch typists. Or maybe they just do not care about them anymore. They do not generate enough cash, that is the problem.

18. Allegro Ma Non Tanto

For some strange reason, I have lots of musician friends. I say strange because, well, I myself I am not a musician. I took some piano lessons once, but I never spent enough time on the piano as to become proficient, and I just know a handful of songs – or at least I used to know them.

I was often with those friends during their rehearsals, or even in backstage zones as they were about to perform. Many of them thought that I was just another musician, because musicians tend to hang out with other musicians. So jokingly I would tell them that I played keyboards. "Oh yeah, which one?" they would ask, and I would say "the 104 keys kind."

Lame joke, I know. I still think that these keyboards are instruments that can be played to perform art, and sometimes art happens.

I like to write, simply and purely, without direction. I sometimes just open a text editor and start pouring words. I let the fingers drive the narrative, without attention to the flow or the contents, in Spanish, but also in English and French, which are the three languages I can write most comfortably with. I have Emacs set in a "writing mode" of my own, with musikcube playing in the background, all in the same tmux session.

In another pane I can run the scripts required to turn this manuscript into other formats, for people to read or download. In yet another pane I use w3m when I need to do some web browsing. I can use Emacs to read EPUB files from my Calibre library. I even use Emacs as an RSS reader.

I guess in a few years I will just install FreeBSD in a ThinkPad laptop and move all of my workflow around the keyboard. But for the moment I got myself a Tuxedo InfinityBook Pro 14'' with Ubuntu Budgie and could not be happier.

I figured out that this love of the keyboard is not just a question of productivity, because I sometimes still get things done faster using the mouse. It is actually a sensation, a feeling of freedom of expression. I can express myself better with a nice keyboard. Like the Das Keyboard I am using as I write these lines.

There are other projects I work at the same time these days, so I navigate from file to file in Emacs using Ctrl+X and the or keys, and in Vim I open those files in tabs using the :tabe command, and then use G T to go from tab to tab in Normal mode.

And the best thing is, they do not consume much memory, and they are respectful of the environment, being easy on the battery of my laptop.

Is this not the definition of sustainable computing?

19. Everything Counts

In September 1990 I was in high school in Argentina, preparing to pass the exams of the "Baccalaureat International" of Geneva. As a part of the preparations towards obtaining that degree, we had an orientation session where teachers explained us the kind of ideas leading to a successful thesis project.

The thing that I remember the most of that day was one of the requirements for such a thesis project: the final document had to have between 14'000 and 15'000 words.

It was the first time I had heard of such a requirement. I did not know that it was common for academic documents to have standardized lengths. But back then I thought to myself, how does one keep track of words in a typewriter? Well, it turns out that in old times, one would count words line per line, write that next to the line in question, and add the total manually with a calculator. In 1990 there were not that many computers in operation in Argentina.

Of course, the existence of WordStar, Emacs, and Vim made such procedures more than obsolete, and thankfully so. These days in Emacs, just highlight the whole document using Ctrl+X, H, and then get statistics using Meta+=. At the time of this writing, Emacs tells me I have poured over 7'400 words.

Vim does not have such a command by default, but one can use the standard wc Unix command to get that information, invoking it directly from Vim: :!wc -w % will get that information for you. Commands that begin with ! are actually executed by the operating system, not by Vim itself. The -w parameter asks for just the number of words (otherwise you would get the number of lines, word and characters, in that order) and the % parameter means "the current buffer."

20. La Grasa De Las Capitales

You may have noticed that all the titles in this book Have Capitalized First Letters, right? Well, the truth is that while writing the book I forgot to capitalize them, so I just went back in Emacs and hit the Meta+C sequence, which does that for each word and moves the cursor to the next word.

You can do something similar in Vim using the ~ ("tilde") key, and then using W to move to the next word, until your title is all capitalized. The ~ key, however, toggles every character from uppercase to lowercase; so beware of any word already capitalized, as it might undo that for you.

Of course, this is super useful in German, where nouns are always capitalized. But it also shows how much computers are tailored for western languages. Maybe other scripts and alphabets do not have such capitalization rules, and thus do not care about this matters that much.

If you want to turn a word to FULL CAPITALS just use Meta+U in Emacs. In Vim, select the text and hit the Shift+U key in Visual mode.

For the inverse operation, to change text to lowercase, just Meta+L in Emacs and U in Visual mode on Vim.

Pay attention to the fact that the U key has radically different functions in Normal and Visual modes: in the former it drives the "undo" function, while in the latter it turns text into lowercase. And, of course, in Insertion mode…​ it inserts the character u!

21. I Want You (She’s So Heavy)

As I said before, we did not have an IBM Selectric typewriter at home. But we did have a venerable, original Remington Portable #2 typewriter, built around 1925, that my grandmother had brought from Europe to Argentina before the Second World War.

I remember when I was a kid, my grandmother still using it to write letters to relatives in Europe, or even to fill tax forms.

By the time I started using it, this machine was around 60 years old, it was still working with its original ink strip (!), it was heavy, and the hammers would jam if you typed too fast. There was a "maximum cruise speed" that you could achieve with it; more than that, and you had to unstick the hammers.

The keys were super hard to press, particularly for little fingers. The A and the ; (yes, it had an American QWERTY layout) were almost impossible to press. You could feel the strain in your fingers after using it. To give you an idea of the finger workout required to operate these machines: the shift key actually did raise the whole typing cylinder. The shift key in my 1952 Olivetti Lettera, in contrast, raises the typing elements, which are way lighter. Smart choice, Olivetti!

Sadly we could not bring that Remington typewriter with us when we moved to Europe in 1991. It was way too heavy and old, and I do not have the slightest memory of what we did with it. Probably sold or given away.

22. The Wall

I mentioned previously that my mother was a fast and very precise typist. It was no accident, for she, like many other young women in the 50s and 60s, had attended the Academia Pitman in Buenos Aires, to learn stenography (also known as "tachygraphy") and typewriting.

When I was a kid we still had her books at home, explaining the life of the office to otherwise unsuspecting victims. How to write proper business correspondence, how to answer the telephone, and yes, even how to dress and behave in an office. I should have kept those booklets. They seemed to me so irksome and ridiculous, almost to the point of awe and laughter.

23. The Distance

As a writer, I really tried to like the iPad. I did. I actually went to New York to buy some when they came out in 2010, including most of their accessories, the most important of which was this weird keyboard for the first iPad, to be used in portrait mode.

The biggest issue was the on-screen keyboard. While the first versions could sustain speed typing on the glass, some later version of iOS (7, I think) broke this feature, and the onscreen keyboard became unusable to me. I think they added some "gestures" on the keyboard, which could not be turned off, and hence if you tried to type too fast, it would think one was "gesturing" instead of typing, and the whole thing was a failure.

Somewhere in 2014 I tried the Hanx Writer, that app created by Tom Hanks to simulate classic typewriters on an iPad. I really tried to use the iPad as a typewriter. I just could not. It is just not made for that.

Finally, having tried the iPad Pro and its new breed of landscape-mode keyboards, I have to say that I like them much more. Ironically enough, I think that the Smart Keyboard is the best keyboard that Apple offers right now, particularly when compared to the clusterfuck that is the 2016 MacBook Pro keyboard.

I nevertheless loved Ulysses in the iPad…​ even though nothing beats a good tmux + Vim session via ssh on Panic’s excellent Prompt. Even though the Smart Keyboard painfully lacks function and Esc keys.

24. True Colors

By now you might be tired of those spartan colors in your terminal. Maybe you want some pizzazz in your editor? Your wish is my command. For the sake of terminology, what Vim calls "color schemes" Emacs calls "themes".

Vim requires you to switch to Normal mode and :color blue. And now your background is blue. If you are in nocompatible mode, you can hit the Tab key a few times after :color and you will see the names of many other color names available.

To go back to the same good old color of yesteryear, just :color default and boom.

For Emacs, hit Meta+X and then write customize-themes. Hit Enter and you will be shown a screen with a list of themes. Move your cursor down and hit Enter on the "deeper-blue" option. And here we are, same colors in both editors. Hit Q when you are happy with the results.

To return to the default theme, just Meta+X and disable-theme. Hit Tab (or enter the name of the theme you selected) and Enter. Black and white is back.

These are not the only possible themes available, mind you; you can install many more from a variety of sources, including the beloved classics Solarized and Dracula.

For your browsing pleasure and color shopping, here you have a gallery of Emacs Themes and another one. There are quite a few collections of Vim color schemes too, for example Rainglow and many other awesome ones. Vim has lots of colors to choose from.

Be your own Picasso.

25. My Culture

My friend Max told me once that I am a "computer vegan." And he told me that more than 5 years ago! The truth is, I have weird computer habits. Well, if you are reading this book it means that you share at least part of those tastes with me, namely Emacs and Vim.

For example, I do not use Google anymore, and have not for the past 6 years at least; I always, always, always search with DuckDuckGo, which provides excellent results and does not sell your data to third parties. And I do not use Chrome, but Firefox. Even on my iOS and Android devices, I use Firefox. I use 1.1.1.1 in my devices, and generally browse with TunnelBear VPN turned on.

Needless to say, Facebook is also in this black list. Whatever they do, I piss on it.

I do not buy books from Amazon; I prefer to buy my books directly at the publisher’s websites, to support them directly without feeding the biggest intermediate of all times. In general I do not buy eBooks with DRM, so that I can read them in any device I want, using the excellent Calibre tool to organize – and also to share my library with others who want to read the same books I read.

I write most documents as Markdown or AsciiDoc, and then translate them to other formats using Pandoc or Asciidoctor. Sometimes I use LibreOffice, but not that often.

I consider these steps as my small contribution towards a better world; like deciding not to buy more plastic bags, or eating organic (all things we do with my wife in our everyday life.) You can decide to do differently, but I hope that you will also do your part. The planet needs it.

And, similarly, I think the web needs us to think differently, and, instead of concentrating power in the hands of a few platform vendors, to actually favor diversity of platforms and tools. The web needs it.

(Surprisingly for some, I am not as hardcore on free and open source software; that means I gladly pay money to independent developers for software that I find excellent and useful, even if the source code is their propriety and not freely available. I do not agree with everything Stallman says, but I respect him greatly, and I think his hardline stance is required and most of his ideas are simply the right thing to do.)

This is why I boycott Medium as much as I can, writing my own publication De Programmatica Ipsum with my friend Graham (who is, to a large extent, responsible of my happy transition to Emacs.) I encourage others to start their own publication platforms, because that is what the web is about: decentralization and diversity.

The fact that pretty much everybody writes and reads only on Medium is the thing that is actually destroying the web – and not URL shorteners.

Using Vim and Emacs I can take my writing skills and my editor configuration from Linux to macOS to Windows almost without change, and I can be as productive. The same applies to Calibre, Firefox, LibreOffice, Pandoc, Asciidoctor, and many other tools.

The freedom I enjoy the most is being able to use different operating systems with my preferred tools, using file formats that will stand the test of time.

26. Give Out But Don’t Give Up

Let us say you have a nice command-line tool that does something you wish you could easily integrate in the text you are writing, in either Vim or Emacs. Can you add a command to these editors to get that information?

The answer is: you do not need to. You can insert the output of pretty much any command in Vim and Emacs, doing like this:

In Emacs, Ctrl+U and then Meta+!, and type the command. Emacs will execute it, and the output will go directly where your cursor is located.

Same thing in Vim: switch to Normal mode, and :r !command – pay attention to that exclamation point! It means that the command is an external tool. The result will be automatically pasted in your current text.

This opens the door to incredible combinations, where you can reuse all the knowledge of your Unix toolkit into your preferred editors. Try now with common, simple Unix commands such as ls, date or ps -eaf.

27. Break & Enter

Sometimes, instead of inserting a command, one just wants to insert the contents of another file in your current work. Maybe you keep a file with code snippets that you would like to embed in your program, or a collection of quotes.

In Emacs, Ctrl+X, I. Enter the filename, and you are done.

In Vim, switch to Normal mode and :r filename and you are done. (Yes, it is the same command you used in the previous chapter! :r is actually a shortcut for :read.)

In both cases, you should see the contents of that other file inside your current one. Which is what we wanted to do.

Act III: Accelerando

I use Emacs, which might be thought of as a thermonuclear word processor.

— Neal Stephenson

28. Packt Like Sardines In A Crushd Tin Box

These days, every software platform must have their own package distribution thingy. Rubygems for Ruby, PIP for Python, Chocolatey for Windows, NuGet for .NET, CocoaPods for Xcode projects, Homebrew for macOS, you get the idea.

Emacs is not the exception. Add the following snippet to your .emacs file to initialize MELPA, the official Emacs package manager:

(require 'package)
(setq package-archives
      '(("GNU ELPA"     . "https://elpa.gnu.org/packages/")
        ("MELPA Stable" . "https://stable.melpa.org/packages/")
        ("MELPA"        . "https://melpa.org/packages/"))
      package-archive-priorities
      '(("MELPA Stable" . 10)
        ("GNU ELPA"     . 5)
        ("MELPA"        . 0)))
(package-initialize)

After saving these changes and relaunching Emacs, you will be able to install packages; but first, refresh the local cache of available packages with Meta+X and package-refresh-contents.

And then install packages simply using the package-install command.

For Vim, there are many options available, but I use the simplest possible, called Pathogen. Install it with

$ mkdir -p ~/.vim/autoload ~/.vim/bundle
$ curl -LSso ~/.vim/autoload/pathogen.vim https://tpo.pe/pathogen.vim

And add the following line to your .vimrc

execute pathogen#infect()

To install plugins, just clone their Git repositories in the ~/.vim/bundle folder, and they will be automatically loaded when you open Vim.

We are going to use some well-known packages and plugins in the coming chapters.

29. Get A Grip

I have plenty of Word 2.0 files I created around 1992 that I cannot reliably open nowadays. That pisses me to no end; of course back then I could not imagine that the binary formats of Word were so brittle! Microsoft themselves do not support their own old formats anymore, which means that a lot of information from those times is probably irrevocably lost.

That is the first great feature of plain text files. No matter what happens, you will be able to read them in the future.

But the second great feature is that they are easily "diffable;" you can easily see the difference between two versions of a file, which means that you can store all versions of them in a repository, for example, using Git. In older times one would have used Subversion, ClearCase, CVS, RCS, or God forbid, Visual SourceSafe; but in the category of version control systems, Git has absolutely won all the fights.

Both Vim and Emacs have excellent integrations with Vim, of course all based on keyboard shortcuts.

For Vim, just clone fugitive.vim, made by the same author of Pathogen, Tim Pope (who is by the way one of the most prolific authors of Vim plugins.)

If you open a file in a folder versioned with Git, fugitive.vim provides very simple commands to commit changes:

  • :Gst to see the output of git status

  • Stage files to commit using the - key

  • :Gcommit to commit changes

  • :Gpush to push changes to remote

In Emacs, just run Meta+X package-install and select Magit. Then add the following entry to your .emacs file to make it easier to use:

(global-set-key (kbd "C-x g") 'magit-status)

Then, whenever you edit a file in a Git repository, just type Ctrl+X, G, and this will open a separate window. In that window you can do the following:

  • Hit S to stage files to commit

  • Hit C C to commit file, entering a message

  • Hit Ctrl+C, Ctrl+C to actually commit after entering the message

  • Hit Shift+P, P to push changes to the remote repository

  • Finally, hit Q to dismiss the Magit window.

And now you can version your files, directly from your most beloved editors.

30. Find My Baby

This single feature is the thing that got me hooked to both Vim and Emacs, more than any other: the ability to quickly search for text anywhere in the text.

In Emacs, just go to Normal mode and hit the / key, and start typing some words. That is it. You will be taken immediately to the first occurrence of that text. Hit N and you will jump to the next occurrence. Hit Enter when you have found what you were looking for.

But with a few entries in .vimrc you can make this even better:

set incsearch
set ignorecase
set hlsearch

In Emacs, just use Ctrl+S and start typing. All the entries matching your search will be highlighted, and pressing Ctrl+S again you will jump directly to the next occurrence, and then again Enter when you have found your target.

31. Nouveau Western

Switzerland is a great country. I love living here; I love the trains in time, the excellent cheese, the breathtaking scenery, the friendliness of people. But some things are not so great.

In particular, I pray for the poor Swiss developers who have the bad luck to land in a company that gives them a keyboard with a Swiss layout to do their jobs.

Have you ever used a Swiss layout keyboard? For software developers it is just a catastrophe. It is like their designers saw an American keyboard and said, how could we make the lives of developers miserable? We will hide all symbols under impossible sequences requiring Alt Gr or other weird keys, just for fun.

You know bad keyboards can cause severe injuries in your wrists; but Swiss keyboards also cause bad luck, flu, movie spoilers, economic crisis, meteorites, volcano eruptions, and mosquitoes during sleep. All at the same time.

The Swiss keyboard is a feat and a case study in uselessness for software developers. I sometimes wonder if this is the reason why software development is not such an advanced industry in Switzerland. For a country that prides itself in precision, minutia, and correctness, one would think that Swiss software must have an incredibly high level of quality, always delivered in time and with an astonishingly low level of defects.

Actually, Swiss software is as bad as anyone else’s. It could certainly be better; the country’s colleges are among the best in the world, one of them even boasting that Einstein studied there. Not all schools can say that.

But of course all of this is just hyperbolae. The keyboard in itself has nothing to do with the fact that the Swiss software industry never really took off. It has more to do with a cultural love of hierarchies, which, in the age of agile teams, creates deep issues for team organisation. Melwin Conway said it very clearly 50 years ago:

The basic thesis of this article is that organizations which design systems (in the broad sense used here) are constrained to produce designs which are copies of the communication structures of these organizations.

— Melvin Conway
How Do Committees Invent?

Software created by highly vertical and structured social structures such as Switzerland will be…​ well, highly vertical and structured. For a country that only gave women the right of vote in the 70’s and with an annoying tendency to curl into a ball and weep, well, it is hard to open up to new ideas and to change.

And one of the things that should change is, without any doubt, that keyboard. What a mess.

The truth is, only American keyboards are comfortable enough to write code. Which is not surprising, since the computer industry was born there, and many early computers were American, and many programming languages have been designed with those keyboards in mind.

Look at the position of the apostrophe ', the forward / and back \ slashes, even the quotes " are easily reachable. And the best are the positions of the opening and closing square [ ] and curly brackets { }, conveniently placed on top of the Enter key. Is is absolutely magnificent. Typing C-like languages is a breeze, and one can write bugs faster with an American keyboard than any other…​ in particular the Swiss one.

32. Bedshaped

If you write code, at some point you will want to automatically formatted so that it looks good and it is easy to read. In both editors you need to select the whole text and then use a command to do that.

In Vim, switch to Normal mode, and then G, G, V, Shift+G, =.

In Emacs, Ctrl+X, H to select all, and then Ctrl+Meta+\.

And your code looks great now.

33. Changes

In 2007 I was finishing my Master degree studies, and I had to write my thesis.

The University of Liverpool, where I was studying, provided us with Microsoft Word templates for the task. After having written two or three pages in it I just could not stand it anymore. The thing would crash for no reason, it was clunky, heavy, and I could not version the files properly. Which meant I had no reliable way to return to a previous version of the document if needed.

I was telling this to Cedric, a colleague and longtime friend of mine, and he suggested I use LaTeX instead. I had never used it, and barely heard about it, so I gave it a try, and I was hooked from the first moment. It was plain text, which meant I could work with version control tools (back then Git was barely starting to be known, and I stored all of my work in a local Subversion repository.)

But the best thing was that the output produced by LaTeX was gorgeous, including those mathematical equations. I remembered all of the Word documents with Equation Editor thingies inside that I could no longer open; here was a pure text format, oblivious to the test of time, which yielded much more beautiful results. I had an epiphany, and happily wrote the 15'000 words, including code snippets, tables of contents, title page and appendices, in a format that worked incredibly well for me.

With a bit of tweaking, some special templates and help from countless webpages, I got to the point where I would write between 500 to 1000 words every day, no exception, 5 days a week, during a whole month. I could just type text, and I lost nothing. I could undo changes if needed, and I could divide my work in separate files. Each file had its own structure, with source code snippets taken from the original project I was working on, including syntax highlighting. Images were separate files, which I could edit separately if needed, without breaking the flow of the main document.

Even the bibliography was a separate file; a small database of books, papers, web pages and other articles, a small catalog of research, which LaTeX would dutifully read and process automatically for me at every build.

At the end, the table of contents, the table of figures, the mandatory bibliography, and the index would be automatically generated for me. All in all, a PDF file with 140 pages, lots of images and code, all processed and shown in a few seconds.

For this task, my main editor was TeXShop, and I managed the bibliography for my work using BibDesk. All of these tools were included in the magnificent MacTeX distribution, including even more tools in a single package.

And there was this geeky feeling of actually compiling my thesis into a PDF file. I even had a Makefile to drive the whole process in as few steps as possible. It was a fitting process for a Master’s thesis in software engineering.

The end result looked absolutely stunning, and I got myself a degree with distinction.

Of course, little did I know back then, but both Vim and Emacs have excellent support for LaTeX. I could have written my thesis with them, but TeXShop worked just fine.

34. 19 Dias Y 500 Noches

Every writer will tell you their trick to get words on paper. We all have different ones, because we are all different, and you should choose your own tools and rhythm, too.

It took me long to find a setup that I enjoy for writing books. My eBook Template project in Github is the result of those evaluations. At first I used LaTeX, but then I migrated all to Markdown and Pandoc, and lately I am using Asciidoctor for my writing.

I want my tools to let me build four major products out of my writing:

  • A fully formatted PDF file, ready to be sent to Lulu for self-publishing;

  • A nice EPUB file, without any kind of DRM, ready to be used in Apple iBooks as well as in other readers (like my beloved Kobo Aura H20);

  • A full HTML page, ready to be uploaded to a website;

  • And a Kindle file, for the poor souls stuck with those shitty devices.

And Asciidoctor fit all of this checkmarks and more, and this is the reason why I use it for my projects.

Even after finding a toolkit like this, you have to sit down and pour words on your text. Hence the 500 word rule. It is a simple one; every day, I sit down, I do a simple wc -w *.adoc on the command line, and I write at least 500 new words on my manuscript.

Do that for a month, only during working days, and you will end up with 10'000 words. Do that for six months, and you have a novel.

Of course every day I end up writing a bit more than 500. Sometimes I can do 3000 words a day, if inspiration strucks and I am in good mood. But the 500 rule is for the days where inspiration does not come, or when I am not feeling well. I stick to it because in those days, writing makes me feel better.

Like today. I did not wake up well, and after the 960 words I wrote, I feel much, much better now.

35. You Learn

Both Emacs and Vim come bundled with tutorials. In Emacs, as soon as you launch it you will see a welcome screen with a link to the tutorial. Use the Tab key to move the cursor on that entry, hit Enter, and learn more about Emacs. Otherwise you can Ctrl+H, T and access it at any time.

For Vim, the tutorial is a separate application called vimtutor. Open a command line window and type the command, and have a good read.

Interestingly, both tutorials spend quite a bit of time teaching how to navigate the text using the keys that you already know so well. But there is much more than that, and you can always learn a few new tricks.

If you have more questions after using the tutorials, you might want to ask them in the Emacs and Vim Stack Exchange websites, where you will most probably find your answer already posted there.

36. Future Is Promises

In order to explain how nature works at the level of elemental particles, Richard Feynman created a really cool type of diagram to explain some quantum physics phenomenon. Because when a subatomic particle undergoes a certain change, the universe splits in two, and two parallel realities exist simultaneously. The fact that these two realities can coexist is required for the whole universe to conserve some kind of momentum or quantity, and it is sacred bread for science fiction writers.

What i am about to show you is the feature that makes people the most jealous about Vim and Emacs. It has to do with the fact that undo and redo are not just like "traveling in time" – they are more like traveling in parallel universes.

In Emacs, use your package installer and Meta+X package-install and then undo-tree.

Add the following configuration in your .emacs now:

(global-undo-tree-mode)
(setq undo-tree-visualizer-diff t)
(setq undo-tree-visualizer-timestamps t)
(global-set-key (kbd "<f5>") 'undo-tree-visualize)

Restart Emacs, open a file and write some text. Undo some text and change it. Then undo again and change some more somewhere else.

Press F5. A tree of all the parallel universes of your text appears. Use the usual movement keys to go back and forth; when you reach a branching point, use the left and right arrow trees to decide which future to follow. Now go down that path. You can close the undo tree hitting Q.

Undo trees are one of the greatest inventions after undo, just like traveling through parallel universes is so much cool than traveling through time.

In Vim, install the Gundo.vim plugin using Pathogen, and then add this to your .vimrc file:

let g:gundo_close_on_revert=1
let g:gundo_prefer_python3 = 1
nnoremap <F5> :GundoToggle<CR>

Restart Vim and do the same as in Emacs. Hit F5 and watch that undo tree unfold in front of you. Navigate. Explore different lives for your text. Make them evolve separately. Move around your text not only in length but in time, and now in parallel universes as well.

If you do not start using Vim or Emacs exclusively after seeing this in action, I think I will have failed my job of writing this book.

Of course, do remember that normal filesystems can only store one version of the text at a time. But Git can has branches, and you can use them to store those different versions…​ and you know how to use Git from Vim or Emacs now, so go on. Save those universes in disk.

37. A Remark You Made

Files, files, files everywhere. Every project is lots of files. IDEs keep you busy opening files all the time. Some have great shortcuts (think of the usual Shift+Option+O for "quick opening" files) but Vim and Emacs have an even greater feature: cross-file bookmarks.

Usually bookmarks allow you to quickly jump from one line to the other in the same file; cross-file bookmarks do that, and also open the target file if required. You can thus quickly jump from file to file, and from location to location within the same file, using the same mechanism.

Vim distinguishes in-file bookmarks with lowercase letters, and cross-file bookmarks with uppercase letters. How do you make a bookmark? Just switch to Normal mode and hit M, Shift+A wherever you are. Then open another file, and hit M, Shift+B in some location.

Now hit ', Shift+A (that is the apostrophe followed by the bookmark name in uppercase) and you will jump back immediately to the previous file. Hit ', Shift+B and go to the second.

If you use lowercase letters, those bookmarks will only work in that particular file.

Emacs has a unified system. Just Ctrl+X, R, M to set a bookmark, and then Ctrl+X, R, L to see the list of bookmarks. Select the one you want using the common pointer movements, and then hit Enter. You can set bookmarks in many different files and you can jump from one to the other in a single keystroke.

38. Shape Of My Heart

I used to think that Apple was the first to come up with the idea of an ergonomic keyboard, the 1993 Apple Adjustable Keyboard. Apparently Apple came up with it after they got sued by someone who got injured using normal keyboards. Seriously. Americans are weird.

But no, it turns out that there have been ergonomic typewriters already in the 1930s, and many computer makers produced ergonomic keyboards in the 80s. Who woulda thought?

But the winner in this category is undoubtedly Microsoft. They used to have white ergonomic keyboards back in the 90s, and they looked (and felt) great. These days they have less good ones; the biggest problem being the use of very shitty switches for the keys. The feeling is just not there anymore. But the feeling of having the hands resting on such devices is simply the best.

The most important thing in keyboards are the switches beneath the keys. Blue switches are the best. Clicky, noisy, but with incredibly nice feedback when typing. Feedback is everything.

39. One Tree Hill

Being able to quickly access files is one of those things we expect from editors. And usually we expect to have them easily accessible, with a simple keystroke, showing all the "siblings" in the current directory.

One of the most popular plugins for Vim serves exactly this purpose: NERDTree. And in the case of Emacs, this is brought by the sr-speedbar package.

Let us install it in Emacs using the common Meta+X package-install and then entering sr-speedbar. A few configuration items in our beloved .emacs configuration file will bring some goodies to the mix:

(setq speedbar-show-unknown-files t) (1)
(setq speedbar-use-images nil) (2)
(setq sr-speedbar-right-side nil) (3)
(setq sr-speedbar-auto-refresh t) (4)
(setq speedbar-directory-unshown-regexp "^\\(CVS\\|RCS\\|SCCS\\|\\.\\.*$\\)\\'") (5)
(add-hook 'speedbar-before-visiting-file-hook 'sr-speedbar-close t) (6)
(global-set-key (kbd "C-o") 'sr-speedbar-toggle) (7)
1 Make speedbar show all files, including hidden ones…​
2 …​and no images.
3 Speedbar on the left side of the screen.
4 Refresh automatically.
5 Atrocious regular expression to actually display all files.
6 Close the speedbar after opening a file.
7 Show the speedbar with a keyboard shortcut.

For Vim, as usual, clone the repository on the ~/.vim/bundles folder: git clone github.com/scrooloose/nerdtree.git and then add some configuration entries in your .vimrc:

let g:NERDTreeDirArrows=0
let g:NERDTreeQuitOnOpen=1 " (1)
let g:NERDTreeShowHidden=1 " (2)
map <C-O> :NERDTreeToggle<CR> " (3)
1 Close the NERDTree after opening a file.
2 Make NERDTree show all files, including hidden ones.
3 Show the NERDTree with a keyboard shortcut.

Now you have in both editors a nice file browser appearing at the left side of the editor every time you hit Ctrl+O. Of course you can use another shortcut if you want.

In Vim you can go to the parent dir in NERDTree using the U key, while in Emacs speedbar you need to use the Shift+U combination. Almost the same.

40. Too Much Information

One last plugin (or package) before we end this book. One that adds a whole lot of information at the bottom of our editor screens, using the Vim Airline plugin or the Emacs PowerLine.

In Emacs, the usual Meta+X package-install powerline will install it locally. Then we need some configuration in .emacs:

(require 'powerline)
(powerline-default-theme)

And for Vim, just as easy: git clone github.com/vim-airline/vim-airline.git and you are done. Nice information bars at the bottom of your editor.

Act IV: Finale

Now we’ve entered a new decade of devices where Unix(-like) operating systems will, on a CPU basis, probably out-install Windows. Not only is iOS based on Unix, but Android and MeeGo and even Bada are based on Linux as are QNX and WebOS. Google, Apple, HP, RIM, Samsung and Nokia are all now betting heavily on Unix or Unix-like implementations. The success is so overwhelming that there are really only two hold-outs: Microsoft and the rapidly depreciating Symbian. (source)

— Horace Dediu about Unix in 2010

41. Walking In My Shoes

This whole book has the very selfish objective of making me feeling less alone. As I write these lines I celebrate my 45th birthday, and no longer qualify as "senior" software developer, but rather as a "senile" one, in the eyes of many.

In the world of today, my experience is no longer seen as an asset; if anything, it is most globally seen a hindrance, an annoyance, at most a good prospect for coaching more "agile" junior profiles.

The interesting thing is that age is unavoidable. The 30 year old developer of today will invariable, barring sudden death, reach my age and and older, and will be brought to these sensations.

The biggest lession I have received from software is that of its impressive capacity to rot. But software rots not on its own, but because of its incapacity to evolve, for any reason, following the changes in the the underlying platforms where it runs.

Hence, Vim and Emacs stand out. The knowledge that these tools will be there in the coming years, and that my writing in pure text format will be readable and editable in the future, is something that one can only appreciate after a certain age.

Being older made me appreciate the uncertainty and stress generated by hype, in all of its forms, and the feeling of reassurance and quality that some older tools can bring. Some classics in our industry, like BSD Unix, Linux, Emacs, Vim, with their mix of openness and freedom, are a bowl of fresh air that makes me feel better.

I choose free and open tools not because of ego, hype, communism, or hubris; but precisely because they are exactly the opposite. They are humble, boring, and universal. And age has made me appreciate those factors.

The same way I appreciate a song by Piazzolla or Robert Fripp; a book by Borges or a poem by Frost; a painting by Dali or Hopper; a photograph by Salgado or Helmut Newton; a keyboard by Logitech or Microsoft; I appreciate, too, the software of Stallman and Molenaar. Because of their timelessness, because of their universality, because of their perennial value.

In the age of uncertainty and doubt, in these moments of crisis, where our society and our planet are undergoing the biggest changes ever, choosing stability and long-term value is a skill that has strong, long-lasting, positive consequences.

I hope these few lines will convince you to try, to open your mind to those tools, and to choose responsibly for your next platform, whatever that may be.

42. Le Vent Nous Portera

This short book ends here. If you found interesting what you learnt about Vim and Emacs, then you will most certainly continue the exploration on your own.

The best approach is to continue customizing your configuration files, until the editors look and behave exactly how you want them too. This is the biggest reason to use them; to have them fit your needs and to look the way you want. They are extremely configurable.

Some people have shared their own pre-cooked configuration files. There are countless "dotfiles" repositories in Github to learn from. You can also install Prelude for Emacs or Janus for Vim. These are just two of a myriad of different precooked environments for both editors, with plenty of settings and plugins ready to be used.

Here is a warning, though. I tried Janus for a while, and then uninstalled it altogether. I found that it made Vim slow to start, and there were many plugins in it that I just did not use. Instead I ended up just installing the things I really used. So my recommendation would be to try Janus or Prelude, and if you like them, then keep them. Otherwise, go as minimalist as possible, and just add the settings you really need. This is what you have done while reading this book.

Also worth mentioning, the CEDET project, the "Collection of Emacs Development Environment Tools," geared to the creation of a complete development environment in Emacs. I have not gone that far with Emacs yet, but maybe I will some day. If you write a lot of C and C++ code with Emacs, you might want to try Meta+X gdb at some point.

But in any case, remember to Meta+X tetris once in a while.

Also, you might have noticed that many Unix commands share the shortcuts of Emacs and Vim, which means that you can use them outside of those programs. For example, you can scroll up and down in a man page, or the output of the more and less commands, using J and K or Ctrl+N and Ctrl+P. Even bash and zsh allow you to Ctrl+A and Ctrl+E to go to the beginning or end of a command before executing it. These calisthenics will prove themselves useful all over Unix.

I cannot finish a book about Emacs without mentioning the venerable Org Mode, which is touted as one of the greatest organization and creativity tools ever created. Then again, this subject is too much for this short introduction, and it deserves a book of its own. Oh, wait.

If you use Visual Studio Code, you might want to add the Vim or Emacs emulation plugins, maybe?

And, if after all these tips and tricks you cannot get enough, try Emacs emulated on a web browser, an actual implementation of Vim compiled in WebAssembly and running on your browser, or a web browser that behaves like Vim. Maybe you could use the latter to view the former, and then dance a little tribal dance in your living room like nobody is watching.

Because, why not? Having fun and learning new things is the true answer to the ultimate question of life, the universe, and everything.

Appendix A: .emacs File

;; Show line numbers
(global-linum-mode t)

;; Option key for meta in GUI Emacs
(setq mac-option-key-is-meta nil
      mac-option-modifier 'none
      mac-command-key-is-meta t
      mac-command-modifier 'meta)

;; Add a space after the line number
(setq linum-format "%4d ")

;; Cursor line highlight
(global-hl-line-mode 1)

;; Package management
(require 'package)
(setq package-archives
      '(("GNU ELPA"     . "https://elpa.gnu.org/packages/")
        ("MELPA Stable" . "https://stable.melpa.org/packages/")
        ("MELPA"        . "https://melpa.org/packages/"))
      package-archive-priorities
      '(("MELPA Stable" . 10)
        ("GNU ELPA"     . 5)
        ("MELPA"        . 0)))
(package-initialize)

;; Magit configuration
(global-set-key (kbd "C-x g") 'magit-status)

;; Undo tree configuration
(global-undo-tree-mode)
(setq undo-tree-visualizer-diff t)
(setq undo-tree-visualizer-timestamps t)
(global-set-key (kbd "<f5>") 'undo-tree-visualize)

;; Speedbar configuration
(setq speedbar-show-unknown-files t)
(setq speedbar-use-images nil)
(setq sr-speedbar-right-side nil)
(setq sr-speedbar-auto-refresh t)
(setq speedbar-directory-unshown-regexp "^\\(CVS\\|RCS\\|SCCS\\|\\.\\.*$\\)\\'")
(add-hook 'speedbar-before-visiting-file-hook 'sr-speedbar-close t)
(global-set-key (kbd "C-o") 'sr-speedbar-toggle)

;; Powerline configuration
(require 'powerline)
(powerline-default-theme)

Appendix B: .vimrc File

" Drop vi compatibility
set nocompatible

" Show line numbers
set number

" Cursor line highlight
set cursorline

" Activate Pathogen
execute pathogen#infect()
filetype plugin indent on

" Syntax highlighting
syntax on

" Better searching
set incsearch
set ignorecase
set hlsearch

" Gundo configuration
let g:gundo_close_on_revert=1
let g:gundo_prefer_python3 = 1
nnoremap <F5> :GundoToggle<CR>

" NERDTree configuration
let g:NERDTreeDirArrows=0
let g:NERDTreeQuitOnOpen=1
let g:NERDTreeShowHidden=1
map <C-O> :NERDTreeToggle<CR>

Colophon

Tales Of Editors & Keyboards: A Personal Introduction To Vim & Emacs

ISBN: 978-3-906926-20-9

(c) 2018 Adrian Kosmaczewski – All Rights Reserved

This document is geared towards providing exact and reliable information in regards to the topic and issue covered. The publication is sold with the idea that the publisher is not required to render accounting, officially permitted, or otherwise, qualified services. If advice is necessary, legal or professional, a practiced individual in the profession should be ordered.

In no way is it legal to reproduce, duplicate, or transmit any part of this document in either electronic means or in printed format. Recording of this publication is strictly prohibited and any storage of this document is not allowed unless with written permission from the publisher. All rights reserved.

The information provided herein is stated to be truthful and consistent, in that any liability, in terms of inattention or otherwise, by any usage or abuse of any policies, processes, or directions contained within is the solitary and utter responsibility of the recipient reader. Under no circumstances will any legal responsibility or blame be held against the publisher for any reparation, damages, or monetary loss due to the information herein, either directly or indirectly.

Respective authors own all copyrights not held by the publisher.

The information herein is offered for informational and recreational purposes solely, and is universal as so. The presentation of the information is without contract or any type of guarantee assurance.

The trademarks that are used are without any consent, and the publication of the trademark is without permission or backing by the trademark owner. All trademarks and brands within this book are for clarifying purposes only and are owned by the owners themselves, not affiliated with this document.

Written and published in Switzerland. Created with the eBook Template Toolchain by Adrian Kosmaczewski based on Asciidoctor.