Customizing Your Vim for work area

(Read more interesting articles on Hacking Vim 7.2 here.)

Work area personalization

In this article, we introduce a list of smaller, good-to-know modifications for the editor area in Vim. The idea with these recipes is that they all give you some sort of help or optimization when you use Vim for editing text or code.

Adding a more visual cursor

Sometimes, you have a lot of syntax coloring in the file you are editing. This can make the task of tracking the cursor really hard. If you could just mark the line the cursor is currently in, then it would be easier to track it.

Many have tried to fix this with Vim scripts, but the results have been near useless (mainly due to slowness, which prevented scrolling longer texts at an acceptable speed). Not until version 7 did Vim have a solution for this. But then it came up with not just one, but two possible solutions for cursor tracking.

The first one is the cursorline command , which basically marks the entire line with, for example, another background color without breaking the syntax coloring. To turn it on, use the following command:

:set cursorline

The color it uses is the one defined in the CursorLine color group. You can change this to any color or styling you like, for example:

:highlight CursorLine guibg=lightblue ctermbg=lightgray

Customizing Your Vim for work area

If you are working with a lot of aligned file content (such as tab-separated data), the next solution for cursor tracking comes in handy:

:set cursorcolumn

This command marks the current column (here the cursor is placed) by coloring the entire column through the entire file, for example.

As with the cursor line, you can change the settings for how the cursor column should be marked. The color group to change is named cursorcolumn.

Adding both the cursor line and column marking makes the cursor look like a crosshair, thus making it impossible to miss.

Even though the cursorline and cursorcolumn functionalities are implemented natively in Vim, it can still give quite a slowdown when scrolling through the file.

Adding line numbers

Often when compiling and debugging code, you will get error messages stating that the error is in some line. One could, of course, start counting lines from the top to find the line, but Vim has a solution to go directly to some line number. Just execute :XXX where XXX is the line number, and you will be taken to the XXX line.

Alternatively, you can go into normal mode (press the Esc key) and then simply use XXXgg or XXXG (again XXX is the line number). Sometimes, however, it is nice to have an indication of the line number right there in the editor, and that's where the following command comes in handy:

:set number

Now, you get line numbers to the left of each line in the file. By default, the numbers take up four columns of space, three for numbers, and one for spacing. This meansthat the width of the numbers will be the same until you have more than 999 lines. If you get above this number of lines, an extra column will be added and the content will be moved to the right.

Of course, you can change the default number of columns used for the line numbers. This can be achieved by changing the following property:

:set numberwidth=XXX

Replace XXX with the number of columns that you want.

Even though it would be nice to make the number of columns higher in order to get more spacing between code and line numbers, this is not achievable with the numberwidth property. This is because the line numbers will be right-aligned within the columns.

In the following figure, you can see how line numbers are shown as right-aligne when a higher number of columns are set in numberwidth:

You can change the styling of the line numbers and the columns they are in by making changes to the LineNr color group.

Spell checking your language

We all know it! Even if we are really good spellers, it still happens from time to time that we misspell a word or hit the wrong keys. In the past, you had to run your texts (that you had written in Vim) through some sort of spell checker such as Aspell or Ispell . This was a tiresome process that could only be performed as a final task, unless you wanted to do it over and over again.

With version 7 of Vim, this troublesome way of spell checking is over. Now, Vim has got a built-in spell checker with support for more than 50 languages from around the world.

The new spell checker marks the wrongly written words as you type them in, so you know right away that there is an error.

The command to execute to turn on this helpful spell checker feature is:

:set spell

This turns on the spell checker with the default language (English). If you don't use English much and would prefer to use another language in the spell checker, then there is no problem changing this. Just add the code of the language you would like to use to the spelllang property . For example:

:set spelllang=de

Here, the language is set to German (Deutsch) as the spell checker language of choice. The language name can be written in several different formats. American English, for example, can be written as:

  • en_us
  • us
  • American

Names can even be an industry-related name such as medical. If Vim does not recognize the language name, Vim will highlight it when you execute the property-setting command.

If you change the spelllang setting to a language not already installed, then Vim will ask you if it should try to automatically retrieve it from the Vim homepage.

Personally, I tend to work in several different languages in Vim, and I really don't want to tell Vim all the time which language I am using right now.

Vim has a solution for this. By appending more language codes to the spelllang property (separated by commas), you can tell Vim to check the spelling in more than one language.

:set spelllang=en,da,de,it

Vim will then take the languages from the start to the end, and check if the words match any word in one of these languages. If they do, then they are not marked as a spelling error. Of course, this means that you can have a word spelled wrong in the language you are using but spelled correctly in another language, thereby introducing a hidden spelling error.

You can find language packages for a lot of languages at the Vim FTP site:

Spelling errors are marked differently in Vim and Gvim.

In regular Vim, the misspelled word is marked with the SpellBad color group (normally, white on red).

In Gvim, the misspelled word is marked with a red curvy line underneath the word. This can, of course, be changed by changing the settings of the color group.

Customizing Your Vim for work area

Customizing Your Vim for work area

Whenever you encounter a misspelled word, you can ask Vim to suggest better ways to spell the word. This is simply done by placing the cursor over the word, going into the normal mode (press Esc), and then pressing Z + =.

Customizing Your Vim for work area

If possible, Vim will give you a list of good guesses for the word you were actually trying to write. In front of each suggestion is a number. Press the number you find in front of the right spelling (of the word you wanted) or press Enter if the word is not there.

Often Vim gives you a long list of alternatives for your misspelled word, but unless you have spelled the word completely wrong, chances are that the correct word is within the top five of the alternatives. If this is the case, and you don't want to look through the entire list of alternatives, then you can limit the output with the following command:

:set spellsuggest=X

Set X to the number of alternative ways of spelling you want Vim to suggest.

Adding helpful tool tips

In the Modifying tabs recipe, we learned about how to use tool tips to store more information using less space in the tabs in Gvim. To build on top of that same idea with this recipe, we move on and use tool tips in other places in the editor.

The editing area is the largest part of Vim. So, why not try to add some extra information to the contents of this area by using tool tips?

In Vim, tool tips for the editing area are called balloons and they are only shown when the cursor is hovering over one of the characters. The commands you will need to know in order to use the balloons are:

  • The first command is the one you will use to actually turn on this functionality in Vim.
    :set ballooneval
  • The second command tells Vim how long it should wait before showing the tool tip/balloon (the delay is in milliseconds and as a default is set to 600).
    :set balloondelay=400
  • The last command is the one that actually sets the string that Vim will show in the balloon.
    :set ballonexpr="textstring"

This can either be a static text string or the return of some function.

In order to have access to information about the place where you are hovering over a character in the editor, Vim provides access to a list of variables holding such information:

abc<space>and abc<enter> Both expand
123abc<space> Will not expand as the abbreviation is part of a word
abcd<space> Will not expand because there are letters after the abbreviation
abc Will not expand until another special letter is pressed

So with these variables in hand, let's look at some examples.

Example 1:

The first example is based on one from the Vim help system. It shows how to make a simple function that will show the information from all the available variables.

function! SimpleBalloon()
return 'Cursor is at line/column: ' . v:beval_lnum .
\'/' . v:beval_col .
\ ' in file ' . bufname(v:beval_bufnr) .
\ '. Word under cursor is: "' . v:beval_text . '"'
set balloonexpr=SimpleBalloon()
set balloonevalcode 59

The result will look similar to the following screenshot:

Customizing Your Vim for work area

Example 2:

Let's look at a more advanced example that explores the use of balloons for specific areas in editing. In this example, we will put together a function that gives us great information balloons for two areas at the same time:

  • Misspelled words: The balloon gives ideas for alternative words
  • Folded text: The balloon gives a preview of what's in the fold

So, let's take a look at what the function should look for, to detect if the cursor is hovering over either a misspelled word or a fold line (a single line representing multiple lines folded behind it).

In order to detect if a word is misspelled, the spell check would need to be turned on:

:set spell

If it is on, then calling the built-in spell checker function—spellsuggest()—would return alternative words if the hovered word was misspelled. So, to see if a word is misspelled, just check if the spellsuggest() returns anything. There is, however, a small catch. spellsuggest() also returns alternative, similar words if the word is not misspelled. To get around this, another function has to be used on the input word before putting it into the spellsuggest() function . This extra function is the spellbadword(). This basically moves the cursor to the first misspelled word in the sentence that it gets as input, and then returns the word. We just input a single word and if it is not misspelled, then the function cannot return any words. Putting no word into spellsuggest() results in getting nothing back, so we can now check if a word is misspelled or not.

It is even simpler to check if a word is in a line, in a fold. You simply have to call the foldclosed()function on the line number of the line over which the cursor is hovering (remember v:beval_lnum ?), and it will return the number of the first line in the current fold; if not in a fold, then it returns -1. In other words, if foldclosed(v:beval_lnum) returns anything but -1 and 0, we are in a fold.

Putting all of this detection together and adding functionality to construct the balloon text ends up as the following function:

function! FoldSpellBalloon()
let foldStart = foldclosed(v:beval_lnum )
let foldEnd = foldclosedend(v:beval_lnum)
let lines = []
" Detect if we are in a fold
if foldStart < 0
" Detect if we are on a misspelled word
let lines = spellsuggest( spellbadword(v:beval_text)[ 0 ], 5, 0 )
" we are in a fold
let numLines = foldEnd - foldStart + 1
" if we have too many lines in fold, show only the first 14
" and the last 14 lines
if ( numLines > 31 )
let lines = getline( foldStart, foldStart + 14 )
let lines += [ '-- Snipped ' . ( numLines - 30 ) . ' lines --' ]
let lines += getline( foldEnd - 14, foldEnd )
"less than 30 lines, lets show all of them
let lines = getline( foldStart, foldEnd )
" return result
return join( lines, has( "balloon_multiline" ) ? "\n" : " " )
set balloonexpr=FoldSpellBalloon()
set ballooneval

The result is some really helpful balloons in the editing area of Vim that can improve your work cycle tremendously. The following screenshot shows how the information balloon could look when it is used to preview a folded range of lines from a file:

Customizing Your Vim for work area

Instead, if the balloon is used on a misspelled word, it will look like the following screenshot:

In Production Boosters, you can learn more about how to use folding of lines to boost productivity in Vim.

(Read more interesting articles on Hacking Vim 7.2 here.)

Using abbreviations

We all know the feeling of writing the same things over and over again, a dozen times during a day. This feeling is the exact opposite of what the philosophy of Vim tries to teach us.

The philosophy of Vim says that if you write a thing once, it is okay. However, if you're writing it twice or more times, then you should find a better way to do it.

One of the methods for getting around writing the same sentences over and over again is by using abbreviations.

In Vim, abbreviations are created with one of the following commands depending on which mode they should be available in:

  • :abbreviate: Abbreviations for all modes
  • :iabbrev: Abbreviations for the insert mode
  • :cabbrev: Abbreviations for the command line only

All of the commands take two arguments—the abbreviation and the full text it should expand to.

So, let's start with a simple example of where the abbreviations can come in handy.

Example 1: Using abbreviations for quick address insertion

I have moved around a bit during the last few years, so a common task for me is writing messages where I tell about my new address. It didn't take me long before I had an abbreviation ready, so I didn't have to write the entire address.

Here is what it looked like:

:iabbrev myAddr 32 Lincoln Road, Birmingham B27 6PA, United Kingdom

Now every time I need to write my address, I just write myAddr> and as soon as I press the Space> key after the word, it expands to the entire address.

Vim is intelligent about detecting whether you are writing an abbreviation or it is just part of another word. This is why myAddr only expanded to the full address when I pressed the Space key after the word. If the character right after my abbreviation was a normal alphabetic letter, then Vim would know that I wasn't trying to use my abbreviation and it would not expand the word. The examples with the abc abbreviation are as follows.

abc<space> and abc<enter>

Both expand


Will not expand as the abbreviation is part of a word


Will not expand because there are letters after the abbreviation


Will not expand until another special letter is pressed

A good place to keep your abbreviations so that you don't have to execute all the commands by hand is in a file in your VIMHOME. Simply place a file there—let's call it abbreviations.vim and write all your abbreviations in it. Then, in your vimrc file, just make sure that the file is read, which is done with the source command:

:source $VIM/abbreviations.vim

Every time you realize that you will need a new abbreviation, you first execute it and then you add it to your abbreviations.vim.

By now you have probably realized that you can use abbreviations for a lot of other interesting things. But anyway, here is a short list of examples to give you some ideas:

  • Correct typical keypress errors:
  • :iabbr teh the

  • Simple templates for programming:
  • :iabbr forx for(x=0;x<100;x++){<cr><cr>}

  • Easy commands in the command line:
  • :cabbr csn colorscheme night

Getting used to adding your abbreviations to a file every time you find a new one might seem weird and inconvenient at first. At the end of the day, however, you will realize that it has saved you a lot of typing and that it will keep doing so. The only thing you have to do is add your abbreviations and reload the abbreviations file once in a while.

Sometimes, it can be annoying that abbreviations automatically change when you actually wanted to write something else. Let's say that you have an abbreviation for your address called "addr", but you actually want to write the word "addressed". In that case, your abbreviation would kick in and you would not be able to write the word easily.

A solution for this is to change your abbreviation to use a function that asks you whether or not to use the abbreviation before it actually inserts the word.

An example of such a function could be the following:

function! s:AbbrAsk(abbr,expansion)
let answer = confirm("Use the abbreviation '" . a:abbr . "'?",
"&Yes\n&No", 1)
return answer == 1 ? a:expansion : a:abbr

The function is called AbbrAsk and takes two arguments. The first argument is the abbreviation and the second argument is the expanded abbreviation. For our address example, this function would be used as follows:

:iabbrev <expr> addr <SID>AbbrAsk('addr', "your full address

So, now when you write the letters addr, you will be asked whether you would like to use the abbreviation or not.

Modifying key bindings

All of us have probably, at some point, used an editor other than Vim. Because of this, most of us have learned to use some very specific keyboard shortcuts for doing different tasks. Even though the key bindings for the keyboard shortcuts in Vim are created with ease and use of speed in mind, sometimes it can still be faster to use the shortcuts you already know.

To facilitate this, Vim gives you the possibility to rebind almost every single key binding it has.

In this recipe, we will learn how to change the key bindings when using Vim in different modes.The main commands to know when dealing with key bindings are:

  • :map: For the Normal, Insert, Visual, and Command-line modes
  • :imap: For the Insert mode only
  • :cmap: For the Command-line mode only
  • :nmap: For the Normal mode only
  • :vmap: For the Visual mode only

Each of the command takes two arguments—the first is what keys the command should be bound to, and the second is the command to bind. So, let's look at an example. Say you can't really get used to saving an open file by executing :w in the normal mode because you are used to using Ctrl-S to save a file and would like to keep it like that.

A mapping for this could be:

:map <C-s> :w<cr>

Notice the <C-s>;in the key binding. This is the Vim way for writing 'key combination Ctrl+S'. Instead of C (Ctrl), you could also use A (Alt) or M (Meta). The <cr> at the end of the command is what actually executes the command. Without it, the command would simply be written to the command line but not executed.

There are several other special notations for some of the other keyboard keys. The following table shows the most common of them:

Keys Notation
<BS> Backspace
<Tab> Tab
<CR> Enter
<Enter> Enter
<Return> Enter
<Esc> Escape
<Space> Space
<Up> Up arrow
<Down> Down arrow
<Left> Left arrow
<Right> Right arrow
<F1> <F12> Function keys 1 to 12
#1 #9#0 Function keys F1 to F9, F10
<Insert> Insert
<Del> Delete
<Home> Home
<End> End
<PageUp> Page up
<PageDown> Page down

Maybe you only want to be able to save when you are in the insert mode and actually editing the file. To change the command for this, you only need to have the following:

:imap <C-s> <esc>:w<cr>a

So, what happens now is that you map the Ctrl+S to do a combination of key presses. First, press <esc>; (the Escape key) to get out of the insert mode and into the normal mode. Then, use :w<cr> to execute the actual saving of the file, and finally the a to get back into the insert mode and go to the end of the line.

You could expand the mappings to fit all of the standard copy / paste / cut / save shortcuts from many applications. This could be constructed like this:

" save file (ctrl-s)
:map <C-s> :w<cr>
" copy selected text (ctrl-c)
:vmap <C-c> y
" Paste clipboard contents (ctrl-v)
:imap <C-p> <esc>P
" cut selected text (ctrl-x)
:vmap <C-x> x

If you are in Gvim, you can even get dialogs shown for the save-as and Open functionalities.

"Open new file dialog (ctrl-n)
:map <C-n> :browse confirm e<cr>
"Open save-as dialog (ctrl-shift-s)
:map <C-S-s> :browse confirm saveas<cr>

You can get into a situation where you map a key combination in which the first key is actually bound to a function of its own. An example could be the $ key, which is bound to the "jump to end of line" functionality in Vim. You might, however, want to have a key binding like $1 for some functionality, $2 for some other functionality, and so on. The mapping could then look like:

:map $1 :MyFunction1()<cr>
:map $2 :MyFunction2()<cr>

Now when you press $, Vim will wait for one second after you press the $ key, and if it does not get the second character in the key binding before the timeout, it will execute the normal "jump to end of line" functionality. However, if you press 1 before the timeout, it will execute your Myfunction1()function instead.

With the ability to change the keyboard mapping in Vim, you really have an access to a powerful way of modifying the editor completely according to your needs.

You can read more about mappings in the Vim help system under:

:help key-mapping


In this article, we looked at how to make Vim a better editor for you by modifying it according to your personal needs.

We started by learning about how basic modifi cations of font and color scheme can give your editor a personalized look.

Then we dived a bit deeper into using colors for marking search matches, thereby making them easily recognizable.

To get the most out of an editor like Vim, you would often like it to have a large area for editing the files and less space spilled on the GUI. We looked at ways of modifying both the status line and tabs to be smaller and more informative.

Even though the menu bar and toolbar can be unimportant and just take up screen real estate, they can also be very useful additions to your editor. In this chapter, we learned how to add our own menu to the menu bar and even how to add icons that are full of functionality to the toolbar.

Many things can be done to the editing area to make it fit your personal needs. In this article, we looked at how to make it easier to get an overview of the editing area. Better and more visual cursors have been proposed, and line numbers have been added to the area.

We also looked at how to make the spell checker in Vim follow your preferred language, so that you will never again misspell a word. If using spell checker is not enough to correct your errors, then maybe the use of abbreviations can help you.

Finally, we looked at how we can change the key bindings in Vim in such a way that it will react on keyboard shortcuts you are used to from other editors.

You have a fully personalized Vim editor with all the recipes in this article and you are now ready to move on and learn more about how you can optimize your navigation around the files in Vim.

If you have read this article you may be interested to view :

You've been reading an excerpt of:

Hacking Vim 7.2

Explore Title