Vim / Neovim 当你有 lua 函数时为什么要使用自动命令?
我对 vim 有一些经验,但我的大部分时间都花在 neovim 上玩 lua (尽管我仍然不是初学者)。我错过了 vimscript 自动命令的魔力,我看到很多人都在使用它,我想知道为什么不直接写一个 lua 函数,比如......
function OpenTerm()
vim.cmd("bel split")
vim.cmd("terminal")
vim.cmd("setlocal nonumber norelativenumber")
end
而不是写一个 autocmd ?
I have some experience with vim but most of my time has been spent in neovim playing around with lua (although I'm still barely not a beginner). I missed out on the vimscript autocommand magic that I see alot of people pulling off and I'm wondering why not just write a lua function like...
function OpenTerm()
vim.cmd("bel split")
vim.cmd("terminal")
vim.cmd("setlocal nonumber norelativenumber")
end
instead of writing a an autocmd ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您正在将两个完全不相关的事物混为一谈。
您的代码片段(假设它有效,我不使用 Neovim,所以我不会测试它):
是一个 Lua 函数,与此 Vimscript 函数完全相同:
并且这两个函数实际上与自动命令无关。它们是完全被动的,定义它们只做了一些低级的与内存相关的事情。为了让他们做任何事情,你必须给他们打电话。
自动命令是一种非常不同的东西,它允许你告诉 Vim 在事件发生时执行某些操作,就像这样:
它本质上告诉 Vim:
与在调用之前不执行任何操作的函数不同,自动命令一旦定义就会对编辑器的状态产生真正的影响。
您可以从函数添加自动命令,可以从自动命令调用函数,但不能指望一个函数充当另一个函数。
基本上,问题是“我使用自动命令还是函数?”完全没有意义。
You are conflating two totally unrelated things.
Your snippet (assuming it works, I don't use Neovim so I won't test it):
is a Lua function that is exactly equivalent to this Vimscript function:
and both functions have literally nothing to do with autocommands. They are completely passive and defining them only did some low-level memory-related things. For them to do anything, you have to call them.
Autocommands are a very different thing that allows you to tell Vim to perform some action when an event occurs, like this one:
which, essentially, tells Vim this:
Unlike functions, which do nothing until they are called, autocommands have a real effect on your editor's state as soon as they are defined.
You can add an autocommand from a function, you can call a function from an autocommand, but you can't expect one to act as the other.
Basically, the question "Do I use an autocommand or a function?" makes no sense at all.