Skip to content

Commit cb46f6e

Browse files
authored
feat(treesitter): support URLs (neovim#27132)
Tree-sitter queries can add URLs to a capture using the `#set!` directive, e.g. (inline_link (link_text) @text.reference (link_destination) @text.uri (#set! @text.reference "url" @text.uri)) The pattern above is included by default in the `markdown_inline` highlight query so that users with supporting terminals will see hyperlinks. For now, this creates a hyperlink for *all* Markdown URLs of the pattern [link text](link url), even if `link url` does not contain a valid protocol (e.g. if `link url` is a path to a file). We may wish to change this in the future to only linkify when the URL has a valid protocol scheme, but for now we delegate handling this to the terminal emulator. In order to support directives which reference other nodes, the highlighter must be updated to use `iter_matches` rather than `iter_captures`. The former provides the `match` table which maps capture IDs to nodes. However, this has its own challenges: - `iter_matches` does not guarantee the order in which patterns are iterated matches the order in the query file. So we must enforce ordering manually using "subpriorities" (neovim#27131). The pattern index of each match dictates the extmark's subpriority. - When injections are used, the highlighter contains multiple trees. The pattern indices of each tree must be offset relative to the maximum pattern index from all previous trees to ensure that extmarks appear in the correct order. - The `iter_captures` implementation currently has a bug where the "match" table is only returned for the first capture within a pattern (see neovim#27274). This bug means that `#set!` directives in a query apply only to the first capture within a pattern. Unfortunately, many queries in the wild have come to depend on this behavior. `iter_matches` does not share this flaw, so switching to `iter_matches` exposed bugs in existing highlight queries. These queries have been updated in this repo, but may still need to be updated by users. The `#set!` directive applies to the _entire_ query pattern when used without a capture argument. To make `#set!` apply only to a single capture, the capture must be given as an argument.
1 parent 41fb98d commit cb46f6e

File tree

5 files changed

+178
-33
lines changed

5 files changed

+178
-33
lines changed

Diff for: runtime/doc/news.txt

+3
Original file line numberDiff line numberDiff line change
@@ -254,6 +254,9 @@ The following new APIs and features were added.
254254
indexing.
255255
|:InspectTree| shows root nodes
256256
|:InspectTree| now supports |folding|
257+
• The `#set!` directive can set the "url" property of a node to have the
258+
node emit a hyperlink. Hyperlinks are UI specific: in the TUI, the OSC 8
259+
control sequence is used.
257260

258261
|vim.ui.open()| opens URIs using the system default handler (macOS `open`,
259262
Windows `explorer`, Linux `xdg-open`, etc.)

Diff for: runtime/lua/vim/treesitter/highlighter.lua

+66-25
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ local Range = require('vim.treesitter._range')
44

55
local ns = api.nvim_create_namespace('treesitter/highlighter')
66

7-
---@alias vim.treesitter.highlighter.Iter fun(end_line: integer|nil): integer, TSNode, vim.treesitter.query.TSMetadata
7+
---@alias vim.treesitter.highlighter.Iter fun(): integer, table<integer, TSNode[]>, vim.treesitter.query.TSMetadata
88

99
---@class (private) vim.treesitter.highlighter.Query
1010
---@field private _query vim.treesitter.Query?
@@ -248,6 +248,13 @@ end
248248
---@param line integer
249249
---@param is_spell_nav boolean
250250
local function on_line_impl(self, buf, line, is_spell_nav)
251+
-- Track the maximum pattern index encountered in each tree. For subsequent
252+
-- trees, the subpriority passed to nvim_buf_set_extmark is offset by the
253+
-- largest pattern index from the prior tree. This ensures that extmarks
254+
-- from subsequent trees always appear "on top of" extmarks from previous
255+
-- trees (e.g. injections should always appear over base highlights).
256+
local pattern_offset = 0
257+
251258
self:for_each_highlight_state(function(state)
252259
local root_node = state.tstree:root()
253260
local root_start_row, _, root_end_row, _ = root_node:range()
@@ -258,22 +265,24 @@ local function on_line_impl(self, buf, line, is_spell_nav)
258265
end
259266

260267
if state.iter == nil or state.next_row < line then
261-
state.iter =
262-
state.highlighter_query:query():iter_captures(root_node, self.bufnr, line, root_end_row + 1)
268+
state.iter = state.highlighter_query
269+
:query()
270+
:iter_matches(root_node, self.bufnr, line, root_end_row + 1, { all = true })
263271
end
264272

273+
local max_pattern_index = -1
265274
while line >= state.next_row do
266-
local capture, node, metadata = state.iter(line)
275+
local pattern, match, metadata = state.iter()
267276

268-
local range = { root_end_row + 1, 0, root_end_row + 1, 0 }
269-
if node then
270-
range = vim.treesitter.get_range(node, buf, metadata and metadata[capture])
277+
if pattern and pattern > max_pattern_index then
278+
max_pattern_index = pattern
271279
end
272-
local start_row, start_col, end_row, end_col = Range.unpack4(range)
273280

274-
if capture then
275-
local hl = state.highlighter_query:get_hl_from_capture(capture)
281+
if not match then
282+
state.next_row = root_end_row + 1
283+
end
276284

285+
for capture, nodes in pairs(match or {}) do
277286
local capture_name = state.highlighter_query:query().captures[capture]
278287
local spell = nil ---@type boolean?
279288
if capture_name == 'spell' then
@@ -282,28 +291,60 @@ local function on_line_impl(self, buf, line, is_spell_nav)
282291
spell = false
283292
end
284293

294+
local hl = state.highlighter_query:get_hl_from_capture(capture)
295+
285296
-- Give nospell a higher priority so it always overrides spell captures.
286297
local spell_pri_offset = capture_name == 'nospell' and 1 or 0
287298

288-
if hl and end_row >= line and (not is_spell_nav or spell ~= nil) then
289-
local priority = (tonumber(metadata.priority) or vim.highlight.priorities.treesitter)
290-
+ spell_pri_offset
291-
api.nvim_buf_set_extmark(buf, ns, start_row, start_col, {
292-
end_line = end_row,
293-
end_col = end_col,
294-
hl_group = hl,
295-
ephemeral = true,
296-
priority = priority,
297-
conceal = metadata.conceal,
298-
spell = spell,
299-
})
299+
-- The "priority" attribute can be set at the pattern level or on a particular capture
300+
local priority = (
301+
tonumber(metadata.priority or metadata[capture] and metadata[capture].priority)
302+
or vim.highlight.priorities.treesitter
303+
) + spell_pri_offset
304+
305+
local url = metadata[capture] and metadata[capture].url ---@type string|number|nil
306+
if type(url) == 'number' then
307+
if match and match[url] then
308+
-- Assume there is only one matching node. If there is more than one, take the URL
309+
-- from the first.
310+
local other_node = match[url][1]
311+
url = vim.treesitter.get_node_text(other_node, buf, {
312+
metadata = metadata[url],
313+
})
314+
else
315+
url = nil
316+
end
300317
end
301-
end
302318

303-
if start_row > line then
304-
state.next_row = start_row
319+
-- The "conceal" attribute can be set at the pattern level or on a particular capture
320+
local conceal = metadata.conceal or metadata[capture] and metadata[capture].conceal
321+
322+
for _, node in ipairs(nodes) do
323+
local range = vim.treesitter.get_range(node, buf, metadata[capture])
324+
local start_row, start_col, end_row, end_col = Range.unpack4(range)
325+
326+
if hl and end_row >= line and (not is_spell_nav or spell ~= nil) then
327+
api.nvim_buf_set_extmark(buf, ns, start_row, start_col, {
328+
end_line = end_row,
329+
end_col = end_col,
330+
hl_group = hl,
331+
ephemeral = true,
332+
priority = priority,
333+
_subpriority = pattern_offset + pattern,
334+
conceal = conceal,
335+
spell = spell,
336+
url = url,
337+
})
338+
end
339+
340+
if start_row > line then
341+
state.next_row = start_row
342+
end
343+
end
305344
end
306345
end
346+
347+
pattern_offset = pattern_offset + max_pattern_index
307348
end)
308349
end
309350

Diff for: runtime/queries/markdown_inline/highlights.scm

+5
Original file line numberDiff line numberDiff line change
@@ -33,6 +33,11 @@
3333
] @markup.link
3434
(#set! conceal ""))
3535

36+
(inline_link
37+
(link_text) @markup.link.label
38+
(link_destination) @markup.link
39+
(#set! @markup.link.label "url" @markup.link))
40+
3641
; Conceal image links
3742
(image
3843
[

Diff for: runtime/queries/vimdoc/highlights.scm

+16-7
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,30 @@
1212

1313
(tag
1414
"*" @markup.heading.5.marker
15-
(#set! conceal "")
16-
text: (_) @label)
15+
.
16+
text: (_) @label
17+
.
18+
"*" @markup.heading.5.marker
19+
(#set! @markup.heading.5.marker conceal ""))
1720

1821
(taglink
19-
"|" @markup.link
20-
(#set! conceal "")
21-
text: (_) @markup.link)
22+
"|" @markup.link.delimiter
23+
.
24+
text: (_) @markup.link
25+
.
26+
"|" @markup.link.delimiter
27+
(#set! @markup.link.delimiter conceal ""))
2228

2329
(optionlink
2430
text: (_) @markup.link)
2531

2632
(codespan
2733
"`" @markup.raw.delimiter
28-
(#set! conceal "")
29-
text: (_) @markup.raw)
34+
.
35+
text: (_) @markup.raw
36+
.
37+
"`" @markup.raw.delimiter
38+
(#set! @markup.raw.delimiter conceal ""))
3039

3140
((codeblock) @markup.raw.block
3241
(#set! "priority" 90))

Diff for: test/functional/treesitter/highlight_spec.lua

+88-1
Original file line numberDiff line numberDiff line change
@@ -681,6 +681,12 @@ describe('treesitter highlighting (C)', function()
681681
((identifier) @Identifier
682682
(#set! conceal "")
683683
(#eq? @Identifier "lstate"))
684+
685+
((call_expression
686+
function: (identifier) @function
687+
arguments: (argument_list) @arguments)
688+
(#eq? @function "multiqueue_put")
689+
(#set! @function conceal "V"))
684690
]]}})
685691
]=]
686692

@@ -697,7 +703,7 @@ describe('treesitter highlighting (C)', function()
697703
|
698704
LuaRef cb = nlua_ref(, 1); |
699705
|
700-
multiqueue_put(main_loop.events, nlua_schedule_event, |
706+
{11:V}(main_loop.events, nlua_schedule_event, |
701707
1, (void *)(ptrdiff_t)cb); |
702708
return 0; |
703709
^} |
@@ -758,6 +764,44 @@ describe('treesitter highlighting (C)', function()
758764
end)
759765
end)
760766

767+
describe('treesitter highlighting (lua)', function()
768+
local screen
769+
770+
before_each(function()
771+
screen = Screen.new(65, 18)
772+
screen:attach()
773+
screen:set_default_attr_ids {
774+
[1] = { bold = true, foreground = Screen.colors.Blue },
775+
[2] = { foreground = Screen.colors.DarkCyan },
776+
[3] = { foreground = Screen.colors.Magenta },
777+
[4] = { foreground = Screen.colors.SlateBlue },
778+
[5] = { bold = true, foreground = Screen.colors.Brown },
779+
}
780+
end)
781+
782+
it('supports language injections', function()
783+
insert [[
784+
local ffi = require('ffi')
785+
ffi.cdef("int (*fun)(int, char *);")
786+
]]
787+
788+
exec_lua [[
789+
vim.bo.filetype = 'lua'
790+
vim.treesitter.start()
791+
]]
792+
793+
screen:expect {
794+
grid = [[
795+
{5:local} {2:ffi} {5:=} {4:require(}{3:'ffi'}{4:)} |
796+
{2:ffi}{4:.}{2:cdef}{4:(}{3:"}{4:int}{3: }{4:(}{5:*}{3:fun}{4:)(int,}{3: }{4:char}{3: }{5:*}{4:);}{3:"}{4:)} |
797+
^ |
798+
{1:~ }|*14
799+
|
800+
]],
801+
}
802+
end)
803+
end)
804+
761805
describe('treesitter highlighting (help)', function()
762806
local screen
763807

@@ -891,3 +935,46 @@ vim.cmd([[
891935
}
892936
end)
893937
end)
938+
939+
describe('treesitter highlighting (markdown)', function()
940+
local screen
941+
942+
before_each(function()
943+
screen = Screen.new(40, 6)
944+
screen:attach()
945+
screen:set_default_attr_ids {
946+
[1] = { foreground = Screen.colors.Blue1 },
947+
[2] = { bold = true, foreground = Screen.colors.Blue1 },
948+
[3] = { bold = true, foreground = Screen.colors.Brown },
949+
[4] = { foreground = Screen.colors.Cyan4 },
950+
[5] = { foreground = Screen.colors.Magenta1 },
951+
}
952+
end)
953+
954+
it('supports hyperlinks', function()
955+
local url = 'https://example.com'
956+
insert(string.format('[This link text](%s) is a hyperlink.', url))
957+
exec_lua([[
958+
vim.bo.filetype = 'markdown'
959+
vim.treesitter.start()
960+
]])
961+
962+
screen:expect {
963+
grid = [[
964+
{4:[}{6:This link text}{4:](}{7:https://example.com}{4:)} is|
965+
a hyperlink^. |
966+
{2:~ }|*3
967+
|
968+
]],
969+
attr_ids = {
970+
[1] = { foreground = Screen.colors.Blue1 },
971+
[2] = { bold = true, foreground = Screen.colors.Blue1 },
972+
[3] = { bold = true, foreground = Screen.colors.Brown },
973+
[4] = { foreground = Screen.colors.Cyan4 },
974+
[5] = { foreground = Screen.colors.Magenta },
975+
[6] = { foreground = Screen.colors.Cyan4, url = url },
976+
[7] = { underline = true, foreground = Screen.colors.SlateBlue },
977+
},
978+
}
979+
end)
980+
end)

0 commit comments

Comments
 (0)