Getting started with & understanding the power of Vim

Being a developer and having used a lot of code editors over the years, I think it’s a very interesting area both when it comes to efficiently but also in the program we spend many many hours in. At the moment, I’m back with Vim (more specifically, MacVim).

The last years I’ve been using Sublime Text extensively, and before that, TextMate. I’ve really liked Sublime Text, it supports most of what I want to do and I’m happy with it.

As the same time, my belief is that you need to keep on challenging yourself. Try and learn new things, get another perspective, learn about needs and possibilities you didn’t even knew you had. Or, at the very least, go back to what you used before, now being more aware of how much you like and appreciate it.

Vim redux

A few years ago I tried out Vim (MacVim) to see what it was like. A lot of great developers use it, and a few friends swore by how amazing it was. So, naturally I had to try it.

Tried for a while, and did it with the Janus distribution. I did end up in a situation where I didn’t have enough control; or rather, didn’t understand how it all works and didn’t take the time to learn. So I tried Vim for a while, got fed up and aggravated that I could get things done quickly. While I learned a lot about Vim after a while, at that time and during its circumstances, the cost was too big to continue.

But now I’m back again, and so far I’m happy about it. 🙂

Let’s be completely honest, though: the learning curve is fairly steep and there are a lot of annoying moments in the beginning, in particular since it is very different from what most people have used before.

Getting started

My recommendation to get started, and really grasp Vim, is to download a clean version, and probably something with a graphical user interface/application wrapper for your operating system. As mainly a Mac OS X user, my choice has been MacVim.

In your home folder, you will get (or create) a folder and a file (there could be more, but this is the start):

.vim folder
Contains your plugins and more
.vimrc file
A file with all kinds of configurations, presets and customizations. For a Vim user, the .vimrc file is the key to success (for my version, see below)

Editing Modes

One of things is that Vim offers a number of different modes, depending on what you want to do. The core ones are:

normal
This is the default mode in Vim, for navigating and manipulating text. Pressing <Esc> at any time takes you back to this mode
insert
Inserting and writing text and code
visual
Any kinds of text selections
command-line
Pressing : takes you to the command line in Vim, from which you can call a plethora of commands

Once you’ve gotten used to switching between these commands, you will realize how extremely powerful they are and, when gained control, how they dramatically improves efficiency. Search/substitute is also very powerful in Vim, but I really do recommend checking out vimregex.com for the low-down on commands and escaping.

Keyboard shortcuts

With the different Modes, there’s an abundance of keyboard shortcuts, some of them for one mode, some of them spanning across modes (and all this customizable as well through your .vimrc file).

Also, Vim is a lot about intent. Not just what you want to do now, but thinking 2, 3 or 4 steps ahead. Where are you going with this entire flow, not just action by action without connections.

For instance, let’s say I have a <h2> element with text in it that I want to replace, like this:

<h2>I am a heading</h2>

My options are (going from most most complicated to most efficient):

  • Press v to go into Visual mode, then use the w (jump by start of words) or e (jump to end of words) to select the text and then delete it (with the delete key or pressing d), press i to go into Insert mode, then enter the new text
  • Press v to go into Visual mode, then use the w (jump by start of words) or e (jump to end of words) to select the text, then press c to go into Insert mode with a change action, i.e. all selected text will be gone and what you type is the new value
  • Press dit in Normal mode, which means “delete in tag”, then press i or c to go into Insert mode and write the new text
  • Press ct< in Normal mode, which means “change to [character]”, then just write the new text
  • Press cit in Normal mode, which means “change in tag”, then just write the new text

Using ct[character] or dt[character], e.g. ct< will apply the first action (“change”) to the specified character (“<” in this case). Other quick ways of changing or deleting things on a row is pressing C or D which will automatically do that action to the end of the current line.

There is a ton of options and combinations, and I’ve listed the most common ones below (taken from http://worldtimzone.com/res/vi.html):

Cursor movement

h - move left
j - move down
k - move up
l - move right
w - jump by start of words (punctuation considered words)
W - jump by words (spaces separate words)
e - jump to end of words (punctuation considered words)
E - jump to end of words (no punctuation)
b - jump backward by words (punctuation considered words)
B - jump backward by words (no punctuation)
0 - (zero) start of line
^ - first non-blank character of line
$ - end of line
G - Go To command (prefix with number - 5G goes to line 5)

Note: Prefix a cursor movement command with a number to repeat it. For example, 4j moves down 4 lines.
Insert Mode – Inserting/Appending text

i - start insert mode at cursor
I - insert at the beginning of the line
a - append after the cursor
A - append at the end of the line
o - open (append) blank line below current line (no need to press return)
O - open blank line above current line
ea - append at end of word
Esc - exit insert mode

Editing

r - replace a single character (does not use insert mode)
J - join line below to the current one
cc - change (replace) an entire line
cw - change (replace) to the end of word
c$ - change (replace) to the end of line
s - delete character at cursor and substitute text
S - delete line at cursor and substitute text (same as cc)
xp - transpose two letters (delete and paste, technically)
u - undo
. - repeat last command

Marking text (visual mode)

v - start visual mode, mark lines, then do command (such as y-yank)
V - start Linewise visual mode
o - move to other end of marked area
Ctrl+v - start visual block mode
O - move to Other corner of block
aw - mark a word
ab - a () block (with braces)
aB - a {} block (with brackets)
ib - inner () block
iB - inner {} block
Esc - exit visual mode

Visual commands

> - shift right
< - shift left
y - yank (copy) marked text
d - delete marked text
~ - switch case

Cut and Paste

yy - yank (copy) a line
2yy - yank 2 lines
yw - yank word
y$ - yank to end of line
p - put (paste) the clipboard after cursor
P - put (paste) before cursor
dd - delete (cut) a line
dw - delete (cut) the current word
x - delete (cut) current character

Exiting

:w - write (save) the file, but don't exit
:wq - write (save) and quit
:q - quit (fails if anything has changed)
:q! - quit and throw away changes

Search/Replace

/pattern - search for pattern
?pattern - search backward for pattern
n - repeat search in same direction
N - repeat search in opposite direction
:%s/old/new/g - replace all old with new throughout file
:%s/old/new/gc - replace all old with new throughout file with confirmations

Working with multiple files

:e filename - Edit a file in a new buffer
:bnext (or :bn) - go to next buffer
:bprev (of :bp) - go to previous buffer
:bd - delete a buffer (close a file)
:sp filename - Open a file in a new buffer and split window
ctrl+ws - Split windows
ctrl+ww - switch between windows
ctrl+wq - Quit a window
ctrl+wv - Split windows vertically

Plugins

There are a number of different ways of approaching plugins with Vim, but the most simple and clearest one that I’ve found, in the form of a plugin itself, is using pathogen.vim. Then you will place all other plugins you install in .vim/bundle

These are the plugins I currently use:

command-t
Mimicking the Command + T functionality in TextMate/Sublime Text, to open any file in the current project. I press , + f to use it (where , is my Leader key)
vim-snipmate
To import snippet support in Vim. For instance, in a JavaScript file, type for then tab to have it completed into a full code snippet. As part of this, some other plugins were needed:

vim-multiple-cursors
I love the multiple selection feature in Sublime Text; Command + D to select the next match(es) in the document that are the same as what is currently selected.
This is a version of this for Vim that works very well. Use Ctrl + n to select any matches, and then act on them with all the powerful commands available in Vim. For instance, after you are done selecting, the simplest thing is to press c to change all those occurrences to what you want.
vim-sensible
A basic plugin to help out with some of the key handling.
vim-surround
surround is a great plugin for surround text with anything you wish. Commands starts with pressing ys which stands for “you surround” and then you enter the selection criteria and finally what to surround it with.
Examples:

  • ysiw" – “You surround in word”
  • ysip<C-t> – “You surround in paragraph” and then ask for which tag to surround with
nerdtree
This offers a fairly rudimentary tree navigation to Vim. Don’t use it much at the moment, though, but rather prefer pressing : to go to the command line in Vim and then just type in e. to open a file tree.

My .vimrc file

Here’s is my .vimrc file which is vital for me in adapting Vim to all my needs – keyboard shortcuts, customizations, eficiency flows:

HyperLinkHelper in Vim

Another thing I really like in TextMate and Sublime Text is the HyperlinkHelper, basically wrapping the current selection as a link with what’s in the clipboard set as the href value. So I created this command for Vim, to add in your .vimrc file:

vmap <Space>l c<a href="<C-r>+"><C-r>"</a>

In Visual mode, select text and then press space bar + l to trigger this action.

Scratching the surface

This has only been scratching the surface of all the power in Vim, but I hope it has been inspiring, understandable and hopefully motivated you to give it a go, alternatively taught you something you didn’t know.

Any input, thoughts and suggestions are more than welcome!

26 Comments

  • Though vim is now my default editor, it took me forever to get used to it. That said, reading through this I find that I have a lot to learn. Thanks!

    • Robert Nyman says:

      Yeah, you really need to work for it! But the investment quite pays off.
      And glad you found some new knowledge here – I’m certain there’s always something new to learn in Vim for everyone. 🙂

  • Justin Wood (Callek) says:

    http://vim-adventures.com/ is how I learned the basics with vim. Still not a fan of vim though

  • Dennis Schubert says:

    Don’t forget about 😡 instead of :wq – will save you thousands of keystrokes in your life! 😉

  • Fabian says:

    Well i can not understand right now why i should use vim as my default editor for programming.

    Yes i use it for Linux administration or writing a shell script once in a while.

    But as an IDE. Well there are programs that do much more for me than vim. Maybe i just missing something here. Where is codecompletition, usage search, declaration jumping. All other stuff i have in my IDE aswell and a build in git manager to work with my team.

    Atm i consider using sublime, textmate or vim for development purpose is just pip and cool.

    • PA says:

      I can assure you that you are indeed missing much here.

      vim has all the features you cite. The thing is, vim without the right plugins is quite frustrating.

      I have used it for ten years now, and I still discover new plugins from times to times… Didn’t know vim-multiple-cursors yet. Thanks Robert.

    • Robert Nyman says:

      Fabian,

      Like PA said, all those things and much more are available for Vim. Since Vim has been around a long time, a lot of people have created amazing extensions to it. I think finding and adapting them can be work, though – for me, using Vim is a work in constant progress while more general IDEs are “done”.

  • Simon Lindholm says:

    > vim-snippets – great language snippets from Jan “Honza” Odvarko

    Misattributed, I’m sorry to say – https://github.com/honza is Honza Pokorny. I haven’t been able to convince Jan Odvarko to switch to vim. 😉

  • Integralist says:

    For anyone interested. I have a Vim/tmux book being release in December by Apress http://www.apress.com/9781484202517 called Pro Vim (aimed at users who’ve never used Vim and takes you all the way to advanced levels).

  • What’s quite useful is that many of the lower-case letters have upper-case equivalents:
    a (append) A (append at end of line)
    c (change) C (change to end of line)
    d (delete) D (delete to end of line)
    f (find char) F (find char backwards)
    i (insert) I (insert at start of line)
    n (next) N (previous)
    o (append line) O (insert line)
    p (append paste) P (prepend paste)
    r (replace) R (replace mode)
    s (substitute) S (substitute line)
    u (undo) U (undo line)
    x (delete forwards) X (delete backwards)
    y (yank) Y (yank line)
    There are probably others I can’t think of offhand.

  • Oh, and when it comes to NERDTree, it isn’t just to see files and directories, but also to CRUD them!

    See :h NERDTreeMappings for a list of what’s available.

  • stephen bartell says:

    glad i landed on this, good cheatsheet. i’ve got a similar story. i bounced like eclipse, textmate, vim, sublime, vim, sublime, atom, and finally vim. im now so glued to my keystrokes that i feel awkward in any other editor. even though i dont use it that much, i still can’t shake `set mouse=a` haha.

    the other editors are cool, i really love atom and how its built. brackets is another one that looks sweet. i just can’t shake that at the end of the day i need an editor thats done, thrashed, and all hashed out. once you get over the learning curve and get into the groove with all your shortcuts, plugins, and motions, everything else feels oldschool – ironic.

    • Robert Nyman says:

      Thanks, glad you liked it! And yes, once you get set in Vim, other editors can feel a bit weird (even in their Vim modes). And very true, lots of learning experiences that have gone into Vim for sure!

  • Hello, Robert,

    today I walked through old feeds of Wil Clouser and spotted one, which might be interesting to your readers as well:

    CLI Split Windows in Vim

    It’s basically a way to split the windows and enter a shell prompt. You need to check out, though, whether the code still runs as the article is from 2010.

    Best regards,

    André Jaenisch

Leave a Reply

Your email address will not be published. Required fields are marked *

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