-1

From https://vi.stackexchange.com/a/28026/47188 I know that by defining in vimrc:

" Insert text at the current cursor position.
function! InsertText(text)
    let cur_line_num = line('.')
    let cur_col_num = col('.')
    let orig_line = getline('.')
    let modified_line =
        \ strpart(orig_line, 0, cur_col_num - 1)
        \ . a:text
        \ . strpart(orig_line, cur_col_num - 1)
    " Replace the current line with the modified line.
    call setline(cur_line_num, modified_line)
    " Place cursor on the last character of the inserted text.
    call cursor(cur_line_num, cur_col_num + strlen(a:text))
endfunction

Then call it as:

let text = "Lorem ipsum sit dolor amet ..."
call InsertText(text)

The text would be inserted.

However, is it possible to insert multiple lines, for example, insert "hello", then the context in text, then "world" in the current line below?

1
  • 1
    What did you try? Commented Jul 16, 2024 at 18:01

2 Answers 2

1

The setline function accepts a list as documented in :help setline():

        {lnum} is used like with |getline()|.
        When {lnum} is just below the last line the {text} will be
        added below the last line.
        {text} can be any type or a List of any type, each item is
        converted to a String.  When {text} is an empty List then
        nothing is changed and FALSE is returned.

So you can do something like

call setline(cur_line_num, ['hello', modified_line, 'world'])

Note that append(orig_line, 'world') doesn't work because orig_line is the text, not the line number. You could do call append(line('.'), 'world') and call append(line('.')-1, 'hello'). The append() function also takes a list for multiple lines.

1

To add a line below with world I would add to your code:

call append(orig_line, "world")

If you want to modify the line I believe you have to repeat the action you did for the previous line with the world content.

More information with :help append()

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.