Vim is a beautiful tool

This post was authored by guest author Mark Sanborn. Find out more below.

When it comes to productivity I can’t think of any application that has saved more time and frustration than Vim. Vim is the ultimate productivity tool for programmers. Most users of Vim that I know that have spent the time to learn it absolutely love it and couldn’t imagine a world without it. My only regret with Vim is not learning it sooner.

So what is Vim?

Vim is a modal text editor that is highly configurable, efficient, and lightweight. Some people refer to it as the programmer’s text editor because it has a plethora of features that make programming easier, although it could be used for other things like writing email and editing config files.

What makes Vim especially great is the shortcuts, commands, and the blistering speed at which you can edit text files since Vim has all the common editing tasks mapped to single keys on or near the home row on your keyboard.

Sounds great… but there is a catch:

Vim isn’t an editor designed to hold its users’ hands. It is a tool, the use of which must be learned.

Easing the learning curve

Vim is known for having a steep learning curve. I think Vim has this reputation because people tend to want to learn all of the features right away and quickly become overwhelmed.

Vim is a lot like Adobe Photoshop, you can learn just a few simple techniques in Photoshop that can make a world of a difference in the images you can create and ways you can manipulate them. Yet it may take you a lifetime to master all the functions Photoshop has to offer. Vim is the same way. You can learn only a few shortcuts and commands that will completely change the way you do text editing but may take years to learn them all (not that you would need to).

The great thing about Vim is everyone uses it differently. I have my favorite shortcuts that I use every day. Someone else might have a different set they use depending on what types of files they generally edit. Once you learn a few basics and get comfortable with the shortcuts and commands that you use every day you can learn another to increase your productivity.

Getting Started

I suggest going through vimtutor once right now and again after you have played around with Vim for a while. You can access vimtutor by typing in the command, ‘vimtutor’ for Linux users and by running vimtutor.bat in your Vim folder for Windows users.

Vimtutor has all the commands and how to use them as well as practice sections for all your basic editing needs. Don’t worry if you don’t remember all the commands when going through the vimtutor for the first time; however, it is important to do the exercises at the end of each section so you can get used to the way Vim works. It should only take about a half hour to make it through your first run through the tutorial.

You might consider bookmarking this article for your reference and checking out vimtutor now.

Making Vim Work for You

After using Vim for a while now I have a good idea which commands I use most often when doing web development, programming, and configuration editing. We will use this experience to look at different ways Vim can improve your programming and make it faster while trying not to overwhelm you with too many new commands. Grab a few of these, use them, and add more when you feel comfortable.

Vim modes

In Vim there are three major modes:

  • Insert mode is like the Windows ‘notepad’. Simply type and text will output to the screen.
  • Command mode is where Vim really shines. This mode is usually called "normal mode" since you will be using this mode a lot. To get into Command mode just hit ‘Esc’. When in command mode almost all letters numbers and keys on the keyboard are now shortcuts. The keys, ‘hjkl’ in command mode are now your "arrow keys".
  • Visual mode is where you can highlight text.

If you ever made a mistake and hit the wrong key you can use ‘Esc‘ to get back to normal mode.

Commands by function

Note: As with other *nix tools, these commands are case sensitive.
You can use these commands in conjunction with another command or repeated x number of times by adding a digit to the beginning. For example, ‘4dd‘ would delete 4 lines. ‘dw‘ would delete a word.

Here are some of the most common vim commands and their meanings:

Open and save:

:e path/to/filename‘ – With Vim running, this will open the file you specify. This command can also be used to open remote files over SSH.
:w‘ – Will save the current file
:q‘ – Exits Vim

You can also use these commands together:

:wq‘ – Writes to the file and exits Vim

If you want to quit without saving your changes you can do

:q!‘ – Quit without saving

Moving Around:

To move your cursor around with vim you will use:

h – left
j – down
k – up
l – right

These movement keys are all located on the home row. It will take a little getting used to but you will thank yourself for not using arrows or the mouse when you realize much time is wasted moving your hands. I even find myself trying to use these keys in other programs and get frustrated when they don’t work. Sometimes I am pleasantly surprised when programs can be navigated with these keys.

Undo and Redo:

Of course you can’t have an editor without undo and redo.

u - undo the last change
U – undo all changes on that line. This is very useful when programming.
Ctrl + r – redo the last change

Copy and Paste:

You will probably find yourself wanting to copy and paste at some point. I will first explain how to copy and paste lines of text in the way that you are used to and then describe a few alternative ways.

To highlight the text you want to copy you will need to put Vim into visual mode. You can do this different ways.

v – go into visual mode and highlight with the Vim movement keys.
V – go into visual mode and highlight lines of text

Once you have the text highlighted you will then "yank" the text with the ‘y’ key.

y – yank (copy) text.

Once you have the text yanked (copied) you can "put" (paste) it with the ‘p’ key.

p – put/paste text.

So far Vim has failed to show any real improvements over the way you are probably used to copying and pasting text. y/p probably isn’t much faster than ctrl+c ctrl+v other than the fact that you don’t have to stretch your fingers to do it. Here are some improvements.

yy – copy current line. This is incredibly useful and fast when doing programming or any type of editing. When using this command in conjunction with, ‘p’ it will automatically add a line to make room. For example you can go to the desired line, hit ‘yy’ then ‘p’ and it will copy the line paste it below and move your cursor to the newly created line.

My most commonly used commands

Like I have said earlier Vim has more shortcuts than you would ever even want to know about but here are the golden ones. These are the commands that I use daily.

  • h,j,k,l‘ – The movement keys are essential
  • w,b‘ – move forward ‘w’ and backward ‘b’ one whole word.
  • dw‘ – delete a word
  • u,ctrl+r‘ – Undo and Redo are a must
  • dd‘ – This deletes the current line. I am constantly using this. It also puts the text into a buffer so you can put/paste it.
  • 0,$‘ – The ‘0′ will put you at the beginning of the line and ‘$’ will put you at the end.
  • i,a‘ – The ‘i’ will put you in insert mode at the cursor. ‘a’ will put you in insert mode after the cursor. Think of it like append.
  • :52‘ – This will put you at line 52. When you have errors in your program on line X use this command.
  • o,O‘ – The ‘o’ will create a line below and put you in insert. ‘O’ does the opposite. It creates a line above. This doesn’t really seem all that useful because you can always hit the enter key if you are at the end of the line but you are not always in insert mode or at the end of the line when you decide to make another line.
  • f,F‘ – This is one of my favorite commands. ‘f’ will search forward in the line for the next character you type and ‘F’ will search backwards.

For example, lets say you have the following line of code:

print LOG "StateProvinceCode: $StateProvinceCode\n";

You could hit the ‘f‘ key then the ‘\‘ key and the cursor would be positioned right near the ‘n’ so I could change this to a tab character instead of a newline character.

This doesn’t mean it will keep on searching, there is a different key for that.

/‘ – Search. This is the key to initiate a search. You can use regular expressions or do a simple word search.

Special commands for programmers

Syntax highlighting — If for some reason Vim isn’t highlighting code by default you can turn it on by typing, ‘:syntax on‘ or add it to your .vimrc config file.
=%‘ – Will auto tab nested ifs/loops/functions. Although Vim automatically tabs everything out for you, sometimes you will run into old code or poorly tabbed code where you want to fix it up real quick. Just go to the first ‘{’ in the code and hit this command and everything will be auto tabbed.
gd‘ - Jump to variable definition. The g stands for go. There are multiple ways you can use ‘g‘, ‘gg‘ will go to the beginning of the file and ‘G’ will go to the end. In this case we are using ‘gd’ to go to the variable definition. For example, lets say you are about a mile down your code and you have a function that calls the variable, $someOldVariable. To find out what is inside this variable or where it was first created you would move your cursor to that variable and hit, ‘gd’ this would auto-magically move you to where that variable was first seen, AKA the variable definition.
%‘ - Go to matching () [] {}. Sometimes you will have a very long loop and a bunch of nested functions. If your tabbing isn’t the best it is sometimes tricky to find out which bracket belongs to which function. The ‘%‘ will move your cursor to the start or end of the matching bracket.
>> and >‘ – The double arrow, ‘>>‘ will shift the current line over one tab. If you highlight a region of text you can shift the entire text over with ‘>‘.

Conclusion

Although there are literally hundreds of shortcuts and commands for Vim you will be far ahead of the regular text editor with just these few. If you simply learned the commands in this article alone you would program/edit much faster and be more productive.

Remember: learn just the basics first. Open a text file or project source file and move around and learn how to save it. Learn how to undo-redo and basic editing in insert modes. To really get the hang of Vim you will need to spend about 5 hours messing around in the editor.

About Mark Sanborn

Hi, I am Mark Sanborn. I am 22 and just graduated from the University of Montana. I have had an interest in computers for as long as I can remember. I still remember the DOS days and really started getting into computers when Windows 3.1 was around. I made my first webpage in the 7th grade. My passion for web design and computers has only progressed from there.

How did I learn to program?
In college I was approached by a group that wanted a realty website created for the University business plan competition. I gladly took the job and forced myself to learn PHP/MySQL while working on the project. By the time the project was complete I was fairly fluent in PHP and was confident I could build pretty much anything I set my mind to. I later used these skills to create a corporate website with a custom e-commerce shopping cart for a client.

Computer Related Education
I just received my B.S. in Business Administration Information Systems. I scored nearly a perfect score on the MCP test allowing me to achieve the Microsoft Certifed Professional status. While attending college I worked for the University as tech support for dorm students and faculty. I have a lot of experience working with computers but there is still a lot I can learn from others. I also believe that you learn the most by teaching it to others. This is why I created my own blog.

What Languages Do You Use?
HTML, CSS, MySQL, PHP, Java, XML, Bash. For some reason I want to learn python yet I don’t know what I would use it for. Some experience in: ASP, Visual Basic, ColdFusion.

What Do You Do In Your Spare Time?
I spend a lot of time in front of the computer but I am not your typical programmer that loves Star Trek and converses with their friends about what to do in the event of zombie attacks. All stereotypes aside, I love to play guitar I am interested in all types of music, mostly blues and classic rock. I am an avid weight lifter and practice Judo. I don’t consider myself a fan of team based sports; however, I love individual sports. Last summer I learned to paraglide and for the past two winters I have been enjoying the fabulous sport of kiteboarding on snow.

If you liked this post, please help me share it

Responses (15)

  1. Jade Robbins says:

    VIM changed my programming life. I love my ability to do quick work without having to take my hands off the home row! These tips will get you up and running no time to make you a vim pro!

  2. Haha, the drawback I always come to is when I edit a document and realize that vim isn’t installed but instead vi is and I get all mad and have to take the extra 20 seconds to apt-get vim.

    Good article Mark.

  3. CRF Design says:

    Great write-up, Mark! Like you, I find Vim to be a very elegant editor. It changed the way I code!

    These didn’t make your list, but I overly abuse two features. The first is the block selection functionality ctrl-v for instant multi-line edits. The second is recording macros into a register using the q command. These two features alone let the editor execute edits in seconds rather than minutes!

  4. Mark Sanborn says:

    Thank you for the kind comments everyone.

    @CRF Design, I left out macros because I thought it might be a little advanced for someone just getting used to Vim and how to move around in the editor; although, I absolutely love executing a good macro. There are just so much you can do with Vim, maybe next time I will cover macros, aliases, markers, code folding, and other cool stuff :)

  5. Julio Biason says:

    The “f” example is wrong. “f\” will position the cursor exactly over the “\”, not “n”. To move it to “n”, you’ll need “$T\” ($ = move to the end of the line, T = tilt [like find, but stops before the char -- t moves forward, T moves backwards in the line, \ is the char you're looking for.])

  6. Mark Sanborn says:

    Julio Biason,

    Nice catch. You are right the “f” doesn’t put you exactly at the “n”, but it gets you pretty close :) I’ll have to fix the wording on that example.

    Thanks for catching it.

  7. manu says:

    Learning to use vim has always been on my Todo list but somehow I’ve stayed away from it for a long time; I get by with nano and gedit for most of the stuff I do. I didn’t know about vimtutor and I tried it after reading your post and it seems like a good way to start. So thanks.

  8. Srikanth says:

    Thanks Mark, I learned 4 new things today :)

    1) Autotab poorly indented code using ‘=%’
    2) Go to matching bracket using ‘%’
    3) Go to variable declaration using ‘gd’ (gg = first Line, didn’t know that too)
    4) Find a character in the current line using ‘f’ and ‘F’

    There are a few other commands I find extremely useful, these are the ones that comes to my mind now:

    1) ‘.’ (dot) = Repeat last command
    2) ‘*’ = Search for the word. Which word? Wherever the cursor is.

  9. Mark Sanborn says:

    @Manu,

    The vimtutor is golden. I used to be just like you. I used to use nano and would try to force myself to use vim. When I needed to make a quick change in a config file I said to myself, “I’m just gonna use nano… next time I’ll use Vim.” You should try to do a project in nothing but Vim.

    @Srikanth,

    Glad I could help! Like I said people use different commands than others. I am always finding new shortcuts. The best thing is that you can slowly add more commands to your arsenal.

  10. Craig says:

    I use vim all the time for editing config files, data files, files I need to do repetitive edits to (i.e. macros are great). I tried using it as an IDE for Java, it just can’t compete productivity wise with Eclipse or some of the other Java IDEs. Why? Because it knows nothing of Java, only of files. And some of the plugins you can get for Java integration are so poorly documented, it’s not work the effort to figure them out.

    Now if Eclipse had a vim editor, that would rock. This looks to be heading in the right direction though: http://eclim.sourceforge.net/

  11. [...] you will probably need something to actually write the code. I suggest using Vim/vi since it will save you a tremendous amount of time. If you haven’t already learned it you should start right [...]

  12. Vasudev Ram says:

    Good tutorial.

    Here is another beginner’s vi tutorial, which I wrote a while ago for Linux For You magazine. It’s for vi, the predecessor of vim, but almost everything in it is still current, and relevant to vim (possibly the only exception is the reference to vedit, an easier mode for vi.

    It might be one of the shortest vi tutorials around, so is good for getting up to speed with vi basics in a short while. Some Windows system administrator friends told me it helped them learn vi basics pretty soon.

    - Vasudev

  13. Vasudev Ram says:

    P.S. A pretty powerful vim command (also works in vi) and one that’s a personal favorite, is this:

    !!command_name optional_arguments ENTER

    Explanation follows:

    Let’s say you want to run some UNIX command and have it’s output brought into the file you’re currently editing. This is a pretty common and useful technique when programming. For example, if you’re writing an app that uses a database, you may often want to refer to the current database schema - the definitions of the tables and columns in the DB. Also, it would be convenient to have the schema available as part of the current file you’re editing. And of course, the schema is subject to change now and then as the project goes on. So if you were to use a saved schema report generated by the appropriate SQL command or script, it could be outdated. What you would like is for the schema-reporting script to be run and its output - the current schema - to be inserted into your file, maybe between comment delimiters. That way, you can refer to it while coding.
    [ And at the end of your editing session, you could easily delete it from your code by deleting everything between those comment delimiters. ]

    To enable that, just do this - move the cursor to a blank line in the file, where you want that output to appear. You could insert comment delimiters above and below that line if you wish. Then do this:

    !!schema-reporting-script-name optional_arguments ENTER

    That’s a double exclamation mark at the start of the above command.
    This results in vim spawning a shell, the shell runs that schema command, then vim pulls in the output of the command, which REPLACES the blank line that the cursor was on.

    There are more advanced versions of this one - which are even more powerful for programming - such as, having that output replace, not just the single blank like, but any range of lines in the file you choose it to. Of course, you can also have the output appended to the file, or inserted at the beginning of the file.

    However, I won’t go into those examples right now for lack of time. But if you want to know it, check out the !! command in the vim help.

    - Vasudev

  14. [...] you want to know more about Vim I wrote an article on Eric Wendelin’s [...]

  15. [...] Vi Cheat Sheet - Who doesn’t love Vi/Vim. Also check out my guest post on Vim. [...]