How to insert text in vimscript

爱⌒轻易说出口 提交于 2019-12-24 07:27:27

问题


I have the simplest requirement in a vimscript. I've been searching on Google for quite some time e.g. 1 2 3. I just want to insert a line of text!

Suppose I have a file with lines:

aaa
bbb
ddd
eee

And I just want to add the missing line ccc after the line bbb.

I have the beginnings of a vimscript function:

function! addLine()
  normal /bbb
  " MISSING LINE
  wq!
endfunction

What should the missing line be?

Note that I want to then call this script on a bunch of files using using vim -c 'call addLine()' FILE.


回答1:


When using Vimscript, I'd avoid :normal-mode operations in favour of builtin functions that do the same things:

function! AddLine()
    let l:foundline = search("bbb") " Can return 0 on no match
    call append(l:foundline, "ccc")
    wq!
endfunction

search() and append() should be more convenient to work with in a function than norm / and norm o.




回答2:


While it isn't vimscript, your search and replace task across a bunch of files sounds like a job for argdo:

:argdo %s/bbb/&\rccc/ge | update  


来源:https://stackoverflow.com/questions/55447394/how-to-insert-text-in-vimscript

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