refact: grep_escape

This commit is contained in:
Thomas Lambert
2023-04-29 00:44:52 +02:00
parent 9c95eb0e52
commit a518036fbf
2 changed files with 22 additions and 22 deletions

View File

@@ -238,25 +238,6 @@ local function make_config_path_absolute(path)
return ret return ret
end end
-- sanitize strings
local escape_chars = function(string)
return string.gsub(string, "[%(|%)|\\|%[|%]|%-|%{%}|%?|%+|%*|%^|%$|%/]", {
["\\"] = "\\\\",
["-"] = "\\-",
["("] = "\\(",
[")"] = "\\)",
["["] = "\\[",
["]"] = "\\]",
["{"] = "\\{",
["}"] = "\\}",
["?"] = "\\?",
["+"] = "\\+",
["*"] = "\\*",
["^"] = "\\^",
["$"] = "\\$",
})
end
local function recursive_substitution(dir, old, new) local function recursive_substitution(dir, old, new)
if not global_dir_check() then if not global_dir_check() then
return return
@@ -267,8 +248,8 @@ local function recursive_substitution(dir, old, new)
return return
end end
old = escape_chars(old) old = tkutils.grep_escape(old)
new = escape_chars(new) new = tkutils.grep_escape(new)
local sedcommand = "sed -i" local sedcommand = "sed -i"
if vim.fn.has("mac") == 1 then if vim.fn.has("mac") == 1 then

View File

@@ -1,7 +1,7 @@
local M = {} local M = {}
-- Prints a basic error message -- Prints a basic error message
local function print_error(s) function M.print_error(s)
vim.cmd("echohl ErrorMsg") vim.cmd("echohl ErrorMsg")
vim.cmd("echomsg " .. '"' .. s .. '"') vim.cmd("echomsg " .. '"' .. s .. '"')
vim.cmd("echohl None") vim.cmd("echohl None")
@@ -18,4 +18,23 @@ function M.strip(s, chars_to_remove)
return s:gsub("[" .. M.escape(chars_to_remove) .. "]", "") return s:gsub("[" .. M.escape(chars_to_remove) .. "]", "")
end end
-- Escapes for regex functions like grep or rg
function M.grep_escape(s)
return s:gsub("[%(|%)|\\|%[|%]|%-|%{%}|%?|%+|%*|%^|%$|%/]", {
["\\"] = "\\\\",
["-"] = "\\-",
["("] = "\\(",
[")"] = "\\)",
["["] = "\\[",
["]"] = "\\]",
["{"] = "\\{",
["}"] = "\\}",
["?"] = "\\?",
["+"] = "\\+",
["*"] = "\\*",
["^"] = "\\^",
["$"] = "\\$",
})
end
return M return M