Autocommand for new file of specific filetype

brianmearns picture brianmearns · May 6, 2014 · Viewed 8.1k times · Source

I want to run some vim commands anytime I create a new file of a specific file type, sort of combination of the BufNewFile and FileType autocommand events.

I have BufNewFile autocommands setup in filetype.vim to set the filetype based on the file extension, but I have multiple extensions that all correspond to the same filetype. I'd like to encapsulate the information about which file-extensions correspond to a particular file-type just in this one place, and then have other autocommands run based just on the filetype. However, I can't just use the FileType event, because I only want to perform the commands for new files, not when editing existing files.

For instance, in filetype.vim, I have:

au BufRead,BufNewFile *.cir setfiletype spice
au BufRead,BufNewFile *.sp setfiletype spice
au BufRead,BufNewFile *.spice setfiletype spice

I thought maybe I could add a BufNewFile autocommand in the ftplugin file for this filetype, like this:

echo "Spice file."
au BufNewFile <buffer> echo "New spice file!"

But when I create a new file, e.g., "test.cir", it doesn't run the auto-command. It runs other commands in the ftplugin file (for instance, I get the "Spice file." echo) but not the autocommand.

Alternatively, if there's some way in vimscript that I can tell whether or not a file is new, then I could run the commands directly in the ftplugin, conditioned on whether or not it is new.

Answer

Ingo Karkat picture Ingo Karkat · May 6, 2014

That BufNewFile autocommand in the ftplugin file doesn't work, because the event order is wrong. BufNewFile triggers FileType, not the other way around.

You could split the au BufRead,BufNewFile into two separate commands, and set a buffer-local variable b:isNew in the first.

But I think it's indeed easiest to check in your ftplugin whether the file is new or not. As this depends on whether the edited file already exists on disk, a simple conditional like this should do:

if filereadable(expand('%'))
    " BufRead
else
    " BufNewFile
endif