1

I am writing a vim script, and I need to insert the contents of a string variable at the current cursor position. What is an appropriate way to do this?

let text = "Lorem ipsum sit dolor amet ..."
" How to insert text at current cursor position?

I know that :read can do something like this, but it is only applicable for inserting text that come from files, not text stored in variables.

3

You can do a literal insert of register contents through :help i_CTRL-R_CTRL-R, combined with the expression register (:help quote=) to reference the variable:

execute "normal! i\<C-r>\<C-r>=text\<CR>\<Esc>"

If you know that the variable contents are just plain text (without any special control characters), you could also just append the variable contents as-is and conclude with <Esc>:

execute "normal! i" . text . "\<Esc>"

Or use the low-level setline(), splicing in the text at the cursor column via string manipulation:

let line = getline('.')
call setline('.', strpart(line, 0, col('.') - 1) . text . strpart(line, col('.') - 1))
  • I don't think you need Esc in execute "normal! i" . text . "\<Esc>" do you? At least if wrapped in a function. – Maxim Kim Nov 8 at 8:02
  • 1
    @MaximKim: You can get away without it, but I prefer to be fully correct. This matters if, for example, you add another :normal later in that function. – Ingo Karkat Nov 8 at 8:04
  • 1
    It still works without explicit Esc though. fun! Test() let text = "Lorem ipsum sit dolor amet ..." exe 'normal a' . text normal gg endfun – Maxim Kim Nov 8 at 8:11
  • 1
    @D.BenKnoble: For the double-quoting and special \<CR> notation. Yes, you could type \<C-r> as ^R instead, but the Enter would be difficult I think. – Ingo Karkat Nov 8 at 12:55
  • 1
    Ah, for some reason I was thinking normal would interpret <C-r> like a mapping. Ofc. The enter would be done the same way, no problem. But this is cleaner. – D. Ben Knoble Nov 8 at 13:03
1

You might go with setline function or simple:

let text = "Lorem ipsum sit dolor amet ..."
exe "normal! a" . text . "\<Esc>"
  • exe (:execute) is to execute vimscript
  • normal! a executes a command as you type in vim (append after cursor)
  • . text then you concatenate your text with normal a. As you would type this text in vim after a.
  • and '\<Esc> to exit insert mode.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.