【问题标题】:How to call a lua function in neovim from autocommand or user_command如何从 autocommand 或 user_command 在 neovim 中调用 lua 函数
【发布时间】:2022-10-21 00:15:39
【问题描述】:

我正在尝试将一些旧的 vimscript 迁移到 lua。我有一堆“散文”设置,现在在 .config/nvim/plugin/functions.lua 中有这些设置:

function prose()
vim.o.fdo:append('search')
vim.bo.virtualedit = block
-- more commands
end

然后在 prose.lua 中:

local textedit = vim.api.nvim_create_augroup('textedit', {clear = true})
vim.api.nvim_create_autocmd({"BufEnter", "BufNew"}, {
  group = "textedit",
  pattern = {"*.adoc", "*.md", "*.tex"},
  callback = "prose",
})

vim.api.nvim_create_user_command(
  'Prose',
  "call prose()",
  {nargs = 0, desc = 'Apply prose settings'}
)````

But either the autocommand on opening an .adoc file or running :Prose on the command line will return:
 
````E117: Unknown function: prose````

How can I make my 'prose' function available?

【问题讨论】:

    标签: lua neovim


    【解决方案1】:

    首先,您的functions.lua 文件必须在.config/nvim/lua/ 目录中。

    对于您的自动命令,将回调修改为需要 functions.lua 和函数 prose

    callback = require('functions').prose()
    

    对于您的用户命令:

    vim.api.nvim_create_user_command('Prose', function()
        require('functions').prose()
      end,                                                                                                                                  
      {nargs = 0, desc = 'Apply prose settings'}                                                                                                       
    )      
    

    【讨论】:

    • 我将单个“函数散文()”移动到 lua/functions2.lua 并将回调更改为:callback = require('functions2').prose()。但后来我得到:lua/prose.lua:21: attempt to index a boolean value。其他一些函数设置 ```` M = {}``` 和 ```` 返回 M, but trying that produces lua/prose.lua:21: 尝试调用字段 'prose'(一个 nil 值)````
    • 如果您需要帮助,请编辑您的第一篇文章以添加 lua/prose.lua 的完整代码。我们需要查看第 21 行以了解您的错误。
    【解决方案2】:

    评论 Icheylus 的回复。

    通过像这样分配回调

    callback = require('functions').prose()
    

    您正在尝试将函数的输出分配给回调。如果您的函数返回一个函数,这将起作用,但您的函数不返回任何内容。

    因此,一个简单的调整就是删除()

    callback = require('functions').prose
    

    或者,如果它在自动命令的回调中非常简单,您甚至可以创建您的函数。

    local textedit = vim.api.nvim_create_augroup('textedit', {clear = true})
    vim.api.nvim_create_autocmd({"BufEnter", "BufNew"}, {
      group = "textedit",
      pattern = {"*.adoc", "*.md", "*.tex"},
      callback = function()
          vim.o.fdo:append('search')
          vim.bo.virtualedit = block
          -- more commands
      end,
    })
    

    【讨论】:

      猜你喜欢
      • 2021-10-06
      • 1970-01-01
      • 2013-12-22
      • 2011-02-01
      • 2015-07-14
      • 2015-04-03
      • 1970-01-01
      • 2019-06-08
      • 2011-02-19
      相关资源
      最近更新 更多