Question

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.

Was it helpful?

Solution

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

OTHER TIPS

The following autocommand should be enough to set the filetype based on those three extensions:

autocmd BufRead,BufNewFile *.{cir,sp,spice} setlocal filetype=spice

Once that autocommand is executed, the FileType event is triggered and Vim knows you are editing a file of filetype spice: you are free to put whatever fancy options/mappings you want in ~/.vim/ftplugin/spice.vim:

setlocal tabstop=23
nnoremap <buffer> <F7> :echo "Woot!"<CR>

Something is not clear, though: do you want to perform a specific action when you create a "spice" buffer or are you unclear about how to define your filetype?

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top