Skip to content

Commit

Permalink
fix(grep_string): cast search value to string (#3319)
Browse files Browse the repository at this point in the history
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.
  • Loading branch information
jamestrew authored Oct 6, 2024
1 parent eae0d8f commit dc6fc32
Showing 1 changed file with 27 additions and 26 deletions.
53 changes: 27 additions & 26 deletions lua/telescope/builtin/__files.lua
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down Expand Up @@ -202,7 +206,10 @@ files.grep_string = function(opts)
else
word = vim.F.if_nil(opts.search, vim.fn.expand "<cword>")
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
Expand All @@ -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
Expand Down

0 comments on commit dc6fc32

Please sign in to comment.