Note: This site is currently "Under construction". I'm migrating to a new version of my site building software. Lots of things are in a state of disrepair as a result (for example, footnote links aren't working). It's all part of the process of building in public. Most things should still be readable though.

Append Text To The End Of A Neovim File Buffer With Lua

The neovim lua function `nvim_buf_set_lines()`lua` can be used to append lines to the end of a file buffer like this:

Code

local bufnr = 25
local start_line = -1
local end_line = -1
local strict_bounds = false
local lines = { "alfa bravo", "charlie delta" }

vim.api.nvim_buf_set_lines(
  bufnr, start_line, end_line, strict_bounds, lines
)

That will append one line with "alfa bravo" and another with "charlie delta" to the end of the buffer with id number of 25.

Details

  • `bufnr`` - the buffer number of the buffer to append the text to. (You can get the buffer number of the current buffer with `nvim_get_current_buf()`lua` or for a specific window by the window number with `nvim_win_get_buf(WINDOW_NUMBER)`lua`

  • `start_line`` - the line on which to start inserting the text. Negative numbers start from the end of the file. So, `-1`` starts at the last line

  • `end_line`` - the line to finish writing the text on. The start line is already at the end of the file, this also gets set to `-1`` since there's nothing after that point

  • `strict_bounds`` - determines if out-of-bounds attempts to write throw an error. This is generally set to false unless you have a specific use case that needs it

  • `lines`` - the array of lines to output. Each line is its own element in the array