问题
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