Insert text into current buffer from function

≡放荡痞女 提交于 2021-01-03 16:08:32

问题


I'm having a hard time finding the documentation for this. How do I read/write text from the current buffer in my vim functions?

More concretely, if my buffer contains the words foo bar how would write a function to overwrite the word bar with cat so that in the end my buffer contains foo cat?


回答1:


You can use the substitute ex command inside a function. For example

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

This defines a function. The % character means operate on the entire buffer. This searches for bar, replaces it with cat, and the g flag replaces every instance on a line, not just the first.

You can run this function by typing :call ReplaceBar() and hitting enter. Often it's convenient to define a function that does this kind of work, then define a command that calls it:

command! -nargs=0 Bar call ReplaceBar()

That command can be run by typing :Bar.




回答2:


To access line(s), you can use the getline() function. setline() updates those lines in the buffer. Likewise, new lines are inserted via append().

The latter can also be done with :put ={variable or expression}, and replacements with :substitute. What is better depends on the particular use case. The benefit of the former, lower-level functions is that they don't clobber stuff like the expression register, last used search pattern, search history, etc.




回答3:


In neovim, they have nvim_put. A few examples:

: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

Others have covered the use of :put pretty well, so I won't cover it myself.



来源:https://stackoverflow.com/questions/24168253/insert-text-into-current-buffer-from-function

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!