home ~ projects ~ socials

Append Lines To The End Of A Neovim Buffer/File With Lua

Head's Up

I can execute Rust and JavaScript code directly in my notes to verify I copied everything in properly. I can't yet do that with Lua. I think I pasted everything correctly. If something doesn't work, please let me know.

Adding Text

This is what I'm using to append lines to a Neovim file buffer:

local append_to_buffer = function(buffer_number, new_lines) 
    if type(new_lines) == "string" then
        new_lines = { new_lines }
    end
    local source_lines = vim.api.nvim_buf_get_lines(buffer_number, 0, -1, true)
    local count = 0
    for _ in pairs(source_lines) do 
        count = count + 1 
    end
    if count == 1 and source_lines[count] == "" then
        vim.api.nvim_buf_set_lines(
            buffer_number, 0, -1, true, new_lines 
        )
    else 
        vim.api.nvim_buf_set_lines(
            buffer_number, count, count, true, new_lines 
        )
    end
end

Usage

local buffer_number = 0
append_to_buffer(
  buffer_number, 
  "single line from string"
)
local buffer_number = 0
append_to_buffer(
  buffer_number,
  { 
    "single line from table" 
  }
)
local buffer_number = 0
append_to_buffer(
  buffer_number, 
  { 
    "multiple lines",
    "from table"
  }
)

Details

The append_to_buffer function takes two arguments:

  1. The id number of the buffer to append to
  2. The lines to append

The lines can be a string or a table. (TODO: test if \n works in strings)

If a table is used, it can contain more than one line.

The function checks to to see if the file is empty in which case the count of lines would be 1 but it would be an empty string. If that's the case, the lines start there. Otherwise, they are append one line after the end of the content.

(Without this check using the function on an empty file would results in an empty first line with the append lines starting on the second line)

-- end of line --