Thursday, August 14, 2014

Learning the Tool of Vim

Barry Arthur, 2014-08-14


Learning to use a tool requires:
  Understanding — What is it? 
                  Why do I need it? 
                  How does it fit in with the rest of my world?;
  Cognition — discovering how it works and remembering so;
  Practice — honing the coordination, grace and speed of movements; and finally,
  Affection — the desire to use it, to use it properly, 
              and to identify with the community using it.

Understanding


If you already understand Vim, you can skip this section.

Vim is a Text Editor


A text editor is a tool for creating and changing text documents.

Vim has a Rich Set of Text Objects


Think of a Text Object as a unit of text that can be manipulated (changed, deleted, cut, copied, pasted, selected, etc). Simple editors like Notepad and Nano offer at most two Text Objects — individual characters, and visually selected text. Vim introduces objects for words, sentences, paragraphs, quoted strings, parenthetical collections, entire blocks and functions in programming languages, and a lot more. Text Objects allow the user to manipulate logical portions of text at a higher level of abstraction than mere characters or clumsy explicit selections. This freedom lets the Vimmer think and act faster.

Vim is Configurable


Nearly every facet of operation is controlled by one or more configurable options. Two different Vimmers may have their Vims configured so differently as to appear as different editors to newcomers. Initially daunting, this flexibility and control is appreciated by seasoned Vimmers.

Vim is Extensible


Default functionality can be altered and new functionality added. One such extensible aspect of Vim is its set of Text Objects — existing definitions can be altered and new objects created. Another area of extensibility is through the modification or addition of keys and commands.

Vim is Scriptable


More complicated edits can be recorded and played back as needed. These are called macros. I link to three macro articles below.

For even more scripting power, there is Vimscript (aka VimL), Vim’s built-in scripting language which is used by plugin authors to create weird and wonderful addons, and ordinary Vimmers to automate and control facets of Vim.

I look forward to meeting you on the Path to VimL Mastery.

Vim is Modal


The control interface to Vim is, typically, a keyboard. Keyboards are necessarily limited in the number of keys they hold. This limits the number of unique interactions with Vim that can be made by a User.

One way to solve this problem is by "chording" keystrokes, that is by holding multiple keys down at the same time. While Vim uses a small amount of chording, the more dominant model it uses could instead be referred to as "plucking".

Chording

One definition of such a key-chord includes the common SHIFT, CTRL, and ALT (META/COMMAND) key combinations used in most Operating Systems / Window Managers, like CTRL-W to close a window, or ALT-F4 to close an application (in Windows). Other definitions exclude such simple instances and instead require multiple non-(SHIFT, CTRL, ALT) keys to form a chord.

Two things to know about chording:
  1. The number of extra interactions it provides is small.
    Chording doesn’t scale very well because the hands can only hold down so many characters at the same time, less even, when limited by reach. It also limits the amount of extra interactions that are possible — chording is unaffected by the order in which the keys are pressed — they all need to be pressed together for the chord to trigger. Chording is therefore the mathematically poorer Combination as compared to the richer Permutation that plucking yields.
  2. It hurts.
    Contorting the hand to simultaneously press multiple keys puts a lot of strain on tendons and ligaments, and I believe, significantly contributes to repetitive strain injury (RSI). Anecdotally, I have heard of far more Emacsians complaining of RSI than I have Vimmers. In fact, it is an often cited reason for an ex-Emacsian switching to Vim. For the Emacsian reading this that can’t bare to lose his beloved Emacs, the Evil mode provides a vimmish interface that might be kinder on your wrists.

Plucking

Instead of holding down more than one key simultaneously, Vim prefers a model of striking multiple keys sequentially. This is called a key-sequence and resembles plucking strings on a guitar (as opposed to strumming a chord).

Plucking is better because:
  1. The number of extra interactions is vastly greater. (permutation vs combination)
  2. It doesn’t hurt. (as much)

And it’s actually better than that because the sequence of keys that Vim uses for its commands are not random — they are carefully considered so as to form an actual language designed specifically for the efficient editing of text.

The d key for example is a verb for performing a delete operation. But… deleting what? A character? A word? A line? In other editors, different chords are used to express these alternatives, like ctrl-d deletes a word, ctrl-shift-d deletes a line, ctrl-alt-shift-d breaks your wrist, etc.

The d verb is an unfinished command in Vim. It is an operator (verb) pending a motion (an object to operate on). Vim is waiting for me to tell it what to delete. If I type l now, it will delete a letter (a synonym for the x command); if I type w it will delete from the cursor to the end of the word; b will delete back from the cursor to the start of the word; and another d will delete the entire line. This is a common idiom in Vim — doubling the operator (here, dd) will operate on the whole line. So, y is the yank operator (and unsurprisingly, I hope, pressing it DOES NOTHING because Vim is now waiting for you to tell it what to yank), and yy yanks the whole line. “Yank” is Vim’s term for copy (for pasting later).

One particularly nice set of "motions" are the Text Objects. I will show one here just quickly, but you need to read :help text-objects (heck, just grab a cold beer and read all of :help motion.txt — thank me later)

The iw Text Object:

The command diw will delete an entire word, no matter where the cursor is inside the word. This is better than messing around with dw which only deletes from the cursor to the end of the word.

What Does This Have To Do With Vim Being Modal?

Whereas some editor might use ctrl-d to delete a word, Vim uses diw To those unfamiliar with Vim, that might seem like a typo: how can the d i and w keys be used to delete a word?! What if I want to type a "d" or "i" or "w"?! This is where modes come in. In Normal mode, Vim uses diw to delete the word at the cursor. In Insert mode, it inserts (types) these letters instead.

By separating semantically different concepts, Vim is able to re-use keys for different purposes. For example, in Normal and Visual modes, the "%" key jumps the cursor to the bracket matching the one under the cursor; in Command-line mode, it serves as an alias meaning "the whole buffer" when used as a range, or the name of the current buffer when used as an argument to an ex command; and, of course, in Insert mode it merely inserts a "%" character.


Pop Quiz: Been paying attention? Let’s see.

Given the following text, where the cursor is on the "(" :

echo getline(1, '$')

What do you expect the following Normal mode key sequence to do:

d%

Check your answer at the end of the article.


Vim has 12 modes all up (6 basic modes — the other 6 are variations on the basic ones) but the beginner Vimmer only needs to know 4 of them:
  • Normal mode — The editor starts in this mode. Use <Escape> to return to Normal mode from any other mode. This mode is for movements and operations on Text Objects, like changing, deleting, cutting, yanking (copying), pasting, and entering one of the other modes.
  • Visual mode — Used to extend a highlight region over text. Non-movement commands in this mode execute the command on the selected text.
  • Insert mode — Anything typed in this mode is inserted into the buffer.
  • Command-line mode — For running one of three types of commands:
    • Ex commands — :
    • Searches — / and ?
    • Filters — ! (which you won’t need until you advance somewhat)

Cognition


Learning Vim is learning a skill


Learning a skill is very different to learning knowledge. Skills require that, not just your mind, but also your muscles get involved. We can intellectually know what is required of a task and yet be completely incapable of performing it competently. The gap here is what separates a skill from knowledge: practice. Physical practice. And not just any old practice; it requires Perfect Practice. More on that later.

A good way to learn a new skill:
  1. Normal - Watch an expert do it at normal speed
  2. Slow - Watch an expert do it slowly
  3. With - Do it with an expert, several times, from slow to normal speed
  4. Practice - Practice the new skill several times per day until competent

Use videos if you don’t have access to an expert to watch live. Textual descriptions of steps in tutorials will suffice if no better source is available, but then you lose value by missing the Normal and Slow steps. The value here is in seeing what really is achievable in terms of speed and ease. Seeing a skill being performed properly lowers learning barriers for many who can’t picture themselves being able to do a set of steps explained orally or in written form. Harness the power of Monkey See, Monkey Do.

A digression:
Unfortunately, a lot of video resources for Vim lack in two important ways:
  1. They tend to show too much in one session, confounding higher level concepts with lower level edit sequences.
  2. Some lack OSD overlays showing keystrokes as they’re typed, resulting more in porn than instruction. Watching a Gary Bernhardt session late at night, after the children have gone to bed, is a perfectly acceptable way to unwind after a stressful day.

Racing up the Vim Ramp — topics begging for decent videos:
  • motion.txt — All the builtin motions and text objects (or at least the most useful ones). Seeing them grouped is useful; perhaps the video could similarly group its presentation of these powerful commands.
  • ranges — Something the Vim Ranger can help you with for now.
  • registers
  • Searching & Replacing (Regular Expressions, /, :s///, :g//, :v//) The Walter Alan Zintz (waz) tutorial is this in text form. Other useful tutorials exist.
  • Macros — when to use them, not silly examples where :[range]s/// is preferred. My macro articles are one place to start.
  • Tags — The 80/20 that makes it worth learning.
  • Quickfix — :make & :vimgrep
  • Buffers, Windows and Tabs — Examples of using them wisely. This buffers & args article is a place to begin.

In addition to all of the resources above, I recommend my LearnVim to rapidly acquaint yourself with and acquire the skills of Vim.

Practice

One of the pieces of advice given in LearnVim is the use of a Practice File — a place where you can collect newly learned editing motions and commands requiring frequent practice.

Since LearnVim was first written wherein the Practice File advice was espoused, I have since written a tool to replace the manual maintenance of such a Practice File: VimGym.

The purpose of VimGym is to be a place for you to practice the things you need to work on. As and when you discover new commands or motions or ways to do things, create a practice task in VimGym. Gradually, you will build up a set of exercises targeting your weaknesses, helping you where you need it.

But how do I know if I’m practising right?

Excellent question. This is one of the key requirements for Deliberate Practice — the supervision of a coach — the knowledge that you’re investing energy in the right place, working on the right things.

In Vim terms, this means practising motions and commands and ways that are suitable to the task at hand.

Where do I find a coach?
  • Read :help motion.txt
  • Read the set of learning resources I have linked to in this article
  • Look at sane solutions to vim-golf problems
    • A solution is not sane if you don’t understand it.
    • Ask on #vim for explanations if you think it could be sane given clarity.

Fast, Slow, Medium

Once you know what you should be practising, there is the question of how: “How do I get my fingers Bernhardt fast?!”

Steve Yegge proposes the Fast, Slow, Medium approach.

I wonder if Gary used this…?

Affection

Being a successful Vimmer requires living the Vim Way. Many initially come to Vim with notions carried over from their prior editor pasts and attempt to change Vim accordingly. Many struggle this way until they give up on Vim, decrying it as worthless or inflexible. Those that eventually give up their struggle against Vim discover the opposite; they discover the power and flexibility and extensibility of a tool that, when used right, has continued to be the best “editor of text” for decades and will probably continue to be so for decades more.

Advice: Stop fighting Vim and start using it the way(s) it was intended. When you’re told on #vim that your approach is anathema to the Vim Way: stop, listen and change your approach. Happiness this way lies.


Good luck, and welcome aboard.


Quiz Answer: The cursor is on the "(" character, and in Normal mode the % key jumps to the matching bracket. The d key is given % as its motion. The result is that the entire bracketed chunk of text [ (1, '$') ] is deleted.