From 638d237b75b25ef855071c750590d5e23a9eaff9 Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Wed, 6 Aug 2025 15:31:26 -0700 Subject: [PATCH] refactor(utils): make prepend_line_numbers() more efficient and idiomatic Between Utils.prepend_line_number() and its only caller, there is a lot of conversions from list to string to list and back to string. Simplify all of this by making it accept and return a list of strings, which avoids unnecessary splitting and joining. The implementation was updated to use vim.iter():map() and string.format() for better performance and to align with the idiomatic functional style used elsewhere in the project. The name of the function has also been tweaked and is now "prepend_line_numbers()" to better reflect that it operates on a list of strings. The caller has been updated to match the new function signature. --- lua/avante/suggestion.lua | 6 ++++-- lua/avante/utils/init.lua | 14 ++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/lua/avante/suggestion.lua b/lua/avante/suggestion.lua index a136523..4a3834f 100644 --- a/lua/avante/suggestion.lua +++ b/lua/avante/suggestion.lua @@ -166,8 +166,10 @@ function Suggestion:suggest() local bufnr = api.nvim_get_current_buf() local filetype = api.nvim_get_option_value("filetype", { buf = bufnr }) - local code_content = - Utils.prepend_line_number(table.concat(api.nvim_buf_get_lines(bufnr, 0, -1, false), "\n") .. "\n\n") + local lines = api.nvim_buf_get_lines(bufnr, 0, -1, false) + table.insert(lines, "") + table.insert(lines, "") + local code_content = table.concat(Utils.prepend_line_numbers(lines), "\n") local full_response = "" diff --git a/lua/avante/utils/init.lua b/lua/avante/utils/init.lua index d85fa12..8752ac4 100644 --- a/lua/avante/utils/init.lua +++ b/lua/avante/utils/init.lua @@ -718,15 +718,13 @@ function M.get_doc() return doc end -function M.prepend_line_number(content, start_line) +---Prepends line numbers to each line in a list of strings. +---@param lines string[] The lines of content to prepend line numbers to. +---@param start_line? integer The starting line number. Defaults to 1. +---@return string[] A new list of strings with line numbers prepended. +function M.prepend_line_numbers(lines, start_line) start_line = start_line or 1 - local lines = vim.split(content, "\n") - local result = {} - for i, line in ipairs(lines) do - i = i + start_line - 1 - table.insert(result, "L" .. i .. ": " .. line) - end - return table.concat(result, "\n") + return vim.iter(lines):map(function(line, i) return string.format("L%d: %s", i + start_line, line) end):totable() end ---Iterates through a list of strings and removes prefixes in form of "L: " from them