Create A Built-in Vim Cheatsheet

Oct 9 2014

I'm always forgetting the cool Vim tricks I hear about. At first I kept a text file of various tips and commands. Then I realized how dumb that idea was. Why not make it easy on myself? So I created my own Vim help module.

Now whenever I want that quick reminder, I can type :h myhelp in Vim and see my personalized cheat sheet. And it's really simple to do. Here's how.

Step 1: Create a Simple Vim Plugin

This part is simple:

$ mkdir -p myhelp/doc
$ touch myhelp/doc/myhelp.txt

That's it. I use the Janus Vim setup, so I put the myhelp/ directory in ~/.janus. In any other system, you can put your myhelp/ directory wherever your Vim searches for plugins.

Step 2: Create Some Help!

The Vim help text syntax is basic. You can read all about it in :h helphelp. Here's a snippet of my file:

*myhelp.txt*    For Vim version 7.4 Last change: 2014 October 8
*myhelp*

Matt's cheat sheet of Vim stuff he always forgets.

===============================================================================
CONTENTS

    1. Normal Mode.......................................|myhelp-normal|
    2. Visual Mode.......................................|myhelp-visual|
    3. Insert Mode.......................................|myhelp-insert|

===============================================================================
1. Normal Mode                                         *myhelp-normal*

   - :wall : Save modified buffers
   - :x : Save buffer only if modified, then exit (better than :wq)
   - ]] : next section
   - ]m : next method

You can view the entire file in my GitHub repo.

The contents of the first line are pretty much pre-determined:

*filename.txt*    For vim_version    Last change: YYYY Month D

The *myhelp* registers a tag. In short, it tells Vim that when I type :h myhelp I want it to go to this file. In fact, anytime you want to create a new tag, just surround a string with asterisks (*foo*). Just remember that your tags must be unique to the entire help system, including other Vim plugins.

After that, the file format is really up to you. I built a fancy table of contents with internal tag links (|myhelp-normal| links to the tag *myhelp-normal*). Vim treats the long lines of === as section breaks.

From there, I just wrote some free-form text.

Step 3: Generate the Tags File

Vim uses a special file, called a tags file, to correlate tags (like *myhelp*) to the document that contains the file (myhelp.txt). While these are just plain text files that you could create on your own, Vim will create them for you with a simple command:

:helpt /path/to/myhelp

Point it to the directory that contains your help text. helpt will walk all of the subdirectories looking for helptext and generating tags files.

Once you run that, your ready to use your personal cheat sheet.

You may need to restart Vim, but at this point :h myhelp should open your custom help file.