Nvim :help
pages, generated
from source
using the tree-sitter-vimdoc parser.
tree-sitter
library for incremental parsing of buffers:
https://tree-sitter.github.io/tree-sitter/parser
runtime directory.parser/{lang}.*
in any 'runtimepath' directory.
If multiple parsers for the same language are found, the first one is used.
(NOTE: This typically implies the priority "user config > plugins > bundled".)vim.treesitter.language.add('python', { path = "/path/to/python.so" })
xml
treesitter parser for buffers with filetype svg
or xslt
, use:vim.treesitter.language.register('xml', { 'svg', 'xslt' })
TSTree
TSTree
of a treesitter tree supports the following methods.TSTree:root()
Return the root node of this tree.TSTree:copy()
Returns a copy of the TSTree
.TSNode
TSNode
of a treesitter node supports the following methods.TSNode:parent()
Get the node's immediate parent.
Prefer TSNode:child_containing_descendant()
for iterating over the node's ancestors.TSNode:next_sibling()
Get the node's next sibling.TSNode:prev_sibling()
Get the node's previous sibling.TSNode:next_named_sibling()
Get the node's next named sibling.TSNode:prev_named_sibling()
Get the node's previous named sibling.TSNode:iter_children()
Iterates over all the direct children of {TSNode}
, regardless of whether
they are named or not.
Returns the child node plus the eventual field name corresponding to this
child node.TSNode:child_count()
Get the node's number of children.{index}
) TSNode:child()
Get the node's child at the given {index}
, where zero represents the first
child.TSNode:named_child_count()
Get the node's number of named children.{index}
) TSNode:named_child()
Get the node's named child at the given {index}
, where zero represents the
first named child.{descendant}
) TSNode:child_containing_descendant()
Get the node's child that contains {descendant}
.TSNode:start()
Get the node's start position. Return three values: the row, column and
total byte count (all zero-based).TSNode:end_()
Get the node's end position. Return three values: the row, column and
total byte count (all zero-based).{include_bytes}
) TSNode:range()
Get the range of the node.{include_bytes}
is true
)
{include_bytes}
is true
)
TSNode:type()
Get the node's type as a string.TSNode:symbol()
Get the node's type as a numerical id.TSNode:named()
Check if the node is named. Named nodes correspond to named rules in the
grammar, whereas anonymous nodes correspond to string literals in the
grammar.TSNode:missing()
Check if the node is missing. Missing nodes are inserted by the parser in
order to recover from certain kinds of syntax errors.TSNode:extra()
Check if the node is extra. Extra nodes represent things like comments,
which are not required by the grammar but can appear anywhere.TSNode:has_changes()
Check if a syntax node has been edited.TSNode:has_error()
Check if the node is a syntax error or contains any syntax errors.TSNode:sexpr()
Get an S-expression representing the node as a string.TSNode:id()
Get a unique identifier for the node inside its own tree.id
is not guaranteed to be unique for nodes from different
trees.TSNode:tree()
Get the TSTree of the node.
TSNode:descendant_for_range()
TSNode:descendant_for_range({start_row}
, {start_col}
, {end_row}
, {end_col}
)
Get the smallest node within this node that spans the given range of (row,
column) positionsTSNode:named_descendant_for_range()
TSNode:named_descendant_for_range({start_row}
, {start_col}
, {end_row}
, {end_col}
)
Get the smallest named node within this node that spans the given range of
(row, column) positions
TSNode:equal()
TSNode:equal({node}
)
Check if {node}
refers to the same node within the same tree.TSNode:byte_length()
TSNode:byte_length()
Return the number of bytes spanned by this node.query
consists of one or
more patterns. A pattern
is defined over node types in the syntax tree. A
match
corresponds to specific elements of the syntax tree which match a
pattern. Patterns may optionally define captures and predicates. A capture
allows you to associate names with a specific node in a pattern. A predicate
adds arbitrary metadata and conditional data to a match.*.scm
files in a queries
directory under
runtimepath
, where each file contains queries for a specific language and
purpose, e.g., queries/lua/highlights.scm
for highlighting Lua files.
By default, the first query on runtimepath
is used (which usually implies
that user config takes precedence over plugins, which take precedence over
queries bundled with Nvim). If a query should extend other queries instead
of replacing them, use treesitter-query-modeline-extends.eq?
predicate can be used as follows:((identifier) @variable.builtin
(#eq? @variable.builtin "self"))
"self"
text. Such queries can
be used to highlight built-in functions or variables differently, for instance.eq?
treesitter-predicate-eq?
Match a string against the text corresponding to a node:((identifier) @variable.builtin (#eq? @variable.builtin "self"))
((node1) @left (node2) @right (#eq? @left @right))
any-eq?
treesitter-predicate-any-eq?
Like eq?
, but for quantified patterns only one captured node must
match.match?
treesitter-predicate-match?
vim-match?
treesitter-predicate-vim-match?
Match a regexp against the text corresponding to a node:((identifier) @constant (#match? @constant "^[A-Z_]+$"))
^
and $
anchors will match the start and end of the
node's text.any-match?
treesitter-predicate-any-match?
any-vim-match?
treesitter-predicate-any-vim-match?
Like match?
, but for quantified patterns only one captured node must
match.lua-match?
treesitter-predicate-lua-match?
Match lua-patterns against the text corresponding to a node,
similar to match?
any-lua-match?
treesitter-predicate-any-lua-match?
Like lua-match?
, but for quantified patterns only one captured node
must match.contains?
treesitter-predicate-contains?
Match a string against parts of the text corresponding to a node:((identifier) @foo (#contains? @foo "foo"))
((identifier) @foo-bar (#contains? @foo-bar "foo" "bar"))
any-contains?
treesitter-predicate-any-contains?
Like contains?
, but for quantified patterns only one captured node
must match.any-of?
treesitter-predicate-any-of?
Match any of the given strings against the text corresponding to
a node:((identifier) @foo (#any-of? @foo "foo" "bar"))
has-ancestor?
treesitter-predicate-has-ancestor?
Match any of the given node types against all ancestors of a node:((identifier) @variable.builtin
(#any-of? @variable.builtin "begin" "end")
(#has-ancestor? @variable.builtin range_expression))
has-parent?
treesitter-predicate-has-parent?
Match any of the given node types against the direct ancestor of a
node:(((field_expression
(field_identifier) @method)) @_parent
(#has-parent? @_parent template_method function_declarator))
lua-treesitter-not-predicate
Each predicate has a not-
prefixed predicate that is just the negation of
the predicate.lua-treesitter-all-predicate
lua-treesitter-any-predicate
Queries can use quantifiers to capture multiple nodes. When a capture contains
multiple nodes, predicates match only if ALL nodes contained by the capture
match the predicate. Some predicates (eq?
, match?
, lua-match?
,
contains?
) accept an any-
prefix to instead match if ANY of the nodes
contained by the capture match the predicate.-- TODO: This is a
-- very long
-- comment (just imagine it)
(((comment)+ @comment)
(#match? @comment "TODO"))
(((comment)+ @comment)
(#any-match? @comment "TODO"))
set!
directive sets metadata on the match or node:((identifier) @foo (#set! "type" "parameter"))
set!
treesitter-directive-set!
Sets key/value metadata for a specific match or capture. Value is
accessible as either metadata[key]
(match specific) or
metadata[capture_id][key]
(capture specific).{capture_id}
(optional)
{key}
{value}
((identifier) @foo (#set! @foo "kind" "parameter"))
((node1) @left (node2) @right (#set! "type" "pair"))
((codeblock) @markup.raw.block (#set! "priority" 90))
offset!
treesitter-directive-offset!
Takes the range of the captured node and applies an offset. This will
set a new Range4
object for the captured node with capture_id
as
metadata[capture_id].range
. Useful for treesitter-language-injections.{capture_id}
{start_row}
{start_col}
{end_row}
{end_col}
((identifier) @constant (#offset! @constant 0 1 0 -1))
gsub!
treesitter-directive-gsub!
Transforms the content of the node using a lua-pattern. This will set
a new metadata[capture_id].text
.{capture_id}
{pattern}
{replacement}
(#gsub! @_node ".*%.(.*)" "%1")
trim!
treesitter-directive-trim!
Trim blank lines from the end of the node. This will set a new
metadata[capture_id].range
.{capture_id}
(#trim! @fold)
;
. Here are the
currently supported modeline alternatives:inherits: {lang}...
treesitter-query-modeline-inherits
Specifies that this query should inherit the queries from {lang}
.
This will recursively descend in the queries of {lang}
unless wrapped
in parentheses: ({lang})
.
Note: This is meant to be used to include queries from another
language. If you want your query to extend the queries of the same
language, use extends
.extends
treesitter-query-modeline-extends
Specifies that this query should be used as an extension for the
query, i.e. that it should be merged with the others.
Note: The order of the extensions, and the query that will be used as
a base depends on your 'runtimepath' value.;; inherits: typescript,jsx
;; extends
;; extends
;;
;; inherits: css
highlights.scm
,
which match a TSNode in the parsed TSTree to a capture
that can be
assigned a highlight group. For example, the query(parameters (identifier) @variable.parameter)
identifier
node inside a function parameters
node to the
capture named @variable.parameter
. For example, for a Lua codefunction f(foo, bar) end
(function_declaration ; [1:1 - 24]
name: (identifier) ; [1:10 - 10]
parameters: (parameters ; [1:11 - 20]
name: (identifier) ; [1:12 - 14]
name: (identifier))) ; [1:17 - 19]
foo
and bar
as @variable.parameter
.[
"if"
"else"
] @keyword.conditional
highlights.scm
query is found in runtimepath,
treesitter highlighting for the current buffer can be enabled simply via
vim.treesitter.start().treesitter-highlight-groups
The capture names, prefixed with @
, are directly usable as highlight groups.
For many commonly used captures, the corresponding highlight groups are linked
to Nvim's standard highlight-groups by default (e.g., @comment
links to
Comment
) but can be overridden in colorschemes.@comment.documentation
could be used. If this group
is not defined, the highlighting for an ordinary @comment
is used. This way,
existing color schemes already work out of the box, but it is possible to add
more specific variants for queries that make them available.hi @comment.c guifg=Blue
hi @comment.lua guifg=DarkBlue
hi link @comment.documentation.java String
this
, self
)
@variable.parameter parameters of a function
@variable.parameter.builtin special parameters (e.g. _
, it
)
@variable.member object and struct fieldsGOTO
and other labels (e.g. label:
in C), including heredoc labelstypedef <type> <identifier>
in C)@property
in Python)
@property the key in key/value pairs+
, *
)go
in Go, async/await
in Python)
@keyword.function keywords that define a function (e.g. func
in Go, def
in Python)
@keyword.operator operators that are English words (e.g. and
, or
)
@keyword.import keywords for including modules (e.g. import
, from
in Python)
@keyword.type keywords defining composite types (e.g. struct
, enum
)
@keyword.modifier keywords defining type modifiers (e.g. const
, static
, public
)
@keyword.repeat keywords related to loops (e.g. for
, while
)
@keyword.return keywords like return
and yield
@keyword.debug keywords related to debugging
@keyword.exception keywords related to exceptions (e.g. throw
, catch
)if
, else
)
@keyword.conditional.ternary ternary operator (e.g. ?
, :
);
, .
, ,
)
@punctuation.bracket brackets (e.g. ()
, {}
, []
)
@punctuation.special special symbols (e.g. {}
in string interpolation)ERROR
, FIXME
, DEPRECATED
)
@comment.warning warning-type comments (e.g. WARNING
, FIX
, HACK
)
@comment.todo todo-type comments (e.g. TODO
, WIP
)
@comment.note note-type comments (e.g. NOTE
, INFO
, XXX
)$ ... $
in LaTeX)treesitter-highlight-spell
The special @spell
capture can be used to indicate that a node should be
spell checked by Nvim's builtin spell checker. For example, the following
capture marks comments as to be checked:(comment) @spell
@nospell
which disables spellchecking regions with @spell
.treesitter-highlight-conceal
Treesitter highlighting supports conceal via the conceal
metadata. By
convention, nodes to be concealed are captured as @conceal
, but any capture
can be used. For example, the following query can be used to hide code block
delimiters in Markdown:(fenced_code_block_delimiter @conceal (#set! conceal ""))
!=
operator by a Unicode glyph, which is
still highlighted the same as other operators:"!=" @operator (#set! conceal "≠")
treesitter-highlight-priority
Treesitter uses nvim_buf_set_extmark() to set highlights with a default
priority of 100. This enables plugins to set a highlighting priority lower or
higher than treesitter. It is also possible to change the priority of an
individual query pattern manually by setting its "priority"
metadata
attribute:((super_important_node) @superimportant (#set! "priority" 105))
<script>
tags and
CSS inside of <style>
tags
<%
%>
tags, and HTML outside of
those tags
<php
tags
@injection.content
- indicates that the captured node should have its
contents re-parsed using another language.
@injection.language
- indicates that the captured node’s text may
contain the name of a language that should be used to re-parse the
@injection.content
.
@injection.filename
- indicates that the captured node’s 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
.
injection.language
- can be used to hard-code the name of a specific
language.
injection.combined
- indicates that all of the matching nodes in the
tree should have their content parsed as one nested document.
injection.include-children
- indicates that the @injection.content
node's entire text should be re-parsed, including the text of its child
nodes. By default, child nodes' text will be excluded from the injected
document.
injection.self
- indicates that the node's text should be parsed with
the same language as the node's LanguageTree.
injection.parent
- indicates that the captured node’s text should
be parsed with the same language as the node's parent LanguageTree.
vim.treesitter
Lua module, which is the main interface for Nvim's treesitter integration.
Most of the following content is automatically generated from the function
documentation.vim.treesitter.language_version
The latest parser ABI version that is supported by the bundled treesitter
library.vim.treesitter.minimum_language_version
The earliest parser ABI version that is supported by the bundled treesitter
library.{lnum}
) vim.treesitter.foldexpr()
Returns the fold level for {lnum}
in the current buffer. Can be set
directly to 'foldexpr':vim.wo.foldexpr = 'v:lua.vim.treesitter.foldexpr()'
{lnum}
(integer?
) Line number to calculate fold level for
string
)vim.treesitter.get_captures_at_cursor()
get_captures_at_cursor({winnr}
)
Returns a list of highlight capture names under the cursor{winnr}
(integer?
) Window handle or 0 for current window (default)
string[]
) List of capture namesvim.treesitter.get_captures_at_pos()
get_captures_at_pos({bufnr}
, {row}
, {col}
)
Returns a list of highlight captures at the given positionpriority
, conceal
, ...; empty
if none are defined).{bufnr}
(integer
) Buffer number (0 for current buffer)
{row}
(integer
) Position row
{col}
(integer
) Position column
{capture: string, lang: string, metadata: table}[]
){opts}
) vim.treesitter.get_node()
Returns the smallest named node at the given positionvim.treesitter.get_parser(bufnr):parse(range)
{opts}
(table?
) Optional keyword arguments:
{bufnr}
(integer?
) Buffer number (nil or 0 for current
buffer)
{pos}
({ [1]: integer, [2]: integer }?
) 0-indexed (row,
col) tuple. Defaults to cursor position in the current
window. Required if {bufnr}
is not the current buffer
{lang}
(string?
) Parser language. (default: from buffer
filetype)
{ignore_injections}
(boolean?
) Ignore injected languages
(default true)
TSNode?
) Node at the given position{node_or_range}
) vim.treesitter.get_node_range()
Returns the node's range or an unpacked range table{node_or_range}
(TSNode|table
) Node or table of positions
integer
) start_row
(integer
) start_col
(integer
) end_row
(integer
) end_colvim.treesitter.get_node_text()
get_node_text({node}
, {source}
, {opts}
)
Gets the text corresponding to a given node{node}
(TSNode
)
{source}
(integer|string
) Buffer or string from which the {node}
is
extracted
{opts}
(table?
) Optional parameters.
metadata[capture_id]
when using
vim.treesitter.query.add_directive().
string
){bufnr}
, {lang}
, {opts}
) vim.treesitter.get_parser()
Returns the parser for a specific buffer and attaches it to the buffer{bufnr}
(integer?
) Buffer the parser should be tied to (default:
current buffer)
{lang}
(string?
) Language of this parser (default: from buffer
filetype)
{opts}
(table?
) Options to pass to the created language tree
vim.treesitter.LanguageTree
) object to use for parsing{node}
, {source}
, {metadata}
) vim.treesitter.get_range()
Get the range of a TSNode. Can also supply {source}
and {metadata}
to
get the range with directives applied.{node}
(TSNode
)
{source}
(integer|string?
) Buffer or string from which the {node}
is extracted
{metadata}
(vim.treesitter.query.TSMetadata?
)
Range6
){str}
(string
) Text to parse
{lang}
(string
) Language of this string
{opts}
(table?
) Options to pass to the created language tree
vim.treesitter.LanguageTree
) object to use for parsing{opts}
) vim.treesitter.inspect_tree()
Open a window that displays a textual representation of the nodes in the
language tree.<Enter>
to jump to the node under the cursor
in the source buffer. Folding also works (try zo, zc, etc.).:InspectTree
. :InspectTree
{opts}
(table?
) Optional options table with the following possible
keys:
{command}
.
{winid}
is
nil.
{dest}
, {source}
) vim.treesitter.is_ancestor()
Determines whether a node is the ancestor of another{dest}
(TSNode
) Possible ancestor
{source}
(TSNode
) Possible descendant
boolean
) True if {dest}
is an ancestor of {source}
vim.treesitter.is_in_node_range()
is_in_node_range({node}
, {line}
, {col}
)
Determines whether (line, col) position is in node range{node}
(TSNode
) defining the range
{line}
(integer
) Line (0-based)
{col}
(integer
) Column (0-based)
boolean
) True if the position is in node range{node}
(TSNode
)
{range}
(table
)
boolean
) True if the {node}
contains the {range}
vim.bo.syntax = 'on'
after
the call to start
.vim.api.nvim_create_autocmd( 'FileType', { pattern = 'tex',
callback = function(args)
vim.treesitter.start(args.buf, 'latex')
vim.bo[args.buf].syntax = 'on' -- only if additional legacy syntax is needed
end
})
{bufnr}
(integer?
) Buffer to be highlighted (default: current
buffer)
{lang}
(string?
) Language of the parser (default: from buffer
filetype)
{bufnr}
) vim.treesitter.stop()
Stops treesitter highlighting for a buffer{bufnr}
(integer?
) Buffer to stop highlighting (default: current
buffer)
parser
runtime directory, or the provided
{path}
{lang}
(string
) Name of the parser (alphanumerical and _
only)
{opts}
(table?
) Options:
{filetype}
(string|string[]
, default: {lang}
) Default
filetype the parser should be associated with.
{path}
(string
) Optional path the parser is located at
{symbol_name}
(string
) Internal symbol name for the
language to load
{lang}
) vim.treesitter.language.get_filetypes()
Get the filetypes associated with the parser named {lang}
.{lang}
(string
) Name of parser
string[]
) filetypes{filetype}
) vim.treesitter.language.get_lang()
{filetype}
(string
)
string?
){lang}
) vim.treesitter.language.inspect()
Inspects the provided language.{lang}
(string
) Language
table
){lang}
, {filetype}
) vim.treesitter.language.register()
Register a parser named {lang}
to be used for {filetype}
(s).{filetype}
, any existing
mappings from other filetypes to {lang}
will be preserved.{lang}
(string
) Name of parser
{filetype}
(string|string[]
) Filetype(s) to associate with lang
vim.treesitter.query.add_directive()
add_directive({name}
, {handler}
, {opts}
)
Adds a new directive to be used in queriesmetadata.key = value
. Additionally, handlers can set node level
data by using the capture id on the metadata table
metadata[capture_id].key = value
{name}
(string
) Name of the directive, without leading #
{handler}
(fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: table)
)
(node (#set! conceal "-"))
would get
the predicate { "#set!", "conceal", "-" }
{opts}
(table
) A table with the following fields:
{force}
(boolean
) Override an existing predicate of
the same name
{all}
(boolean
) Use the correct implementation of the
match table where capture IDs map to a list of nodes
instead of a single node. Defaults to false (for backward
compatibility). This option will eventually become the
default and removed.
vim.treesitter.query.add_predicate()
add_predicate({name}
, {handler}
, {opts}
)
Adds a new predicate to be used in queries{name}
(string
) Name of the predicate, without leading #
{handler}
(fun(match: table<integer,TSNode[]>, pattern: integer, source: integer|string, predicate: any[], metadata: table)
)
{opts}
(table
) A table with the following fields:
{force}
(boolean
) Override an existing predicate of
the same name
{all}
(boolean
) Use the correct implementation of the
match table where capture IDs map to a list of nodes
instead of a single node. Defaults to false (for backward
compatibility). This option will eventually become the
default and removed.
{lang}
) vim.treesitter.query.edit()
Opens a live editor to query the buffer you started from.:EditQuery
.:write
to save it. You can find example queries at
$VIMRUNTIME/queries/
.{lang}
(string?
) language to open the query editor for. If omitted,
inferred from the current buffer's filetype.
{lang}
, {query_name}
) vim.treesitter.query.get()
Returns the runtime query {query_name}
for {lang}
.{lang}
(string
) Language to use for the query
{query_name}
(string
) Name of the query (e.g. "highlights")
vim.treesitter.Query?
) Parsed query. nil
if no query files are
found.vim.treesitter.query.get_files()
get_files({lang}
, {query_name}
, {is_included}
)
Gets the list of files used to make up a query{lang}
(string
) Language to get query for
{query_name}
(string
) Name of the query to load (e.g.,
"highlights")
{is_included}
(boolean?
) Internal parameter, most of the time left
as nil
string[]
) query_files List of files to load for given query and
language{buf}
, {opts}
) vim.treesitter.query.lint()
Lint treesitter queries using installed parser, or clear lint errors.{buf}
for errors:
/lua/highlights.scm
, the parser
for the lua
language will be used.{buf}
(integer
) Buffer handle
{opts}
(table?
) Optional keyword arguments:
{langs}
(string|string[]
) Language(s) to use for checking
the query. If multiple languages are specified, queries are
validated for all of them
{clear}
(boolean
) Just clear current lint errors
vim.treesitter.query.list_directives()
Lists the currently available directives to use in queries.string[]
) Supported directives.vim.treesitter.query.list_predicates()
Lists the currently available predicates to use in queries.string[]
) Supported predicates.{findstart}
, {base}
) vim.treesitter.query.omnifunc()
Omnifunc for completing node names and predicates in treesitter queries.vim.bo.omnifunc = 'v:lua.vim.treesitter.query.omnifunc'
{findstart}
(0|1
)
{base}
(string
)
{lang}
, {query}
) vim.treesitter.query.parse()
Parse {query}
as a string. (If the query is in a file, the caller should
read the contents into a string before calling).Query
(see lua-treesitter-query) object which can be used to
search nodes in the syntax tree for the patterns defined in {query}
using
the iter_captures
and iter_matches
methods.info
and captures
with additional context about {query}
.
captures
contains the list of unique capture names defined in {query}
.
info.captures
also points to captures
.
info.patterns
contains information about predicates.
{lang}
(string
) Language to use for the query
{query}
(string
) Query in s-expr syntax
vim.treesitter.Query
) Parsed queryQuery:iter_captures()
Query:iter_captures({node}
, {source}
, {start}
, {stop}
)
Iterate over all captures from all matches inside {node}
{source}
is needed if the query contains predicates; then the caller must
ensure to use a freshly parsed tree consistent with the current text of
the buffer (if relevant). {start}
and {stop}
can be used to limit matches
inside a row range (this is typically used with root node as the {node}
,
i.e., to get syntax highlight matches in the current viewport). When
omitted, the {start}
and {stop}
row values are used from the given node.for id, node, metadata, match in query:iter_captures(tree:root(), bufnr, first, last) do
local name = query.captures[id] -- name of the capture in the query
-- typically useful info about the node:
local type = node:type() -- type of the captured node
local row1, col1, row2, col2 = node:range() -- range of the capture
-- ... use the info here ...
end
{node}
(TSNode
) under which the search will occur
{source}
(integer|string
) Source buffer or string to extract text
from
{start}
(integer?
) Starting line for the search. Defaults to
node:start()
.
{stop}
(integer?
) Stopping line for the search (end-exclusive).
Defaults to node:end_()
.
fun(end_line: integer?): integer, TSNode, vim.treesitter.query.TSMetadata, TSQueryMatch
)
capture id, capture node, metadata, matchQuery:iter_matches()
Query:iter_matches({node}
, {source}
, {start}
, {stop}
, {opts}
)
Iterates the matches of self on a given range.{node}
. The arguments are the same as
for Query:iter_captures() but the iterated values are different: an
(1-based) index of the pattern in the query, a table mapping capture
indices to a list of nodes, and metadata from any directives processing
the match.all=true
to ensure all matching nodes in a match are
returned, otherwise only the last node in a match is returned, breaking
captures involving quantifiers such as (comment)+ @comment
. The default
option all=false
is only provided for backward compatibility and will be
removed after Nvim 0.10.for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, 0, -1, { all = true }) do
for id, nodes in pairs(match) do
local name = query.captures[id]
for _, node in ipairs(nodes) do
-- `node` was captured by the `name` capture in the match
local node_data = metadata[id] -- Node level metadata
... use the info here ...
end
end
end
{node}
(TSNode
) under which the search will occur
{source}
(integer|string
) Source buffer or string to search
{start}
(integer?
) Starting line for the search. Defaults to
node:start()
.
{stop}
(integer?
) Stopping line for the search (end-exclusive).
Defaults to node:end_()
.
{opts}
(table?
) Optional keyword arguments:
fun(): integer, table<integer, TSNode[]>, table
) pattern id, match,
metadata{lang}
, {query_name}
, {text}
) vim.treesitter.query.set()
Sets the runtime query named {query_name}
for {lang}
{lang}
(string
) Language to use for the query
{query_name}
(string
) Name of the query (e.g., "highlights")
{text}
(string
) Query text (unparsed).
LanguageTree
contains a tree of parsers: the root treesitter parser for
{lang}
and any "injected" language parsers, which themselves may inject other
languages, recursively. For example a Lua buffer containing some Vimscript
commands needs multiple parsers to fully understand its contents.local parser = vim.treesitter.get_parser(bufnr, lang)
bufnr=0
means current buffer). lang
defaults to 'filetype'. Note:
currently the parser is retained for the lifetime of a buffer but this may
change; a plugin should keep a reference to the parser object if it wants
incremental updates.local tree = parser:parse({ start_row, end_row })
parse()
again. If the buffer wasn't edited, the
same tree will be returned again without extra work. If the buffer was parsed
before, incremental parsing will be done of the changed parts.LanguageTree:children()
Returns a map of language to child tree.{range}
) LanguageTree:contains()
Determines whether {range}
is contained in the LanguageTree.{range}
(Range4
) { start_line, start_col, end_line, end_col }
boolean
)LanguageTree:destroy()
Destroys this LanguageTree and all its children.remove_child
must be called on the parent to remove it.{fn}
) LanguageTree:for_each_tree()
Invokes the callback for each LanguageTree recursively.{fn}
(fun(tree: TSTree, ltree: vim.treesitter.LanguageTree)
)
LanguageTree:included_regions()
Gets the set of included regions managed by this LanguageTree. This can be
different from the regions set by injection query, because a partial
LanguageTree:parse() drops the regions outside the requested range.table<integer, Range6[]>
){reload}
) LanguageTree:invalidate()
Invalidates this parser and its children.{reload}
(boolean?
)
{exclude_children}
) LanguageTree:is_valid()
Returns whether this LanguageTree is valid, i.e., LanguageTree:trees()
reflects the latest state of the source. If invalid, user should call
LanguageTree:parse().{exclude_children}
(boolean?
) whether to ignore the validity of
children (default false
)
boolean
)LanguageTree:lang()
Gets the language of this tree node.LanguageTree:language_for_range()
LanguageTree:language_for_range({range}
)
Gets the appropriate language that contains {range}
.{range}
(Range4
) { start_line, start_col, end_line, end_col }
vim.treesitter.LanguageTree
) tree Managing {range}
LanguageTree:named_node_for_range()
LanguageTree:named_node_for_range({range}
, {opts}
)
Gets the smallest named node that contains {range}
.{range}
(Range4
) { start_line, start_col, end_line, end_col }
{opts}
(table?
) A table with the following fields:
{ignore_injections}
(boolean
, default: true
) Ignore
injected languages
TSNode?
){range}
) LanguageTree:parse()
Recursively parse all regions in the language tree using
treesitter-parsers for the corresponding languages and run injection
queries on the parsed trees to determine whether child trees should be
created and parsed.{}
, typically only the root tree) is always
parsed; otherwise (typically injections) only if it intersects {range}
(or
if {range}
is true
).{range}
(boolean|Range?
) Parse this range in the parser's source.
Set to true
to run a complete parse of the source (Note:
Can be slow!) Set to false|nil
to only parse regions with
empty ranges (typically only the root tree without
injections).
table<integer, TSTree>
)LanguageTree:register_cbs()
LanguageTree:register_cbs({cbs}
, {recursive}
)
Registers callbacks for the LanguageTree.{cbs}
(table<TSCallbackNameOn,function>
) An
nvim_buf_attach()-like table argument with the
following handlers:
on_bytes
: see nvim_buf_attach(), but this will be
called after the parsers callback.
on_changedtree
: a callback that will be called every
time the tree has syntactical changes. It will be
passed two arguments: a table of the ranges (as node
ranges) that changed and the changed tree.
on_child_added
: emitted when a child is added to the
tree.
on_child_removed
: emitted when a child is removed
from the tree.
on_detach
: emitted when the buffer is detached, see
nvim_buf_detach_event. Takes one argument, the number
of the buffer.
{recursive}
(boolean?
) Apply callbacks recursively for all
children. Any new children will also inherit the
callbacks.
LanguageTree:source()
Returns the source content of the language tree (bufnr or string).LanguageTree:tree_for_range()
LanguageTree:tree_for_range({range}
, {opts}
)
Gets the tree that contains {range}
.{range}
(Range4
) { start_line, start_col, end_line, end_col }
{opts}
(table?
) A table with the following fields:
{ignore_injections}
(boolean
, default: true
) Ignore
injected languages
TSTree?
)LanguageTree:trees()
Returns all trees of the regions parsed by this parser. Does not include
child languages. The result is list-like if
table<integer, TSTree>
)