【问题标题】:How to get the last inserted character using Lua in Neovim?如何在 Neovim 中使用 Lua 获取最后插入的字符?
【发布时间】:2023-01-30 02:19:37
【问题描述】:

使用 Lua 我想知道插入的字符(在插入模式下)是什么触发了 InsertCharPre/TextChangedI/... 事件。

我想编写一个简单的 Neovim 插件,如果我在这样的列表中按 enter 键,它会自动将新行添加到降价项目符号列表中。到目前为止,该插件能够检测给定行是否为项目符号列表行。现在,如果插入的字符是 <CR>,我想插入它,检查项目符号列表的当前缩进并在下一行的同一级别添加一个新元素。自动命令通过 InsertCharPre 事件触发,该事件是在按下某个键但在将其插入缓冲区之前创建的。

此代码正在为其创建自动命令:

api.nvim_create_autocmd("InsertCharPre", {
    pattern = { "*.md" },
    callback = create_new_bullet_list_entry,
    group = mdGroup
})

这是我想继续检查最后输入的字符是否为 <CR> 的地方:

local create_new_bullet_list_entry = function(table)
    local cur_line = api.nvim_get_current_line()
    local is_bullet_list = is_line_bullet_list(cur_line)
    if not is_bullet_list then
        return
    end
end

如何检查输入的字符触发了InsertCharPre 事件?

我检查了传递给回调函数的表,它不包含有关键入字符的任何信息:

{ ["id"] = 36,["file"] = /foo/bar,["match"] = /foo/bar,["group"] = 28,["buf"] = 1,["event"] = InsertCharPre,}

实现相同结果的其他方法也将非常有帮助!

【问题讨论】:

    标签: plugins lua neovim


    【解决方案1】:

    要检查输入的字符触发了InsertCharPre事件,您可以在事件回调中使用vim.v.char引用v:char变量。

    然而,这对您的用例不起作用,因为您的要求是检查插入的字符是否是不会触发 InsertCharPre 事件的回车符。正如 Bram 在 Github issue 中建议的那样,您可能想要改为使用表达式映射。我想是这样的:

    au FileType markdown inoremap <expr> <CR> CreateNewBulletListEntry()
    

    并使用您想要的功能定义该功能。

    【讨论】:

      猜你喜欢
      • 2019-04-21
      • 2017-02-06
      • 2011-08-16
      • 1970-01-01
      • 2021-11-02
      • 1970-01-01
      • 2016-10-24
      • 2016-05-28
      • 2016-09-09
      相关资源
      最近更新 更多