Getting Started with Vim

Vi/Vim is one of the most popular editors in the programming community. Vim has been around for decades, and offers many advantages and efficiencies, provided you are willing to learn it. Today, I hope to help you on the path of learning Vim. We will explore the basics of Vim in this tutorial, and there will be another one for using Vim in Ruby on Rails development which will be published soon.

A Brief History of Vi and Vim

Before the appearance of the UNIX, the text editor “ed” appeared, written by Ken Thompson in 1971. ed is regarded as one of the oldest text editors ever, as well as the first to implement the concept of Regular Expressions.

After a short period, the “ex” text editor appeared. ex is short for “EXtend”, as it adds some features to ed and to make it simpler.

Vi appeared in 1976, written by Bill Joy which for the BSD operating system. Licensed, of course, under the license with the same name as the operating system (the BSD license).

Vi is regarded as an addition to ex which had only 2 of vi‘s current modes. We will explore the concept of modes and how to use them, in this tutorial.

After a few years, other editions began to appear, the most famous one bding Vim which is short for “Vi Improved”.

In 1991 Bram Moolenaar started to work on Vim. The goal was to build an Amiga compatible text editor to edit source code. Vim is licensed under GPL as an open source program. Vim only worked in the shell until 1996,when the first GUI interface made it’s debut. At this time, Vim bac was at version 4.

Vim can be used to edit files using network protocols like SSH and HTTP.

Vim includes multilevel undo/redo.

Vim allows the screen to be split for editing multiple files.

Vim can edit files inside a compressed archive (gzip, zip, tar, etc).

Vim includes a built in diff for comparing files (vimdiff).

Vim includes support for plugins, and finer control over config and startup files.

Vim can be scripted with vimscript, or with an external scripting language (e.g. python, perl, shell).

Installing Vim

On Ubuntu

If you’re using a GNOME-based desktop, such as Unity, you can use vim-gnome which is a GUI version of Vim. To install, type in a terminal

sudo apt-get install vim-gnome

If you’re running another desktop environment, such as XFCE, LXDE, or KDE, you can use vim-gtk which doesn’t depend on as many extra library files as vim-gnome. To install, type in a terminal:

sudo apt-get install vim-gtk

NOTE:
As of Ubuntu 6.10 (Edgy Eft), the default Vim install is a cut-down version called “vim-tiny”. In order to get the full version complete with the online help documentation, and many of the advanced functions such as code folding; you will need to install “vim”:

sudo apt-get install vim

On MacOSX

In Mac OS X, the package managers are Homebrew and MacPorts. There is a project called MacVim which is a GUI interface for Vim. To install it using Homebrew, just type:

brew install macvim --override-system-vim

This will create vim, vimdiff, etc. symlinks to mvim in /usr/local/bin/vim. You need to make sure /usr/local/bin is before /usr/bin in your PATH. MacVim come with built-in support for Ruby, which will be useful when integrating some plugins, like Command-T.

On Windows

Download Vim: Go to Vim Download page and click on “PC: MS-DOS and MS-Windows”. Click on the gvim72.exe, which is a Self-installing executable, or download gvim72.exe directly.

Installing: After downloading click on gVim72.exe, which will install gVim on your Windows as shown below.

Beginning Vim

Here is a common scenario when people try to use Vim for the first time:

Start Vim and try to type ‘test’

Alarmingly, only the letter ‘t’ is printed!

Try to close vim, but they can’t figure out how.

Force quit or kill the process.

Forget about Vim and never try to use it again.

Unbeknowst to many beginners, there are plenty of useful resources to learn the basics of Vim. There’s the well known vimtutor (which you can use by typing vimtutor in the terminal and it will introduce you to the basics in less than 30 minutes) or the awesome game Vim Adeventures. Why not to give them a try before hitting vim from the terminal or starting the GUI version of Vim?

Yes, Vim is not straightforward at the start, but once you learn the basics, it’s easier to continue grasping more of it. Many people say that Vim has a formidable learning curve, which I consider the price for the efficiency in manipulating text that comes after with practice.

Vim is like a game: You start playing it while knowing just the basics, then you learn more and more. After some time, you start composing or chaining commands effectively, you build muscle memory, and then you’re on the downhill slope. Speaking of muscle memory, it is recommended to keep a cheat sheet like this one handy while you use Vim.

You can start Vim by typing vi or vim in the terminal, or vim in graphical mode by typing gvim on Linux or macvim on the Mac. Doing so should bring up a blank screen, with details about Vim. However, most attempts to type text will fail! You are in the wrong mode! This brings us to the most confusing feature for beginners: modes.

Vim Modes

Vim assumes that users edit text more often than they type it. Hence, it has a mode for inserting text and several modes for editing text. The behavior of Vim depends on which mode is current:

Command mode is the default mode of Vim. It provides a library of keyboard-based commands to edit text. Pressing the escape key switches back to this mode.

Insert mode allows for the insertion of text. This is the functionality most users associate with text editors. Pressing the i key in command mode switches to insert mode.

Vim Commands

Vi’s design is very similar to that of the Unix operating system. That is, functionality is provided through a library of simple commands that can be combined into more complex commands.

For example, the w command moves the cursor to the beginning of the next word. The d command is the deletion command. Thus, dw deletes the next word; d2w deletes the next two words. This is how composing actions based on commands works.

Here is a very clever cheat sheet that will introduce you to the basic Vim movement commands. Have a look at it and practice each command. Also, here is another very useful cheat sheet for a reference while using/learning Vim.

As a beginner, you should be able to (all of these are in command mode):

Switch between command mode and insert mode.

To switch from command mode to insert mode and insert text at the current cursor position, press i.

To switch from command mode to insert mode and insert text at the beginning of the line, press I.

To switch from command mode to insert mode and insert text at the end of the line, press A.

To switch from insert mode back to command mode use Esc.

Opening new lines

To open a new line after the current one and begin inserting text (switching to insert mode) use o.

To open a new line before the current one and begin inserting text (switching to insert mode) use O.

Navigating in the source using hjkl

Navigate up a line, press k.

Navigate down a line, press j.

Navigate left a character, press h.

Navigate right a character, press l.

Save

To save current edits use :w (short for write).

Exit

To exit, type :q (short for quit).

To save and exit, type :wq.

To force exit without saving, type :q!.

To force save and exit, type :wq!.

Undo

To undo last edit use u.

Redo

To redo use CTRL + r.

Copy and paste

To select a block of a text, Ctrl + v to switch to the visual mode, then select a block using the directional keys (hjkl).

To copy the selected block, yy (yank line).

To paste the selected block, p (paste).

To paste before cursor,P.

Tab complete

To use tab completion, CTRL + p.

Move to beginning and end of a file

To move to the beginning of the line, 0.

To move to the end of the line,$.

Substitute/Replace

To substitute the character under the cursor, type r followed by the character you will substitute.

To switch to replace mode use Shift + r and start typing.

Combine operators (like delete) with motions (like end of word)

As mentioned, Vim commands are composable. So you can combine operations like delete/change/copy with motions like beginning/end of word/line.

Using the Arrow Keys

In Vim, you can use arrow keys in both command and insert mode, but this is bad practice. You should use hjkl for navigation to build your muscle memory. Similarly, don’t use the Home or End buttons, just stick with the $ and ^ to move to the end and beginning of a line, respectively.

You can unmap the arrow keys to avoid temptation. Just add the following lines to your vimrc file:

Changing Case and Repeating a Command

Vim provides three awesome commands for text manipulations. I often find experienced Vim users that don’t know about them, which is really strange. The three commands are:

~ (tilde) – toggle the casing of a letter/selection (upper-case/down-case).

. (dot) – repeat the last set of commands (use in a combination with search, such as *, and jumps).

* (star) – to search and highlight for the word under the cursor.

Setting Up Vim

When Vim starts up, it loads a file called .vimrc (_vimrc on Windows), which holds the configuration settings. It is found in your home dirctory, specified by $HOME (Windows) or ~ (Unix).

Type :help vimrc in Vim to see some documentation about it. In this tutorial, we will edit the vimrc file to add some plugins and customizations.

Bare Minimum .vimrc

It is recommended to start customizatoin with a bare minimum .vimrc file. Yes, there are many popular developers who share their dotfiles (configuration files), but they built it along their way, depending on their usage and needs. So, why just copy it entirely??? I think every user should start with a bare minimum .vimrc file and configure it according to his/her needs.

Recovering from Errors

Errors in your vimrc file may prevent Vim from starting successfully. A reliable way to handle this case is to rename your vimrc file, start vim, and edit the renamed file. Alternatively, you could start Vim with a command like this (or use “GVim/MacVim” if that is how you run Vim):

vim -N -u NONE -U NONE

The -N starts in “not compatible” mode (that is, with extra Vim features). The NONE argument (must be uppercase) skips initializations and does not read vimrc (-u), and does not read any gvimrc file (-U).

Using the Vundle Plugin Manager

Vim has a plugin system which can be used to add more functionality. These plugins are implemented as simple configuration files, located in subdirectories inside the $HOME/.vim directory. If you are using a lot of plugins, managing them can be a hassle, so a plugin manager can help take care of them effectively.

There are a few plugin managers for Vim, like Vundle and Pathogen, which make it super easy to add, install, update, search, or remove any plugin. Here, we will be exploring how to use Vundle.

Vundle is a short for Vim Bundle. To install it, you need to have Git first. Here is a guide on how to install git. Once git is installed, you can install Vundle following the steps below.

set nocompatible " be iMproved, required
filetype off " required
" set the runtime path to include Vundle and initialize
set rtp+=~/.vim/bundle/Vundle.vim
call vundle#begin()
" alternatively, pass a path where Vundle should install plugins
"call vundle#begin('~/some/path/here')
" let Vundle manage Vundle, required
Plugin 'gmarik/Vundle.vim'
" The following are examples of different formats supported.
" Keep Plugin commands between vundle#begin/end.
" All of your Plugins must be added before the following line
call vundle#end() " required
filetype plugin indent on " required

4- Add the plugins:

Now you can add any plugin you want just by adding the word Plugin and the URL for it or its Git repository (it doesn’t matter if the repository is on Github, another server, or even on your machine, just add the path to it.)

As an example, to add the vim-fugitive plugin, place the following line inside the call vundle#begin() and call vundle#end() block.

Plugin 'tpope/vim-fugitive.git'

NOTE:
We didn’t add the full git URL (which is ‘git@github.com:tpope/vim-fugitive.git’) because Vundle will automatically do that for us if the repository is hosted on Github. If it’s not on Github, add the full path.

5- Installing the plugins

To install the plugin, launch vim and run :PluginInstall or from the command line just type:

$ vim +PluginInstall +qall

6- Searching for plugins

One of the most useful functions of Vundle is the ability to find and install more plugins.

To list every plugin that Vundle can find on the Vim Scripts site use:

:Plugins

Or

:PluginSearch!

The “!” at the end of the command refreshes the local list from the Vim Scripts site.

If we want to search for a specific plugin, use:

:PluginSearch! plugin_query

7- Deleting plugins

To delete a specific plugin, you need to list the plugins first by using the command :PluginList, then move to the plugin line and hit D to mark it for deletion. Then, run the command :PluginInstall.

NOTE:
After doing so, the plugin is the vimrc file, and you can reinstall it by typing :PluginInstall.

Their is an easier way to delete a plugin, simply delete it from the vimrc file and issue the command :PluginClean, which deletes any plugin that is not in your vimrc file.

Vim Themes/Color Schemes

You can add as many Vim color schemes into your Vim as you like. There are plenty of color schemes out there, varying from bright ones to dark ones. Here is a link to the most popular schemes. Let’s explore how to add these schemes to Vim.

Each color scheme comes in a file with a .vim extension. All you need to do is download the file to the colors subdirectory, found inside the ~/.vim directory. Then, from your vimrc file, change the line colorscheme badwolf to the name of your selected color scheme. Alternatively, you can use this awesome color scheme scroller plugin.

Color Scheme Scroller Plugin

It can be difficult to test color schemes when changing them manually in the vimrc file. Imagine that you have a list of 15 color schemes and you need to select a good one that matches your mood. That will be painful!

Here is the advantage of the color scheme scroller plugin, which allows you to scroll through the schemes using your arrow keys and preview themes quickly and easily.

Just put the following line into the vundle block in your vimrc file:

Plugin 'https://github.com/vim-scripts/ScrollColors'

And follow it up with :PluginInstall, which will install the plugin.

After a Vim restart, type :SCROLL and use your arrow keys to quickly preview the color schemes. Neat, eh?

This plugin only allows you to view the themes in the currently opened Vim session. If you restart Vim, the color scheme change will not take effect, so you need to add your selected color scheme to your vimrc manually, as mentioned above.

Vim Replacement Icons

The defualt Vim icon is a bit old, here is a list of some alternatives:

Summary

After reading this tutorial, you know the basics of Vim and how to customize it to add any plugins that suit you. In the next part, we will explore how to customize Vim for Rails development, specifically. When we’re done, Vim will be transformed into a full featured RoR text edior.

Islam is a freelance web developer with experience spanning the full stack of application development. He is a co-founder of Whitespace which is a web development agency. Besides for that he spends his time working on open source projects that he find intriguing or writing tutorials. He was an ex-Google Summer of Code student in 2012 and a mentor for 2 projects in 2013 for KDE. You can find him on Twitter @wazery_ or check his Linkedin profile linkedin.com/in/wazery.

Free Guide:

7 Habits of Successful CTOs

"What makes a great CTO?" Engineering skills? Business savvy? An innate tendency to channel a mythical creature (ahem, unicorn)? All of the above? Discover the top traits of the most successful CTOs in this free guide.

Anh Ho

It’s a pretty handy post! I like the way of delivering proper syntax with practical usage. Hope to see more your upcoming entries.

Dragan

Thanks :)

Michael

Yes, I totally agree. Really awesome post! I found the Learning Resources list at the bottom to be very helpful, too.

Jānis

Using neovim for ~6months now, but still learned some new stuff – thanks for post! Awesome!