【问题标题】:Insert text into current buffer from function从函数将文本插入当前缓冲区
【发布时间】:2014-08-01 19:48:18
【问题描述】:

我很难找到这方面的文档。如何在我的 vim 函数中从当前缓冲区读取/写入文本?

更具体地说,如果我的缓冲区包含单词foo bar,如何编写一个函数用cat 覆盖单词bar,以便最终我的缓冲区包含foo cat

【问题讨论】:

  • :help eval:help functions

标签: buffer vim


【解决方案1】:

您可以在函数内使用substitute ex 命令。例如

function! ReplaceBar() 
  :%s/bar/cat/g
endfunction

这定义了一个函数。 % 字符表示对整个缓冲区进行操作。这会搜索bar,将其替换为catg 标志会替换一行中的每个实例,而不仅仅是第一个。

您可以通过输入:call ReplaceBar() 并按回车键来运行此功能。通常定义一个执行此类工作的函数很方便,然后定义一个调用它的命令:

command! -nargs=0 Bar call ReplaceBar()

该命令可以通过输入:Bar来运行。

【讨论】:

    【解决方案2】:

    要访问线路,您可以使用getline() 函数。 setline() 更新缓冲区中的这些行。同样,通过append() 插入新行。

    后者也可以用:put ={variable or expression} 完成,替换为:substitute。什么更好取决于特定的用例。前者的低级函数的好处是它们不会破坏表达式寄存器、上次使用的搜索模式、搜索历史等内容。

    【讨论】:

      【解决方案3】:

      在 neovim 中,他们有 nvim_put。几个例子:

      :call nvim_put(['cat'], 'c', v:false, v:true) ; insert 'cat' right where the cursor is, as if you typed `:normal! icat`
      :call nvim_put(['cat'], 'l', v:true, v:true) ; insert 'cat' on the next line
      

      :put的用法别人已经讲的很好了,我自己就不讲了。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-07-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-07-29
        相关资源
        最近更新 更多