Please note: this blog has been migrated to a new location at https://jakesgordon.com. All new writing will be published over there, existing content has been left here for reference, but will no longer be updated (as of Nov 2023)

Navigating Vim

Sun, Feb 13, 2011
Embracing Vim

The traditional way for moving around in Vim is the h,j,k,l keys. The reasoning is that it keeps your hands on the home row of the keyboard without having to move away to the arrow keys. The problem with this is that its just too much of a cognitive shift from traditional arrow key based editing. I think more important is learning to navigate beyond simple up/down/left/right.

Even more useful than navigating by search is to be able to follow tags. Depending on the language you are editing in, you may be able to setup an exuberant tags ctags file and use <C-]> to jump to the definition of the method currently under the cursor.

From the command line:

sudo apt-get install ctags
cd /path/to/my/project
ctags -R

Now from within vim in that same directory, if your cursor is over a call to method foo and you enter command <C-]> then vim will jump to the definition for method foo.

As programmers, our code is modularized and spread out amongst many files within our project structure. So, not only do we need to figure out how to navigate within a single file, we must also become efficient at finding and opening other files relevant to our task in hand. There are many plugins to make file management easier, and we will look at the most useful in a future post, but for now its best to start with the Vim basics so you can appreciate what the plugins are managing when you look into them later.

Vim maintains multiple buffers in memory for each open file. You can edit a new file from within vim:

 :e [FILENAME]

If your existing buffer has unsaved changes you will not be allowed to open a 2nd buffer. You can override this behavior by setting the hidden option:

 :set hidden

Once you have multiple buffers open you need to be able to switch between them. To see open buffers use the :ls or :buffer command. You will see a list of open buffers along with a buffer number as the first column. To view one of these buffers use the :buffer N command.

If you are anything like me you will find this very annoying. Luckily, thanks to various plugins (that I will show you in a future post) buffer management can be made a lot easier.