home ~ projects ~ socials

Use Lua To Insert Text At The Current Cursor Position In Neovim

Output The Text

This is how I'm inserting text from Lua scripts into file buffers at the current cursor position:

function insert_text(text)
    local window_number = 0
    local buffer_number = vim.api.nvim_win_get_buf(
        window_number
    )
    local row, col = unpack(
        vim.api.nvim_win_get_cursor(
            window_number
        )
    )
    local output = {}
    if (type(text) == 'table') then
        output = text
    else
        table.insert(output, text)
    end
    vim.api.nvim_buf_set_text(
        buffer_number, 
        row - 1, 
        col + 1, 
        row - 1, 
        col + 1, 
        output
    )
    local line_count = 0
    for _ in pairs(output) do
        line_count = line_count + 1
    end
    if line_count == 1 then
        vim.api.nvim_win_set_cursor(
            window_number,
            {row, col + string.len(output[1])}
        )
    else
        vim.api.nvim_win_set_cursor(
            window_number,
            {
                row + line_count - 1, 
                string.len(output[line_count]) - 1
            }
        )
    end
    vim.api.nvim_feedkeys('a', 'n', true)
end

Usage Examples

The insert_text function can take a string or a table:

insert_text("example with string")

insert_text({
  'single line in table',
})

insert_text({
    'multiple lines',
    'in table',
})

Notes

  • The text is inserted after the current cursor position the same way it would be if you hit p to paste a string.
  • The function switches to "insert" mode with the cursor after the last inserted character.
-- end of line --

References