feat(treesitter): add @injection.filename

Problem: Injecting languages for file redirects (e.g., in bash) is not
possible.

Solution: Add `@injection.filename` capture that is piped through
`vim.filetype.match({ filename = node_text })`; the resulting filetype
(if not `nil`) is then resolved as a language (either directly or
through the list maintained via `vim.treesitter.language.register()`).

Note: `@injection.filename` is a non-standard capture introduced by
Helix; having two editors implement it makes it likely to be upstreamed.
This commit is contained in:
Christian Clason 2024-04-02 10:54:40 +02:00
parent b3f9da9524
commit 6cfca21bac
3 changed files with 11 additions and 0 deletions

View File

@ -240,6 +240,9 @@ The following new APIs and features were added.
language aliases (e.g., filetype or custom shorthands) registered via
|vim.treesitter.language.register()| and/or attempt lower case variants of
the text.
• `@injection.filename` will try to match the node text via
|vim.filetype.match()| and treat the result as a language name in the same
way as `@injection.language`.
• The `#set!` directive now supports `injection.self` and `injection.parent`
for injecting either the current node's language or the parent
|LanguageTree|'s language, respectively.

View File

@ -654,6 +654,10 @@ parent tree. The language injection query allows you to specify these
• `@injection.language` - indicates that the captured nodes text may
contain the name of a language that should be used to re-parse the
`@injection.content`.
• `@injection.filename` - indicates that the captured nodes text may
contain a filename; the corresponding filetype is then looked-up up via
|vim.filetype.match()| and treated as the name of a language that should
be used to re-parse the `@injection.content`.
The language injection behavior can also be configured by some properties
associated with patterns:

View File

@ -809,6 +809,10 @@ function LanguageTree:_get_injection(match, metadata)
if name == 'injection.language' then
local text = vim.treesitter.get_node_text(node, self._source, { metadata = metadata[id] })
lang = resolve_lang(text)
elseif name == 'injection.filename' then
local text = vim.treesitter.get_node_text(node, self._source, { metadata = metadata[id] })
local ft = vim.filetype.match({ filename = text })
lang = ft and resolve_lang(ft)
elseif name == 'injection.content' then
ranges = get_node_ranges(node, self._source, metadata[id], include_children)
end