refactor(utils): simplify and annotate count_lines() (#2446)
This commit is contained in:
@@ -1774,20 +1774,15 @@ function M.message_to_text(message, messages)
|
|||||||
return ""
|
return ""
|
||||||
end
|
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)
|
function M.count_lines(str)
|
||||||
if not str or str == "" then return 0 end
|
if not str or str == "" then return 0 end
|
||||||
|
|
||||||
local count = 1
|
local _, count = str:gsub("\n", "\n")
|
||||||
local len = #str
|
-- Number of lines is one more than number of newlines unless we have a trailing newline
|
||||||
local newline_byte = string.byte("\n")
|
return str:sub(-1) ~= "\n" and count + 1 or count
|
||||||
|
|
||||||
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
|
|
||||||
end
|
end
|
||||||
|
|
||||||
function M.tbl_override(value, override)
|
function M.tbl_override(value, override)
|
||||||
|
|||||||
Reference in New Issue
Block a user