home ~ projects ~ socials

Replace A Line In A Neovim Buffer/File

This is the function I'm using to replace lines in Neovim buffers.

local replace_line = function(buffer_number, line_number, content)
    if type(content) == "string" then
        content = { content }
    end
    vim.api.nvim_buf_set_lines(
        buffer_number, 
        line_number - 1, 
        line_number, 
        false, 
        content
    )
end

replace_line(0, 7, "-- line from string")
replace_line(0, 8, { "-- line from table" })

Basic Usage

The function can be used with strings:

replace_line(0, 7, "-- line from string")

Or tables:

replace_line(0, 8, { "-- line from table" })

Sending Multiple Lines

The function accepts tables with multiple lines as well. The first line does a replacement. The rest of the lines are inserted after it without replacing anything else.

For example, given this starting text:

Original Line Alfa
Original Line Bravo 
Original Line Charlie 
Original Line Delta 
Original Line Echo

Doing this:

replace_line(0, 3, {
  "Replacement Line Alfa",
  "Replacement Line Bravo",
  "Replacement Line Charlie",
  "Replacement Line Delta",
  "Replacement Line Echo",
}

Produces this:

Original Line Alfa
Original Line Bravo 
Replacement Line Alfa
Replacement Line Bravo
Replacement Line Charlie
Replacement Line Delta 
Replacement Line Echo 
Original Line Delta 
Original Line Echo

Original Line Charlie has been replaced with the five replacment lines. Even though five lines were output, only one was replaced. Original Line Detlta and Original Line Echo just got pushed down.

-- end of line --