Vim Template Files and :keepalt

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

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!
        autocmd BufNewFile */sixohthree.com/content/*.md 0r %:s?content/.*?templates/article.md?
    augroup END
endif

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 */sixohthree.com/content/*.md keepalt 0r %:s?content/.*?templates/article.md?

,b is safe again!