diff --git a/lua/avante/llm_tools/replace_in_file.lua b/lua/avante/llm_tools/replace_in_file.lua index 65f2332..af1d336 100644 --- a/lua/avante/llm_tools/replace_in_file.lua +++ b/lua/avante/llm_tools/replace_in_file.lua @@ -163,7 +163,8 @@ function M.func(input, opts) elseif is_searching then table.insert(current_old_lines, line) elseif is_replacing then - table.insert(current_new_lines, line) + -- Remove trailing spaces from each line before adding to new_lines + table.insert(current_new_lines, (line:gsub("%s+$", ""))) end end diff --git a/lua/avante/llm_tools/str_replace.lua b/lua/avante/llm_tools/str_replace.lua index 32a32ec..f3a8080 100644 --- a/lua/avante/llm_tools/str_replace.lua +++ b/lua/avante/llm_tools/str_replace.lua @@ -56,6 +56,11 @@ M.returns = { ---@type AvanteLLMToolFunc<{ path: string, old_str: string, new_str: string }> function M.func(input, opts) local replace_in_file = require("avante.llm_tools.replace_in_file") + local Utils = require("avante.utils") + + -- Remove trailing spaces from the new string + input.new_str = Utils.remove_trailing_spaces(input.new_str) + local diff = "------- SEARCH\n" .. input.old_str .. "\n=======\n" .. input.new_str if not opts.streaming then diff = diff .. "\n+++++++ REPLACE" end local new_input = { diff --git a/lua/avante/llm_tools/write_to_file.lua b/lua/avante/llm_tools/write_to_file.lua index 09d59cd..4bf278a 100644 --- a/lua/avante/llm_tools/write_to_file.lua +++ b/lua/avante/llm_tools/write_to_file.lua @@ -70,6 +70,8 @@ function M.func(input, opts) Utils.debug("Trimming escapes from content") input.the_content = Utils.trim_escapes(input.the_content) end + -- Remove trailing spaces from each line + input.the_content = Utils.remove_trailing_spaces(input.the_content) local old_lines = Utils.read_file_from_buf_or_disk(abs_path) local old_content = table.concat(old_lines or {}, "\n") local str_replace = require("avante.llm_tools.str_replace") diff --git a/lua/avante/utils/init.lua b/lua/avante/utils/init.lua index 8752ac4..810f1aa 100644 --- a/lua/avante/utils/init.lua +++ b/lua/avante/utils/init.lua @@ -554,6 +554,18 @@ end function M.trim_spaces(s) return s:match("^%s*(.-)%s*$") end +---Remove trailing spaces from each line in a string +---@param content string The content to process +---@return string The content with trailing spaces removed from each line +function M.remove_trailing_spaces(content) + if not content then return content end + local lines = vim.split(content, "\n") + for i, line in ipairs(lines) do + lines[i] = line:gsub("%s+$", "") + end + return table.concat(lines, "\n") +end + function M.fallback(v, default_value) return type(v) == "nil" and default_value or v end ---Join URL parts together, handling slashes correctly