A brief (A brev) useful feature in Vim for new coders.

·

2 min read

Starting in Vim can seem so hard, but boy oh boy it's worth it.

I've learned so much and it sort of feels like coming home, you know?

As a programmer, as I learn and develop, I don't want to keep typing what I already know; I want to focus instead on learning what I don't.

So naturally, abbreviations and mapping are something I would want to work with.

Abbreviations

Using an abbreviation means that I can type a combination that I wouldn't normally use such as 'cm' (without the single quotes), which expands to:

/* */

or 'pf' which expands to:

printf("");

I've just got to make sure I remember that I've created them. See below for how to add these to your ~/.vimrc file.

Mapping

On the same bent right now is mapping.

By pressing a key of my choosing when combined with a 'leader' key (so I don't accidentally ruin standard shortcuts), I can begin creating templates for C. For example, if I press \t then this template appears:

#include <stdio.h>

int main (void)
{
     |<-- cursor here 
    return 0;
}

... Yes... that's two letters, '\t'.

How To Do this Magic?

Open your .vimrc configuration file and preface any abbreviations you want as follows (I've included the two from above):

" printf abbreviation 
ab pf printf("")
" comment abbreviation
ab cm /*  */

then save the file. C'est voila like we say in these parts and you're good to go. Mapping is slightly different but the same principle:

map <leader>t i#include <stdio.h>^M^Mint main (void)^M{^M^Mreturn 0;^M}^[OA^[OA^[OA

The marks between what would be newlines or tabs are created by pressing CTRL-v when in Vim, followed by the relevant command key for example if I want an Enter/return to appear in my map, I press CTRL-v then return. This records as ^M and you can see after <stdio.h> I have two of them. For my abbreviations ('abbrevs') I've left some of these out for clarity, but it's possible with them also.

ANYHOO... Like my lady says, it's the little things in life that bring happiness.

Vim is always challenging me to think:

"But is there a better way to do {x,y,z}?".

Chances are that yes, there is, and it's already in there.