2

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.

4

2 回答 2

4

BufNewFileftplugin 文件中的自动命令不起作用,因为事件顺序错误。BufNewFile触发器FileType,而不是相反。

您可以将其拆分au BufRead,BufNewFile为两个单独的命令,并在第一个中设置一个缓冲区局部变量b:isNew

但我认为检查您的 ftplugin 文件是否是新文件确实是最简单的。因为这取决于编辑的文件是否已经存在于磁盘上,所以像这样的简单条件应该可以:

if filereadable(expand('%'))
    " BufRead
else
    " BufNewFile
endif
于 2014-05-06T13:46:05.063 回答
3

以下自动命令应该足以根据这三个扩展名设置文件类型:

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

一旦该自动命令被执行,FileType事件就会被触发并且 Vim 知道你正在编辑一个 filetype 的文件spice:你可以自由地把你想要的任何花哨的选项/映射放入~/.vim/ftplugin/spice.vim

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

不过,有些事情还不清楚:您想在创建“香料”缓冲区时执行特定操作,还是不清楚如何定义文件类型?

于 2014-05-06T13:57:02.417 回答