Treesitter
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 FILES
parser
runtime directory. By default, Nvim bundles only
parsers for C, Lua, and Vimscript, but parsers can be installed manually or
via a plugin like https://github.com/nvim-treesitter/nvim-treesitter.
Parsers are searched for as parser/{lang}.*
in any 'runtimepath' directory.
If multiple parsers for the same language are found, the first one is used.
(This typically implies the priority "user config > plugins > bundled".
A parser can also be loaded manually using a full path:vim.treesitter.require_language("python", "/path/to/python.so")
tsparser = vim.treesitter.get_parser(bufnr, lang)
bufnr=0
can be used for current buffer. lang
will default to 'filetype'.
Currently, the parser will be retained for the lifetime of a buffer but this
is subject to change. A plugin should keep a reference to the parser object as
long as it wants incremental updates.tstree = tsparser:parse()
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.tstree
of a treesitter tree supports the following methods.tsnode
of a treesitter node supports the following methods.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()
Get the node's child at the given {index}
, where zero represents the first
child.tsnode:named_child()
Get the node's named child at the given {index}
, where zero represents the
first named child.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).tsnode:range()
Get the range of the node. Return four values: the row, column of the
start position, then the row, column of the end position.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:has_error()
Check if the node is a syntax error or contains any syntax errors.id
is not guaranteed to be unique for nodes from different
trees.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) positionsTREESITTER QUERIES
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 Neovim). If a query should extend other queries instead
of replacing them, use treesitter-query-modeline-extends.TREESITTER QUERY PREDICATES
eq?
predicate can be used as follows:((identifier) @foo (#eq? @foo "foo"))
"foo"
text.eq?
treesitter-predicate-eq?
Match a string against the text corresponding to a node:((identifier) @foo (#eq? @foo "foo")) ((node1) @left (node2) @right (#eq? @left @right))
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.lua-match?
treesitter-predicate-lua-match?
Match lua-patterns against the text corresponding to a node,
similar to 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-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"))
lua-treesitter-not-predicate
Each predicate has a not-
prefixed predicate that is just the negation of
the predicate.vim.treesitter.query.
add_predicate().
Use vim.treesitter.query.
list_predicates() to list all available
predicates.TREESITTER QUERY DIRECTIVES
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"))
offset!
treesitter-directive-offset!
Takes the range of the captured node and applies an offset. This will
generate a new range object for the captured node as
metadata[capture_id].range
.{capture_id}
{start_row}
{start_col}
{end_row}
{end_col}
((identifier) @constant (#offset! @constant 0 1 0 -1))
vim.treesitter.query.
add_directive().
Use vim.treesitter.query.
list_directives() to list all available
directives.TREESITTER QUERY MODELINES
;
. 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: foo,bar ;; extends;; extends ;; ;; inherits: baz
TREESITTER SYNTAX HIGHLIGHTING
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) @parameter)
identifier
node inside a function parameter
node (e.g., the
bar
in foo(bar)
) to the capture named @parameter
. It is also possible to
match literal expressions (provided the parser returns them):"return" @keyword.return
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, with @
included, 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 but can be overridden in
colorschemes.@comment.doc
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.doc.java String
@text.literal Comment @text.reference Identifier @text.title Title @text.uri Underlined @text.underline Underlined @text.todo Todo@comment Comment @punctuation Delimiter
@constant Constant @constant.builtin Special @constant.macro Define @define Define @macro Macro @string String @string.escape SpecialChar @string.special SpecialChar @character Character @character.special SpecialChar @number Number @boolean Boolean @float Float
@function Function @function.builtin Special @function.macro Macro @parameter Identifier @method Function @field Identifier @property Identifier @constructor Special
@conditional Conditional @repeat Repeat @label Label @operator Operator @keyword Keyword @exception Exception
@variable Identifier @type Type @type.definition Typedef @storageclass StorageClass @structure Structure @namespace Identifier @include Include @preproc PreProc @debug Debug @tag Tag
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 tree-sitter. It is also possible to change the priority of an
individual query pattern manually by setting its "priority"
metadata
attribute:(super_important_node) @ImportantHighlight (#set! "priority" 105)
VIM.TREESITTER
vim.treesitter
Lua module, which is the main interface for Nvim's tree-sitter 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 tree-sitter
library.vim.treesitter.minimum_language_version
The earliest parser ABI version that is supported by the bundled tree-sitter
library.Lua module: vim.treesitter
{winnr}
) get_captures_at_cursor()
Returns a list of highlight capture names under the cursor{winnr}
(number|nil) Window handle or 0 for current window (default)
{bufnr}
, {row}
, {col}
) get_captures_at_pos()
Returns a list of highlight captures at the given positionpriority
, conceal
, ...; empty
if none are defined).{bufnr}
(number) Buffer number (0 for current buffer)
{row}
(number) Position row
{col}
(number) Position column
{winnr}
) get_node_at_cursor()
Returns the smallest named node under the cursor{winnr}
(number|nil) Window handle or 0 for current window (default)
{bufnr}
, {row}
, {col}
, {opts}
) get_node_at_pos()
Returns the smallest named node at the given position{bufnr}
(number) Buffer number (0 for current buffer)
{row}
(number) Position row
{col}
(number) Position column
{opts}
(table) Optional keyword arguments:
{node_or_range}
) get_node_range()
Returns the node's range or an unpacked range table{node_or_range}
(userdata|table) tsnode or table of positions
{ start_row, start_col, end_row, end_col }
{bufnr}
, {lang}
, {opts}
) get_parser()
Returns the parser for a specific buffer and filetype and attaches it to
the buffer{bufnr}
(number|nil) Buffer the parser should be tied to (default:
current buffer)
{lang}
(string|nil) Filetype of this parser (default: buffer
filetype)
{opts}
(table|nil) Options to pass to the created language tree
{str}
(string) Text to parse
{lang}
(string) Language of this string
{opts}
(table|nil) Options to pass to the created language tree
{dest}
is an ancestor of {source}
{node}
, {line}
, {col}
) is_in_node_range()
Determines whether (line, col) position is in node range{node}
userdata tsnode defining the range
{line}
(number) Line (0-based)
{col}
(number) Column (0-based)
{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}
(number|nil) Buffer to be highlighted (default: current
buffer)
{lang}
(string|nil) Language of the parser (default: buffer
filetype)
{bufnr}
(number|nil) Buffer to stop highlighting (default: current
buffer)
Lua module: vim.treesitter.language
{lang}
(string) Language
require_language()
require_language({lang}
, {path}
, {silent}
, {symbol_name}
)
Asserts that a parser for the language {lang}
is installed.parser
runtime directory, or the provided
{path}
{lang}
(string) Language the parser should parse
{path}
(string|nil) Optional path the parser is located at
{silent}
(boolean|nil) Don't throw an error if language not
found
{symbol_name}
(string|nil) Internal symbol name for the language to
load
Lua module: vim.treesitter.query
{name}
, {handler}
, {force}
) add_directive()
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}
function(match:string, pattern:string, bufnr:number,
predicate:function, metadata:table)
{name}
, {handler}
, {force}
) add_predicate()
Adds a new predicate to be used in queries{name}
(string) Name of the predicate, without leading #
{handler}
function(match:string, pattern:string, bufnr:number,
predicate:function)
{node}
userdata tsnode
{source}
(number|string) Buffer or string from which the {node}
is
extracted
{opts}
(table|nil) Optional parameters.
{lang}
(string) Language to use for the query
{query_name}
(string) Name of the query (e.g. "highlights")
get_query_files()
get_query_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|nil) Internal parameter, most of the time left
as nil
{lang}
, {query}
) parse_query()
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 iter_*
methods below.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
Query:iter_captures()
Query:iter_captures({self}, {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_row}
and {end_row}
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 {end}
row values are used from the given
node.for id, node, metadata 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}
userdata tsnode under which the search will occur
{source}
(number|string) Source buffer or string to extract text from
{start}
(number) Starting line for the search
{stop}
(number) Stopping line for the search (end-exclusive)
{self}
{node}
(table) metadata for the {capture}
Query:iter_matches()
Query:iter_matches({self}, {node}
, {source}
, {start}
, {stop}
)
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 nodes, and metadata from any directives processing the match.
If the query has more than one pattern, the capture table might be sparse
and e.g. pairs()
method should be used over ipairs
. Here is an example iterating over all captures in every match:for pattern, match, metadata in cquery:iter_matches(tree:root(), bufnr, first, last) do for id, node in pairs(match) do local name = query.captures[id] -- `node` was captured by the `name` capture in the matchlocal node_data = metadata[id] -- Node level metadata ... use the info here ...
end end
{node}
userdata tsnode under which the search will occur
{source}
(number|string) Source buffer or string to search
{start}
(number) Starting line for the search
{stop}
(number) Stopping line for the search (end-exclusive)
{self}
{lang}
, {query_name}
, {text}
) set_query()
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).
Lua module: vim.treesitter.highlighter
{tree}
LanguageTree LanguageTree parser object to use for highlighting
{opts}
(table|nil) Configuration of the highlighter:
TSHighlighter:destroy()
Removes all internal references to the highlighter{self}
Lua module: vim.treesitter.languagetree
{self}
{range}
) LanguageTree:contains()
Determines whether {range}
is contained in the LanguageTree.{range}
(table) { start_line, start_col, end_line, end_col }
{self}
LanguageTree:destroy()
Destroys this LanguageTree and all its children.remove_child
must be called on the parent to remove it.{self}
LanguageTree:for_each_child()
LanguageTree:for_each_child({self}, {fn}
, {include_self}
)
Invokes the callback for each LanguageTree and its children recursively{fn}
function(tree: LanguageTree, lang: string)
{include_self}
(boolean) Whether to include the invoking tree in the
results
{self}
{fn}
) LanguageTree:for_each_tree()
Invokes the callback for each LanguageTree recursively.{fn}
function(tree: TSTree, languageTree: LanguageTree)
{self}
LanguageTree:included_regions()
Gets the set of included regions{self}
{reload}
) LanguageTree:invalidate()
Invalidates this parser and all its children{self}
LanguageTree:is_valid()
Determines whether this tree is valid. If the tree is invalid, call parse()
. This will return the updated tree.{self}
{self}
LanguageTree:language_for_range()
LanguageTree:language_for_range({self}, {range}
)
Gets the appropriate language that contains {range}
.{range}
(table) { start_line, start_col, end_line, end_col }
{self}
{range}
LanguageTree:named_node_for_range()
LanguageTree:named_node_for_range({self}, {range}
, {opts}
)
Gets the smallest named node that contains {range}
.{range}
(table) { start_line, start_col, end_line, end_col }
{opts}
(table|nil) Optional keyword arguments:
{self}
LanguageTree:parse()
Parses all defined regions using a treesitter parser for the language this
tree represents. This will run the injection query for this language to
determine if any child languages should be created.{self}
{cbs}
) LanguageTree:register_cbs()
Registers callbacks for the LanguageTree.{cbs}
(table) 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 only be passed one
argument, which is a table of the ranges (as node ranges)
that changed.
on_child_added
: emitted when a child is added to the
tree.
on_child_removed
: emitted when a child is removed from
the tree.
{self}
LanguageTree:source()
Returns the source content of the language tree (bufnr or string).{self}
LanguageTree:tree_for_range()
LanguageTree:tree_for_range({self}, {range}
, {opts}
)
Gets the tree that contains {range}
.{range}
(table) { start_line, start_col, end_line, end_col }
{opts}
(table|nil) Optional keyword arguments:
{self}
LanguageTree:trees()
Returns all trees this language tree contains. Does not include child
languages.{self}
{source}
, {lang}
, {opts}
) languagetree.new()
A LanguageTree holds the treesitter parser for a given language {lang}
used to parse a buffer. As the buffer may contain injected languages, the LanguageTree needs to store parsers for these child languages as well (which in turn
may contain child languages themselves, hence the name).{source}
(number|string) Buffer or a string of text to parse
{lang}
(string) Root language this tree represents
{opts}
(table|nil) Optional keyword arguments: