A Guide to Getting Started with ViM
Preface
Why use ViM?
With the abundance of WYSIWYG (What You See Is What You Get) text editors out there, why in the world would anyone use a (predominantly) command-line interface with obscure key bindings and a notoriously steep learning curve? I'll try to give some reasons I've heard elsewhere, as well as my own reasons why I decided to all but abandon conventional text editors like Word and Pages. I'll describe my current setup and how I learned to use the program, and in the future, I will try to elaborate my specific use of ViM in writing class notes in LaTeX.
Some reasons for using ViM:
Speed
This is probably the reason most people switch. One of the disadvantages of using a conventional text editor is switching between the mouse and the keyboard. The ViM editor does not require the use of the mouse (nor the arrow keys, if desired), and the lack of switching saves a ton of time. The actual speed gain is actually difficult to determine, and will vary for different people depending on how they use the various macros. The real reason you should invest in learning ViM is the next point:
Ergonomics
ViM is comfortable. The vast majority of commands require very little motion from your fingers, and they rarely involve holding down one key while pressing another, an action that strains the wrists. This is another reason ViM is preferable to similar editors like Emacs, as most Emacs commands start with the control key, usually located near the pinky fingers or sometimes the thumb (but regardless, rarely in a comfortable position).
Ubiquity
ViM commands work the same way on any system. Vi is actually standard on Unix systems, so most Unix-based servers will already have at least Vi installed. The installation process for ViM is extremely simple on most systems, and it's common to run into a ViM editor when using tools such as git
.
Customizability
You can change just about everything in the ViM editor from the key bindings to the color scheme to the window layout. You can create your own commands to do things which you find yourself repeating often, and you can overwrite keys which you wish to use in different ways.
Plugins
While ViM can do syntax highlighting for most languages without any extras, there is a vast library of plugins and extensions. Want to have a live preview of LaTeX or Markdown as you type? There's a plugin for that. Need tab completion for [insert programming language here]? There's a plugin for that.
Cost
Certainly the most important feature of ViM is that it is free and open-source (and this likely won't change).
Installation
The specific instructions for installing ViM are available on the download website. There are even instructions for installing ViM on iOS and Android (this seems a bit unnecessary). Rather than go over the installation details, I'd rather skip right to the most important part of setting up ViM: The .vimrc
file. This will also give us an opportunity to go over some of the basic ViM commands.
What is .vimrc
?
This file typically exists in your home drive (I will be using Unix file paths in this tutorial): ~/.vimrc
. To edit this file, you can use ViM! Of course, you don't have to, but might as well start learning as soon as possible. Before you type vim ~/.vimrc
, we should discuss how the ViM editor works.
Saving and Exiting
The first thing you should know how to do in ViM is exit the program. The exit command is :q
. Yes, I know I just said there weren't many commands the required you hold down a button, but this is one of them. It is important to note that the :q
command does not save the file. The command to save a file is :w
("q" for quit, "w" for write). I include these mnemonics because a lot of the commands in ViM have words associated with them that explain what they do, and it's a helpful way of memorizing commands. With practice, it becomes second nature. You can use these commands together as :wq
to save and exit. By default, :q
will warn you if you have unsaved changes. If you really want to get around this, you can type :q!
, where the !
overrides this warning. You can also use :wa
, wqa
, or qa!
to write, write and quit, or quit without writing "all" buffers. Here, a buffer refers to a file open in ViM.
Opening a File
Now that we know how to save a file, we should probably discuss opening them. There are lots of nifty ways to open files once you're already running a ViM session, but for now we'll just discuss opening an existing file (or creating a new one). Simply type vim filename
in a command line prompt. filename
can correspond to just a word, in which case ViM will create a file with that name in the current directory, or a path, in which case the file will be created in the corresponding path, given that the parent folders exist. Therefore, the command vim ~/.vimrc
will either open an existing file in your home drive called .vimrc
or it will create a new one.
Also note that you must specify file extensions when creating the file. This is important because it is one of the things that allows ViM to have extension-specific code highlighting (how would ViM know you're typing Python code if the file didn't end in .py
?). For those Unix beginners out there, .vimrc
is not the file extension of some weird, nameless file. The .
prefix causes this file to be hidden in most file browsers (and in the command line, you must use ls -a
to view these files). Files with no extension are perfectly okay and can be read and written to by ViM, just not necessarily by other programs. The .vimrc
file contains all of the preferences which we want to set for our ViM environment. Go ahead and open it now with vim ~/.vimrc
.
The file you have just opened is likely blank, unless someone has been using ViM on the system before. When you enter a new file in ViM, you will automatically be in NORMAL
mode. The write/quit commands above will only work in this mode, so try them now. Try not to press any other keys; If you do, just pres esc
a few times to get back into NORMAL
mode. This is basically the method you will use to get back to this mode from any other mode. Pressing esc
once will be enough to get you from another mode to NORMAL
, but if you accidentally pressed yourself halfway into a command, it won't hurt to press it a few more times to make sure you're back in NORMAL
mode. Later, we'll add a display that shows what mode you are in for convenience. When you press :
, notice that what you type appears in the bottom of the ViM environment. This is the ViM version of the command line. In fact, command line commands can be run here without exiting ViM by prefacing them with !
, so :!echo hello world
will do just that (try it now!).
Bear with me. I realize it's already been quite a bit of reading and we haven't even used this text editor to write anything yet. This is what people mean when they say ViM has a steep learning curve. Once you start to use it, everything I've been saying will make a lot more sense, but until then, it's going to feel like learning to type for the first time.
Writing Text
We will now learn the next most important mode, INSERT
mode. As the name suggests, this is the mode that actually allows you to type new text into your file. Press i
while in NORMAL
mode to enter insert mode. You can now type away! Everything in this mode works as you might expect with a typical editor, except for any commands like copy/paste or save/quit. For these, we have to exit back to NORMAL
mode (esc
). Remember to think of i
as shorthand for the word "insert". There are other ways to get into this mode also. I won't go over all of them right now, but a
for "append" starts your cursor after the word it is currently on (while i
starts before it). One tricky thing to get used to when learning ViM is that the cursor actually exists on a character rather than before or after it. For this reason, some users prefer to set their command line cursor to be an underscore rather than a vertical line. This small adjustment will be important in a few commands, but after a while, you'll get used to using both i
and a
without hesitating to think about where you want the cursor to go. Also, you can capitalize these commands for a very useful effect: I
goes to INSERT
mode at the beginning of a line and A
enters this mode at the end of the line. I find myself using A
a lot if I've just been editing something in the middle of a line and I want to pick up at the end to keep typing.
Navigation
Now that we're a bit comfortable adding text to a file and switching between NORMAL
and INSERT
mode, let's discuss one more thing that will help early on before we start making changes to .vimrc
. I told you there is no need to use a mouse in ViM. While you certainly can (I have some mouse functionality enabled in my setup), there are commands which you can use to move around your text while in NORMAL
mode. ViM prides itself in placing these movement keys in the home row, you know, the middle row of the keyboard where your hand is supposed to rest when you start typing. All navigation can be done with the right hand using the j
, k
, l
, and ;
keys (note that this is a semicolon rather than the colon we used to enter the write/quit commands above). These keys correspond somewhat to the arrow keys, and while the arrow keys can also be used, it is highly recommended that you practice with the home row keys since it will mean less moving around (and ergo, faster editing speeds). In ViM, j
= ↓
, k
= ↑
, l
= ←
, and ;
= →
. Practice this a bit in NORMAL
mode to get a feel for how it works with multiple lines of text. The j
and k
keys are under the most dominant fingers because you'll most often be moving up and down lines in NORMAL
mode. The l
and ;
keys are placed directionally (left and right) in the way that they operate. This may seem slower than just using a mouse right now. Believe me, for a time, I refused to restrict myself to jkl;
because I didn't think it was that much faster, and now I find myself pressing things like esc jA
in GMail absentmindedly. The more you use it, the more useful it will become. While optional, I highly recommend disabling the arrow keys entirely. This will be our first addition to .vimrc
. In that file, type the following:
noremap <Up> <Nop>
noremap <Down> <Nop>
noremap <Left> <Nop>
noremap <Right> <Nop>
For now, don't worry too much about what these commands mean (if you must know they remap the arrow keys to a "do nothing" key, and the no
prefix is a code for the modes in which this mapping will work. You can learn more about these by typing :help :map-modes
in NORMAL
mode, but we'll discuss these in more detail later).
Next, save the file and then use the command :source ~/.vimrc
(or :so ~/.vimrc
for short) to "source" the file, basically reading the settings into the current ViM environment. You should find that the arrow keys are totally useless now. The file gets automatically sourced when ViM is opened fresh, so there is no need to run this each time you open ViM, it is only needed when you want a change to be applied to the current session.
.vimrc
Settings
To wrap up this post, I'll go over some of the settings I have in my .vimrc
. Most of these commands come in the form set <property>
, so I'll list each one and explain what they do. You can feel free to add them to your .vimrc
file at your discretion. Many of these were collected over my time using ViM, but I got quite a few from a really great blog post.
set number
creates a column that displays line numbers. There are neat commands which allow one to jump back and forth using line numbers, so this is nice to have.set relativenumber
causes that number column to instead display the relative number of lines each line is away from the currently selected line. Trust me, this is far more useful. If you really care about what line you're currently on, it's still displayed with this setting.set autoindent
causes new lines to have the same indentation as the previous line. This is nice for most programming languages.set expandtab
turns tabs into spaces, which is also nice for programming.set filetype indent on
allows for certain extension-specific indentation rules to take effect.set smarttab
inserts spaces when thetab
key is pressed. How many spaces? See the next command.set tabstop=4
sets the number of spaces per tab indent.set wrap
enables line wrapping.syntax enable
well... enables syntax highlighting.set spell
enables spellcheck. Yes, ViM does have a built-in spell checker that I will hopefully elaborate on in a later post.set spelllang=en
is a useful addition to the previous setting if you happen to speak English.set history=1000
increases the undo limit to 1000 steps (yes you read that correctly). We'll discuss the undo/redo commands in the next post.set confirm
gives a nice prompt when closing an unsaved file.set ruler
makes the cursor always visibleset laststatus=2
makes the status bar at the bottom always visibleset backsapce=indent,eol,start
makes thebackspace
key work well with indentation and the start and ends of lines inINSERT
mode.
It can really be annoying to never be able to use your mouse in ViM, so I might as well tell you that set mouse=a
gives you some mouse functionality back (scrolling, moveing the cursor, highlighting, and resizing windows).
Finally, I want to mention a really nice feature of ViM. While I made a point about the lack of autosave above when discussing the write/quit commands, this wasn't entirely accurate. Sure, if you force the program to quit without saving, it won't save. However, if ViM crashes for some reason (or if your computer crashes, or if you close ViM externally), there will be two files which exist that contain information on everything written since the last save. These files are called the backup file, which is saved as <filename>.ext~
with a ~
after the typical file name, and the swap file, saved as <filename>.ext.swp
. The backup file contains the original file as it was before you started editing it. When you save with :w
, this file becomes identical to the current file. The swap file stores changes you made to the buffer, allowing you to recover those changes in the event of a crash. It also prevents you from opening the same file in multiple instances of ViM (for example, if you work on a multi-user system and many people could potentially edit a file with ViM, an error would show up if this file exists). These files kind of clutter up directories, so it's nice to save them all to one place. You can chose whatever file to store them in, but I keep my swap and backup files in a directory called ~/.vim/tmp
. The .vim
folder probably exists, but you'll have to create the subdirectory yourself. Once you do that, add the following lines to your .vimrc
:
set dir^=~/.vim/tmp//
set backupdir^=~/.vim/tmp//
The ^=
makes ViM check this directory first, and the //
at the end of the directory makes ViM use absolute paths to generate the file names to avoid conflicts. I believe this will eliminate the warning given if multiple users try to access the same file, so use it at your own discretion.
Another place where ViM outperforms conventional text editors is with the persistent undo feature, meaning you can save the undo history from your files even when you save and exit them. To do this, I followed Jovica Ilic's blog post, created a directory called ~/.vim/undodir
, and added set undodir^=/.vim/undodir//
to my .vimrc
. I slightly modified this from the blog post to match the note above.
In my next post, I'll talk about some more commands like undo/redo and copy/paste, as well as some useful key bindings, like spellchecking shortcuts and searching. You can look through the linked blog above for some more settings to add to your .vimrc
, and I will periodically mention useful settings that I have in mine. I need to put some comments into my .vimrc
before I post it here, but I'll eventually do that also when I find time.
Comments !