VIM:BufNewfile AutoCMD在Filetype插件中不起作用
背景故事:我希望VIM在编辑新的Java文件时生成公共类声明,因此我写了以下AUGROUP:
augroup generate_public_class_declaration_upon_creation
au!
autocmd BufNewFile *.java execute "normal! ipublic class " . expand('%:t:r') . "\<CR>{}\<Left>\<CR>\<CR>\<Up>\<Tab>" | startinsert
augroup END
放入.vimrc时的工作正常,但是在转移到ftplugin/java.vim后不再起作用。我尝试了其他一些事件,例如bufwritepre,java.vim内的bufwienter,没有什么问题。发生了什么事?
Background story: I want vim to generate a public class declaration when editing new java files, so I wrote the following augroup:
augroup generate_public_class_declaration_upon_creation
au!
autocmd BufNewFile *.java execute "normal! ipublic class " . expand('%:t:r') . "\<CR>{}\<Left>\<CR>\<CR>\<Up>\<Tab>" | startinsert
augroup END
Which works fine when put in .vimrc, but no longer functions after being transferred to ftplugin/java.vim. I tried some other events e.g. BufWritePre, BufWinEnter inside java.vim and nothing goes wrong. What's happening?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
到摘要从您的ftplugin执行时,捕获
bufnewfile
事件已经为时已晚。您可以将其留在已知可以正常工作的
vimrc
中,也可以修改它,以便可以从ftplugin中执行它。这是一个快速而肮脏的解决方案:
在插入骨架之前,我们在其中检查当前缓冲区是否有文件。
基本上,当您进行
:e foo.java
或$ vim foo.java
时,使用名称foo.java
创建一个缓冲区,哪个应该是关联文件的名称,可以用:help bufname()
检索。如果不存在该名称的文件,我们会使用检查:help fileReadable()
,我们可以插入骨架。请注意
!
startinsert
:如果没有它,插入将在&lt; tab; tab&gt;
之前发生。请参阅:帮助:StartInsert
。By the time that snippet is executed from your ftplugin it is already too late for catching the
BufNewFile
event.You can either leave it in your
vimrc
, where it is known to work, or modify it so that it can be executed from your ftplugin.Here is a quick and dirty solution:
where we check if there is a file for the current buffer before inserting our skeleton.
Basically, when you do
:e foo.java
or$ vim foo.java
, a buffer is created with the namefoo.java
, which is supposed to be the name of the associated file and can be retrieved with:help bufname()
. If a file with that name doesn't exist, we check with:help filereadable()
, we can insert the skeleton.Note the
!
afterstartinsert
: without it the insertion would happen before the<Tab>
. See:help :startinsert
.