Vim Template Files and :keepalt

Annika Backstrom
in Technology, on 7 November 2020. It is tagged and #Vim. (history)

Today I learned about Vim's :keepalt, which fixes alternate-file in my use case when I'm also using Vim template files.

Vim's "alternate file" is changed to the previous "current file" any time the current file changes. CTRL-^ or :b# switch to the alternate file, and are a quick way to toggle between two files. I map this functionality to ,b and it's one of my most frequently used shortcuts:

let mapleader=","
map <leader>b <C-^>

I also use template files to populate new files automatically:

if has("autocmd")
    augroup templates
        autocmd BufNewFile */*.md 0r %:s?content/.*?templates/
    augroup END

I've always had a minor annoyance with templates: the template file does not show up in the buffer list :ls, but it does become the alternate file, and gets picked up by CTRL-^.

I finally set out to fix this today, which brought me to :keepalt. Prefacing the autocmd with keepalt keeps the template from becoming the alternate file, so you don't toggle back to a file you didn't actually edit.

autocmd BufNewFile */*.md keepalt 0r %:s?content/.*?templates/

,b is safe again!