From f81bd133b8a6cd11e20f9c247f1a6ce9333052d3 Mon Sep 17 00:00:00 2001 From: Guldoman Date: Tue, 22 Oct 2024 18:59:55 +0200 Subject: [PATCH] Add `inclusive` parameter to `Doc:get_text` (#1586) This is needed to get the last character of the "selection". For example: ```lua doc:get_text(1, 1, #doc.lines, math.huge) ``` will return everything but the last newline, while ```lua doc:get_text(1, 1, #doc.lines, math.huge, true) ``` will return the last newline too. --- data/core/doc/init.lua | 17 ++++++++++++++--- 1 file changed, 14 insertions(+), 3 deletions(-) diff --git a/data/core/doc/init.lua b/data/core/doc/init.lua index 3999937f..502da779 100644 --- a/data/core/doc/init.lua +++ b/data/core/doc/init.lua @@ -340,18 +340,29 @@ function Doc:position_offset(line, col, ...) end end -function Doc:get_text(line1, col1, line2, col2) +---Returns the content of the doc between two positions.
+---The positions will be sanitized and sorted.
+---The character at the "end" position is not included by default. +---@see core.doc.sanitize_position +---@param line1 integer +---@param col1 integer +---@param line2 integer +---@param col2 integer +---@param inclusive boolean? Whether or not to return the character at the last position +---@return string +function Doc:get_text(line1, col1, line2, col2, inclusive) line1, col1 = self:sanitize_position(line1, col1) line2, col2 = self:sanitize_position(line2, col2) line1, col1, line2, col2 = sort_positions(line1, col1, line2, col2) + local col2_offset = inclusive and 0 or 1 if line1 == line2 then - return self.lines[line1]:sub(col1, col2 - 1) + return self.lines[line1]:sub(col1, col2 - col2_offset) end local lines = { self.lines[line1]:sub(col1) } for i = line1 + 1, line2 - 1 do table.insert(lines, self.lines[i]) end - table.insert(lines, self.lines[line2]:sub(1, col2 - 1)) + table.insert(lines, self.lines[line2]:sub(1, col2 - col2_offset)) return table.concat(lines) end