robin/laufey

git clone https://git.robinwobin.dev/robin/laufey

robinmerge: 1dc9728daa1d8a2702

master
19.0 KiB599 linesraw
1local api = vim.api
2
3---@type table<integer,vim.treesitter.LanguageTree>
4local parsers = setmetatable({}, { __mode = 'v' })
5
6local M = vim._defer_require('vim.treesitter', {
7  _fold = ..., --- @module 'vim.treesitter._fold'
8  _query_linter = ..., --- @module 'vim.treesitter._query_linter'
9  _range = ..., --- @module 'vim.treesitter._range'
10  dev = ..., --- @module 'vim.treesitter.dev'
11  highlighter = ..., --- @module 'vim.treesitter.highlighter'
12  language = ..., --- @module 'vim.treesitter.language'
13  languagetree = ..., --- @module 'vim.treesitter.languagetree'
14  query = ..., --- @module 'vim.treesitter.query'
15  _select = ..., --- @module 'vim.treesitter._select'
16})
17
18local LanguageTree = M.languagetree
19
20--- @nodoc
21M.language_version = vim._ts_get_language_version()
22
23--- @nodoc
24M.minimum_language_version = vim._ts_get_minimum_language_version()
25
26--- Creates a new parser
27---
28--- It is not recommended to use this; use |get_parser()| instead.
29---
30---@param buf integer Buffer the parser will be tied to (0 for current buffer)
31---@param lang string Language of the parser
32---@param opts (table|nil) Options to pass to the created language tree
33---
34---@return vim.treesitter.LanguageTree object to use for parsing
35function M._create_parser(buf, lang, opts)
36  buf = vim._resolve_bufnr(buf)
37
38  local self = LanguageTree.new(buf, lang, opts)
39
40  local function bytes_cb(_, ...)
41    self:_on_bytes(...)
42  end
43
44  local function detach_cb(_, ...)
45    if parsers[buf] == self then
46      parsers[buf] = nil
47    end
48    self:_on_detach(...)
49  end
50
51  local function reload_cb(_)
52    self:_on_reload()
53  end
54
55  local source = self:source() --[[@as integer]]
56
57  api.nvim_buf_attach(
58    source,
59    false,
60    { on_bytes = bytes_cb, on_detach = detach_cb, on_reload = reload_cb, preview = true }
61  )
62
63  return self
64end
65
66--- @param lang string?
67local function valid_lang(lang)
68  return lang and lang ~= ''
69end
70
71--- Returns the parser for a specific buffer and attaches it to the buffer
72---
73--- If needed, this will create the parser.
74---
75--- If no parser can be created, nil (and an error message) is returned.
76---
77---@param buf integer|nil (default: current buffer) Buffer the parser should be tied to
78---@param lang string|nil (default: from 'filetype') Language of this parser
79---@param opts table|nil Options to pass to the created language tree
80---
81---@return vim.treesitter.LanguageTree? object to use for parsing
82---@return string? error message, if applicable
83function M.get_parser(buf, lang, opts)
84  opts = opts or {}
85
86  buf = vim._resolve_bufnr(buf)
87
88  if not valid_lang(lang) then
89    lang = M.language.get_lang(vim.bo[buf].filetype)
90  end
91
92  if not valid_lang(lang) then
93    if not parsers[buf] then
94      return nil,
95        string.format('Parser not found for buffer %s: language could not be determined', buf)
96    end
97  elseif parsers[buf] == nil or parsers[buf]:lang() ~= lang then
98    if not api.nvim_buf_is_loaded(buf) then
99      return nil, string.format('Buffer %s must be loaded to create parser', buf)
100    end
101    local status, res = pcall(M._create_parser, buf, assert(lang), opts)
102    if not status then
103      local msg = 'Parser could not be created for buffer %s and language "%s": %s'
104      return nil, string.format(msg, buf, lang, res)
105    end
106    parsers[buf] = res
107  end
108
109  parsers[buf]:register_cbs(opts.buf_attach_cbs)
110
111  return parsers[buf]
112end
113
114--- Returns a string parser
115---
116---@param str string Text to parse
117---@param lang string Language of this string
118---@param opts (table|nil) Options to pass to the created language tree
119---
120---@return vim.treesitter.LanguageTree object to use for parsing
121function M.get_string_parser(str, lang, opts)
122  vim.validate('str', str, 'string')
123  vim.validate('lang', lang, 'string')
124
125  return LanguageTree.new(str, lang, opts)
126end
127
128--- Determines whether a node is the ancestor of another
129---
130---@param dest TSNode Possible ancestor
131---@param source TSNode Possible descendant
132---
133---@return boolean True if {dest} is an ancestor of {source}
134function M.is_ancestor(dest, source)
135  if not (dest and source) then
136    return false
137  end
138
139  return dest:child_with_descendant(source) ~= nil
140end
141
142--- Returns the node's range or an unpacked range table
143---
144---@param node_or_range TSNode|Range4 Node or table of positions
145---
146---@return integer start_row
147---@return integer start_col # (byte offset)
148---@return integer end_row
149---@return integer end_col # (byte offset)
150function M.get_node_range(node_or_range)
151  if type(node_or_range) == 'table' then
152    --- @cast node_or_range -TSNode LuaLS bug
153    return M._range.unpack4(node_or_range)
154  else
155    return node_or_range:range(false)
156  end
157end
158
159---@param node TSNode
160---@param source integer|string Buffer or string from which the {node} is extracted
161---@param offset Range4
162---@return Range6
163local function apply_range_offset(node, source, offset)
164  ---@diagnostic disable-next-line: missing-fields LuaLS varargs bug
165  local range = { node:range() } ---@type Range4
166  local start_row_offset = offset[1]
167  local start_col_offset = offset[2]
168  local end_row_offset = offset[3]
169  local end_col_offset = offset[4]
170
171  range[1] = range[1] + start_row_offset
172  range[2] = range[2] + start_col_offset
173  range[3] = range[3] + end_row_offset
174  range[4] = range[4] + end_col_offset
175
176  if range[1] < range[3] or (range[1] == range[3] and range[2] <= range[4]) then
177    return M._range.add_bytes(source, range)
178  end
179
180  -- If this produces an invalid range, we just skip it.
181  return { node:range(true) }
182end
183
184---Get the range of a |TSNode|. Can also supply {source} and {metadata}
185---to get the range with directives applied.
186---@param node TSNode
187---@param source integer|string|nil Buffer or string from which the {node} is extracted
188---@param metadata vim.treesitter.query.TSMetadata|nil
189---@return Range6
190function M.get_range(node, source, metadata)
191  if metadata then
192    if metadata.range then
193      return M._range.add_bytes(assert(source), metadata.range)
194    elseif metadata.offset then
195      return apply_range_offset(node, assert(source), metadata.offset)
196    end
197  end
198  return { node:range(true) }
199end
200
201---@param buf integer
202---@param range Range
203---@return string
204local function buf_range_get_text(buf, range)
205  local start_row, start_col, end_row, end_col = M._range.unpack4(range)
206  local append_newline = end_col == 0 and start_row ~= end_row
207
208  if end_col == 0 then
209    if start_row == end_row then
210      start_col = -1
211      start_row = start_row - 1
212    end
213    end_col = -1
214    end_row = end_row - 1
215  end
216
217  local lines = api.nvim_buf_get_text(buf, start_row, start_col, end_row, end_col)
218  if append_newline then
219    table.insert(lines, '')
220  end
221
222  return table.concat(lines, '\n')
223end
224
225--- Gets the text corresponding to a given node
226---
227---@param node TSNode
228---@param source (integer|string) Buffer or string from which the {node} is extracted
229---@param opts (table|nil) Optional parameters.
230---          - metadata (table) Metadata of a specific capture. This would be
231---            set to `metadata[capture_id]` when using |vim.treesitter.query.add_directive()|.
232---@return string
233function M.get_node_text(node, source, opts)
234  opts = opts or {}
235  local metadata = opts.metadata or {}
236
237  if metadata.text then
238    return metadata.text
239  elseif type(source) == 'number' then
240    local range = M.get_range(node, source, metadata)
241    return buf_range_get_text(source, range)
242  end
243
244  ---@cast source string
245  return source:sub(select(3, node:start()) + 1, select(3, node:end_()))
246end
247
248--- Determines whether (line, col) position is in node range
249---
250---@param node TSNode defining the range
251---@param line integer Line (0-based)
252---@param col integer Column (0-based)
253---
254---@return boolean True if the position is in node range
255function M.is_in_node_range(node, line, col)
256  return M.node_contains(node, { line, col, line, col + 1 })
257end
258
259--- Determines if a node contains a range
260---
261---@param node TSNode
262---@param range table
263---
264---@return boolean True if the {node} contains the {range}
265function M.node_contains(node, range)
266  -- allow a table so nodes can be mocked
267  vim.validate('node', node, { 'userdata', 'table' })
268  vim.validate('range', range, M._range.validate, 'integer list with 4 or 6 elements')
269  --- @diagnostic disable-next-line: missing-fields LuaLS bug
270  local nrange = { node:range() } --- @type Range4
271  return M._range.contains(nrange, range)
272end
273
274--- @class vim.treesitter.CaptureInfo
275--- @inlinedoc
276--- @field capture string Capture name
277--- @field lang string Language name
278--- @field metadata vim.treesitter.query.TSMetadata Query metadata, e.g. `priority` or `conceal`
279--- @field id integer 1-based capture id in the query
280--- @field pattern_id integer 1-based id of the matched pattern in the query
281--- @field row integer Start row
282--- @field col integer Start column
283--- @field end_row integer End row
284--- @field end_col integer End column (excluded)
285
286---@deprecated Use vim.treesitter.get_captures() instead.
287---@param buf integer
288---@param row integer
289---@param col integer
290---@return vim.treesitter.CaptureInfo[]
291function M.get_captures_at_pos(buf, row, col)
292  vim.deprecate('vim.treesitter.get_captures_at_pos()', 'vim.treesitter.get_captures()', '0.15')
293  return M.get_captures(buf, { row, col })
294end
295
296--- Returns highlight captures at a position, on a line, or overlapping a range.
297---
298--- {start} and {stop} can be a row number or a `{row, col}` pair. All rows and
299--- columns are 0-based; columns are byte offsets.
300---
301--- Without {stop}, a row number queries the whole line and a `{row, col}` pair
302--- queries one position.
303---
304--- With {stop}, return captures that overlap the range. The stop position is
305--- excluded; a row number excludes that row. Empty ranges return no captures.
306---
307--- Each result includes the full captured node range, which may extend outside the
308--- requested range. Returns an empty list if treesitter highlighting is not active
309--- in {buf}.
310---
311---@since 15
312---@param buf integer Buffer number (0 for current buffer)
313---@param start integer|[integer,integer] Start row or `{row, col}`
314---@param stop? integer|[integer,integer] Stop row or `{row, col}` (excluded)
315---@return vim.treesitter.CaptureInfo[]
316function M.get_captures(buf, start, stop)
317  buf = vim._resolve_bufnr(buf)
318
319  --- @type integer, integer, integer, integer
320  local start_row, start_col, end_row, end_col
321  if type(start) == 'number' then
322    start_row, start_col = start, 0
323  else
324    start_row, start_col = start[1], start[2]
325  end
326
327  if stop == nil then
328    end_row = type(start) == 'number' and start_row + 1 or start_row
329    end_col = type(start) == 'number' and 0 or start_col + 1
330  elseif type(stop) == 'number' then
331    end_row, end_col = stop, 0
332  else
333    end_row, end_col = stop[1], stop[2]
334  end
335
336  local buf_highlighter = M.highlighter.active[buf]
337
338  if not buf_highlighter or M._range.cmp_pos.ge(start_row, start_col, end_row, end_col) then
339    return {}
340  end
341
342  local matches = {} --- @type vim.treesitter.CaptureInfo[]
343  local query_range = { start_row, start_col, end_row, end_col } --- @type Range4
344
345  -- Highlighting only parses visible ranges, so offscreen injections may be missing.
346  buf_highlighter.tree:parse(query_range)
347  buf_highlighter.tree:for_each_tree(function(tstree, tree)
348    if not tstree then
349      return
350    end
351
352    local root = tstree:root()
353    if not M._range.intercepts({ root:range() }, query_range) then
354      return
355    end
356
357    local q = buf_highlighter:get_query(tree:lang())
358    local query = q:query()
359
360    -- Some injected languages may not have highlight queries.
361    if not query then
362      return
363    end
364
365    local iter = query:iter_captures(root, buf_highlighter.bufnr, start_row, end_row, {
366      start_col = start_col,
367      end_col = end_col,
368    })
369    for id, node, metadata, match in iter do
370      local nsrow, nscol, nerow, necol = node:range()
371      if M._range.intercepts({ nsrow, nscol, nerow, necol }, query_range) then
372        ---@diagnostic disable-next-line: invisible
373        local capture = query.captures[id] -- name of the capture in the query
374        if capture ~= nil then
375          local _, pattern_id = match:info()
376          matches[#matches + 1] = {
377            capture = capture,
378            metadata = metadata,
379            lang = tree:lang(),
380            id = id,
381            pattern_id = pattern_id,
382            row = nsrow,
383            col = nscol,
384            end_row = nerow,
385            end_col = necol,
386          }
387        end
388      end
389    end
390  end)
391  return matches
392end
393
394--- Returns a list of highlight capture names under the cursor
395---
396---@param win integer|nil # |window-ID| or 0 for current window (default)
397---
398---@return string[] List of capture names
399function M.get_captures_at_cursor(win)
400  win = win or 0
401  local bufnr = api.nvim_win_get_buf(win)
402  local cursor = api.nvim_win_get_cursor(win)
403
404  local data = M.get_captures(bufnr, { cursor[1] - 1, cursor[2] })
405
406  local captures = {}
407
408  for _, capture in ipairs(data) do
409    table.insert(captures, capture.capture)
410  end
411
412  return captures
413end
414
415--- Optional keyword arguments:
416--- @class vim.treesitter.get_node.Opts : vim.treesitter.LanguageTree.tree_for_range.Opts
417--- @inlinedoc
418---
419--- Buffer number (nil or 0 for current buffer)
420--- @field bufnr integer?
421---
422--- 0-indexed (row, col) tuple. Required if {bufnr} is not the current buffer
423--- (default: window-local cursor)
424--- @field pos [integer, integer]?
425---
426--- Parser language.
427--- (default: from 'filetype')
428--- @field lang string?
429---
430--- Ignore injected languages
431--- (default: true)
432--- @field ignore_injections boolean?
433---
434--- Include anonymous nodes
435--- (default: false)
436--- @field include_anonymous boolean?
437
438--- Returns the smallest named node at the given position
439---
440--- NOTE: Calling this on an unparsed tree can yield an invalid node.
441--- If the tree is not known to be parsed by, e.g., an active highlighter,
442--- parse the tree first via
443---
444--- ```lua
445--- vim.treesitter.get_parser(bufnr):parse(range)
446--- ```
447---
448---@param opts vim.treesitter.get_node.Opts?
449---
450---@return TSNode | nil Node at the given position
451function M.get_node(opts)
452  opts = opts or {}
453
454  local bufnr = vim._resolve_bufnr(opts.bufnr)
455
456  local row, col --- @type integer, integer
457  if opts.pos then
458    assert(#opts.pos == 2, 'Position must be a (row, col) tuple')
459    row, col = opts.pos[1], opts.pos[2]
460  else
461    assert(
462      bufnr == api.nvim_get_current_buf(),
463      'Position must be explicitly provided when not using the current buffer'
464    )
465    local pos = api.nvim_win_get_cursor(0)
466    -- Subtract one to account for 1-based row indexing in nvim_win_get_cursor
467    row, col = pos[1] - 1, pos[2]
468  end
469
470  assert(row >= 0 and col >= 0, 'Invalid position: row and col must be non-negative')
471
472  local ts_range = { row, col, row, col }
473
474  local root_lang_tree = M.get_parser(bufnr, opts.lang)
475  if not root_lang_tree then
476    return
477  end
478
479  if opts.include_anonymous then
480    return root_lang_tree:node_for_range(ts_range, opts)
481  end
482  return root_lang_tree:named_node_for_range(ts_range, opts)
483end
484
485--- Starts treesitter highlighting for a buffer
486---
487--- Can be used in an ftplugin or FileType autocommand.
488---
489--- Note: By default, disables regex syntax highlighting, which may be required for some plugins.
490--- In this case, add `vim.bo.syntax = 'ON'` after the call to `start`.
491---
492--- Note: By default, the highlighter parses code asynchronously, using a segment time of 3ms.
493---
494--- Example:
495---
496--- ```lua
497--- vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
498---     callback = function(ev)
499---         vim.treesitter.start(ev.buf, 'latex')
500---         vim.bo[ev.buf].syntax = 'ON'  -- only if additional legacy syntax is needed
501---     end
502--- })
503--- ```
504---
505---@param buf integer? (default: current buffer) Buffer to be highlighted
506---@param lang string? (default: from 'filetype') Language of the parser
507function M.start(buf, lang)
508  buf = vim._resolve_bufnr(buf)
509  -- Ensure buffer is loaded. `:edit` over `bufload()` to show swapfile prompt.
510  if not api.nvim_buf_is_loaded(buf) then
511    if api.nvim_buf_get_name(buf) ~= '' then
512      pcall(api.nvim_buf_call, buf, vim.cmd.edit)
513    else
514      vim.fn.bufload(buf)
515    end
516  end
517  local parser = assert(M.get_parser(buf, lang))
518  M.highlighter.new(parser)
519end
520
521--- Stops treesitter highlighting for a buffer
522---
523---@param buf integer|nil (default: current buffer) Buffer to stop highlighting
524function M.stop(buf)
525  buf = vim._resolve_bufnr(buf)
526
527  if M.highlighter.active[buf] then
528    M.highlighter.active[buf]:destroy()
529  end
530end
531
532--- Open a window that displays a textual representation of the nodes in the language tree.
533---
534--- While in the window, press "a" to toggle display of anonymous nodes, "I" to toggle the
535--- display of the source language of each node, "o" to toggle the query editor, and press
536--- [<Enter>] to jump to the node under the cursor in the source buffer. Folding also works
537--- (try |zo|, |zc|, etc.).
538---
539--- Can also be shown with `:InspectTree`. [:InspectTree]()
540---
541---@since 11
542---@param opts table|nil Optional options table with the following possible keys:
543---                      - bufnr (integer|nil): Buffer to draw the tree into. If omitted, a new
544---                        buffer is created.
545---                      - command (string|nil): Vimscript command to create the window. Default
546---                        value is "60vnew". Only used when {winid} is nil.
547---                      - lang (string|nil): The language of the source buffer. If omitted, detect
548---                        from the filetype of the source buffer.
549---                      - title (string|fun(bufnr:integer):string|nil): Title of the window. If a
550---                        function, it accepts the buffer number of the source buffer as its only
551---                        argument and should return a string.
552---                      - winid (integer|nil): Window id to display the tree buffer in. If omitted,
553---                        a new window is created with {command}.
554function M.inspect_tree(opts)
555  ---@diagnostic disable-next-line: invisible
556  M.dev.inspect_tree(opts)
557end
558
559--- Returns the fold level for {lnum} in the current buffer. Can be set directly to 'foldexpr':
560---
561--- ```lua
562--- vim.wo.foldexpr = vim.treesitter.foldexpr
563--- ```
564---
565---@since 11
566---@param lnum integer|nil Line number to calculate fold level for
567---@return string
568function M.foldexpr(lnum)
569  return M._fold.foldexpr(lnum)
570end
571
572--- Starts or adjusts a |Visual| selection at cursor, based on tree nodes. The `target` parameter
573--- decides the selection behavior.
574---
575---@param target 'parent'|'child'|'next'|'prev'|'extend_next'|'extend_prev' Decides the selection behavior.
576---@param count? integer (default: 1) Expand or adjust the selection this many times.
577function M.select(target, count)
578  vim.validate('target', target, 'string')
579  vim.validate('count', count, 'number', true)
580  count = count or 1
581
582  if target == 'parent' then
583    return M._select.select_parent(count)
584  elseif target == 'child' then
585    return M._select.select_child(count)
586  elseif target == 'next' then
587    return M._select.select_next(count)
588  elseif target == 'prev' then
589    return M._select.select_prev(count)
590  elseif target == 'extend_next' then
591    return M._select.select_grow_next(count)
592  elseif target == 'extend_prev' then
593    return M._select.select_grow_prev(count)
594  else
595    error(('Invalid target: %s'):format(target))
596  end
597end
598
599return M