VIM:BufNewfile AutoCMD在Filetype插件中不起作用

发布于 2025-01-27 08:25:42 字数 438 浏览 2 评论 0原文

背景故事:我希望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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

烂人 2025-02-03 08:25:42

到摘要从您的ftplugin执行时,捕获bufnewfile事件已经为时已晚。

您可以将其留在已知可以正常工作的vimrc中,也可以修改它,以便可以从ftplugin中执行它。

这是一个快速而肮脏的解决方案:

" in after/ftplugin/java.vim
if !(bufname()->filereadable())
    execute "normal! ipublic class " . expand('%:t:r') . "\<CR>{}\<Left>\<CR>\<CR>\<Up>\<Tab>" | startinsert!
endif

在插入骨架之前,我们在其中检查当前缓冲区是否有文件。

基本上,当您进行: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:

" in after/ftplugin/java.vim
if !(bufname()->filereadable())
    execute "normal! ipublic class " . expand('%:t:r') . "\<CR>{}\<Left>\<CR>\<CR>\<Up>\<Tab>" | startinsert!
endif

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 name foo.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 ! after startinsert: without it the insertion would happen before the <Tab>. See :help :startinsert.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文