From dc6fc321a5ba076697cca89c9d7ea43153276d81 Mon Sep 17 00:00:00 2001 From: James Trew <66286082+jamestrew@users.noreply.github.com> Date: Sun, 6 Oct 2024 02:11:05 +0000 Subject: [PATCH] fix(grep_string): cast `search` value to string (#3319) When using the vim command API and passing a number to the `search` option of `grep_string` (eg. `:Telescope grep_string search=3`), the number is passed as a number. This eventually causes a type error at `string.gsub` as the `search` value is expected to be a string. We'll just cast `search` value to a string. --- lua/telescope/builtin/__files.lua | 53 ++++++++++++++++--------------- 1 file changed, 27 insertions(+), 26 deletions(-) diff --git a/lua/telescope/builtin/__files.lua b/lua/telescope/builtin/__files.lua index cc5f905c0f..97ee6a3def 100644 --- a/lua/telescope/builtin/__files.lua +++ b/lua/telescope/builtin/__files.lua @@ -17,23 +17,27 @@ local filter = vim.tbl_filter local files = {} -local escape_chars = function(string) - return string.gsub(string, "[%(|%)|\\|%[|%]|%-|%{%}|%?|%+|%*|%^|%$|%.]", { - ["\\"] = "\\\\", - ["-"] = "\\-", - ["("] = "\\(", - [")"] = "\\)", - ["["] = "\\[", - ["]"] = "\\]", - ["{"] = "\\{", - ["}"] = "\\}", - ["?"] = "\\?", - ["+"] = "\\+", - ["*"] = "\\*", - ["^"] = "\\^", - ["$"] = "\\$", - ["."] = "\\.", - }) +---@param s string +---@return string +local escape_chars = function(s) + return ( + s:gsub("[%(|%)|\\|%[|%]|%-|%{%}|%?|%+|%*|%^|%$|%.]", { + ["\\"] = "\\\\", + ["-"] = "\\-", + ["("] = "\\(", + [")"] = "\\)", + ["["] = "\\[", + ["]"] = "\\]", + ["{"] = "\\{", + ["}"] = "\\}", + ["?"] = "\\?", + ["+"] = "\\+", + ["*"] = "\\*", + ["^"] = "\\^", + ["$"] = "\\$", + ["."] = "\\.", + }) + ) end local has_rg_program = function(picker_name, program) @@ -202,7 +206,10 @@ files.grep_string = function(opts) else word = vim.F.if_nil(opts.search, vim.fn.expand "") end + + word = tostring(word) local search = opts.use_regex and word or escape_chars(word) + local search_args = search == "" and { "-v", "--", "^[[:space:]]*$" } or { "--", search } local additional_args = {} if opts.additional_args ~= nil then @@ -217,32 +224,26 @@ files.grep_string = function(opts) additional_args[#additional_args + 1] = "--encoding=" .. opts.file_encoding end - if search == "" then - search = { "-v", "--", "^[[:space:]]*$" } - else - search = { "--", search } - end - local args if visual == true then args = flatten { vimgrep_arguments, additional_args, - search, + search_args, } else args = flatten { vimgrep_arguments, additional_args, opts.word_match, - search, + search_args, } end opts.__inverted, opts.__matches = opts_contain_invert(args) if opts.grep_open_files then - for _, file in ipairs(get_open_filelist(opts.grep_open_files, opts.cwd)) do + for _, file in ipairs(get_open_filelist(opts.grep_open_files, opts.cwd) or {}) do table.insert(args, file) end elseif opts.search_dirs then