Vim / Neovim 当你有 lua 函数时为什么要使用自动命令?

发布于 2025-01-09 13:15:48 字数 327 浏览 0 评论 0原文

我对 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 技术交流群。

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

发布评论

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

评论(1

初心 2025-01-16 13:15:48

您正在将两个完全不相关的事物混为一谈。

您的代码片段(假设它有效,我不使用 Neovim,所以我不会测试它):

function OpenTerm()
  vim.cmd("bel split")
  vim.cmd("terminal")
  vim.cmd("setlocal nonumber norelativenumber")
end

是一个 Lua 函数,与此 Vimscript 函数完全相同:

function! OpenTerm()
  bel split
  terminal
  setlocal nonumber norelativenumber
endfunction

并且这两个函数实际上与自动命令无关。它们是完全被动的,定义它们只做了一些低级的与内存相关的事情。为了让他们做任何事情,你必须给他们打电话

自动命令是一种非常不同的东西,它允许你告诉 Vim 在事件发生时执行某些操作,就像这样:

autocmd VimEnter * call OpenTerm()

它本质上告诉 Vim:

启动完成后,调用OpenTerm()函数。

与在调用之前不执行任何操作的函数不同,自动命令一旦定义就会对编辑器的状态产生真正的影响。

您可以从函数添加自动命令,可以从自动命令调用函数,但不能指望一个函数充当另一个函数。

基本上,问题是“我使用自动命令还是函数?”完全没有意义。

You are conflating two totally unrelated things.

Your snippet (assuming it works, I don't use Neovim so I won't test it):

function OpenTerm()
  vim.cmd("bel split")
  vim.cmd("terminal")
  vim.cmd("setlocal nonumber norelativenumber")
end

is a Lua function that is exactly equivalent to this Vimscript function:

function! OpenTerm()
  bel split
  terminal
  setlocal nonumber norelativenumber
endfunction

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:

autocmd VimEnter * call OpenTerm()

which, essentially, tells Vim this:

When you are done starting up, call the OpenTerm() function.

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.

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