2

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.

Alex Harvey
  • 14,494
  • 5
  • 61
  • 97

2 Answers2

4

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.

muru
  • 4,723
  • 1
  • 34
  • 78
  • While it's hard to explain, that's not going to work in my actual use-case. Are you saying it's simply not possible to do what I am trying to do? – Alex Harvey Apr 01 '19 at 03:20
  • Oh it's possible alright, you would need a combination of `exec` and `norm` to get keypresses like `Enter`, and generally messier quoting as a result. Try explaining anyway. – muru Apr 01 '19 at 03:22
  • Generally, the advice is that you shouldn't edit a question if it invalidates existing answers, but I don't mind. Go ahead and edit as you see fit. I'll try to fix accordingly, or delete if I can't. – muru Apr 01 '19 at 03:24
  • It's actually impossible without asking a completely new question. Give me a bit. – Alex Harvey Apr 01 '19 at 03:26
  • https://stackoverflow.com/questions/55447788/how-to-insert-text-in-a-vimscript-without-using-the-builtin-functions – Alex Harvey Apr 01 '19 at 03:33
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  
gregory
  • 10,969
  • 2
  • 30
  • 42