Use Lua To Insert Lines Into A Neovim Buffer/File
April 2025
Make Some Lines
This is the function I use to insert lines into a Neovim buffer:
Need to do a little more testing on this for when there is already content in the buffer
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 line_count = 0
vim.api.nvim_buf_set_lines(
buffer_number,
row,
row,
false,
lines
)
for _ in pairs(lines) do
line_count = line_count + 1
end
vim.api.nvim_win_set_cursor(
window_number,
{row + line_count, 0}
)
endI use it like:
insert_lines(
{
'example line alfa',
'example line bravo',
'example line charlie'
}
)Notes
-
The function works like hitting
pto paste when you're innormalmode (i.e. the lines are inserted below the current line and the cursor is moved to the first character of the last line that's output) - The function is set up to use the current buffer in the current window.
-
The argument passed to the
insert_lines()function is a table with the lines to output.
end of line
Endnotes
It took me a few hours to figure this out. I couldn't find a simple, clear example. Everything was complicated with all kinds of unrelated content. Hopefully, this will help other folks who want to play around with Neovim scripting and plugins.