From d3dde0c5ffa645ba55a6f0789e0b77235c09a366 Mon Sep 17 00:00:00 2001 From: Dmitry Torokhov Date: Tue, 15 Jul 2025 01:42:30 -0700 Subject: [PATCH] refactor(utils): simplify and annotate count_lines() (#2446) --- lua/avante/utils/init.lua | 17 ++++++----------- 1 file changed, 6 insertions(+), 11 deletions(-) diff --git a/lua/avante/utils/init.lua b/lua/avante/utils/init.lua index 5a54ee6..919cd2c 100644 --- a/lua/avante/utils/init.lua +++ b/lua/avante/utils/init.lua @@ -1774,20 +1774,15 @@ function M.message_to_text(message, messages) return "" end +---Counts number of strings in text, accounting for possibility of a trailing newline +---@param str string | nil +---@return integer function M.count_lines(str) if not str or str == "" then return 0 end - local count = 1 - local len = #str - local newline_byte = string.byte("\n") - - for i = 1, len do - if str:byte(i) == newline_byte then count = count + 1 end - end - - if str:byte(len) == newline_byte then count = count - 1 end - - return count + local _, count = str:gsub("\n", "\n") + -- Number of lines is one more than number of newlines unless we have a trailing newline + return str:sub(-1) ~= "\n" and count + 1 or count end function M.tbl_override(value, override)