From 1c052ace3043d1a0c30a390ef1574c6420a2673b Mon Sep 17 00:00:00 2001 From: L3MON4D3 Date: Sat, 2 Nov 2024 22:15:18 +0100 Subject: [PATCH] add :sub to snippetString. --- lua/luasnip/nodes/util/snippet_string.lua | 39 +++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/lua/luasnip/nodes/util/snippet_string.lua b/lua/luasnip/nodes/util/snippet_string.lua index 6949c1944..bba59c7cf 100644 --- a/lua/luasnip/nodes/util/snippet_string.lua +++ b/lua/luasnip/nodes/util/snippet_string.lua @@ -426,4 +426,43 @@ function SnippetString:gsub(pattern, repl) return self end +function SnippetString:sub(from, to) + self = self:copy() + + local snipstr_map = {} + local str = gen_snipstr_map(self, snipstr_map, 1) + + to = to or #str + + -- negative -> positive + if from < 0 then + from = #str + from + 1 + end + if to < 0 then + to = #str + to + 1 + end + + -- empty range => return empty snippetString. + if from > #str or to < from or to < 1 then + return M.new({""}) + end + + from = math.max(from, 1) + to = math.min(to, #str) + + local replacements = {} + -- from <= 1 => don't need to remove from beginning. + if from > 1 then + table.insert(replacements, { from=1, to=from-1, str = "" }) + end + -- to >= #str => don't need to remove from end. + if to < #str then + table.insert(replacements, { from=to+1, to=#str, str = "" }) + end + + _replace(self, replacements, snipstr_map) + return self +end + + return M