Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(filetype.lua): escape expansion of ~ when used as a pattern #18353

Merged
merged 1 commit into from
May 2, 2022
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
16 changes: 13 additions & 3 deletions runtime/lua/vim/filetype.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1480,8 +1480,18 @@ end
local pattern_sorted = sort_by_priority(pattern)

---@private
local function normalize_path(path)
return (path:gsub("\\", "/"):gsub("^~", vim.env.HOME))
local function normalize_path(path, as_pattern)
local normal = path:gsub("\\", '/')
if normal:find('^~') then
if as_pattern then
-- Escape Lua's metacharacters when $HOME is used in a pattern.
-- The rest of path should already be properly escaped.
normal = vim.env.HOME:gsub('[-^$()%%.%[%]+?]', '%%%0') .. normal:sub(2)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

is vim.pesc useful here?

function vim.pesc(s)

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Yeah, that would have been useful to notice. :)

Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

There will be more than one opportunity to refactor filetype.lua (e.g., as part of #18241) ;)

else
normal = vim.env.HOME .. normal:sub(2)
end
end
return normal
end

--- Add new filetype mappings.
Expand Down Expand Up @@ -1550,7 +1560,7 @@ function M.add(filetypes)
end

for k, v in pairs(filetypes.pattern or {}) do
pattern[normalize_path(k)] = v
pattern[normalize_path(k, true)] = v
end

if filetypes.pattern then
Expand Down
1 change: 1 addition & 0 deletions test/functional/lua/filetype_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -70,6 +70,7 @@ describe('vim.filetype', function()
it('works with patterns', function()
eq('markdown', exec_lua([[
local root = ...
vim.env.HOME = '/a-funky+home%dir'
zeertzjq marked this conversation as resolved.
Show resolved Hide resolved
vim.filetype.add({
pattern = {
['~/blog/.*%.txt'] = 'markdown',
Expand Down