Treesitter from Scratch — Syntax Highlighting, Text Objects & Code Folding | Episode 8
Video: Treesitter from Scratch — Syntax Highlighting, Text Objects & Code Folding | Episode 8 by Taught by Celeste AI - AI Coding Coach
Watch full page →Treesitter from Scratch — Syntax Highlighting, Text Objects & Code Folding
Enhance your Neovim setup by integrating nvim-treesitter for powerful AST-based syntax highlighting, smarter code navigation, and code folding. This guide walks you through installing Treesitter with multiple language parsers, configuring incremental selection, text objects, and folding commands to improve your editing workflow.
Code
-- Install nvim-treesitter with desired language parsers and build command
require('nvim-treesitter.configs').setup {
ensure_installed = { "lua", "python", "kotlin", "tsx", "javascript", "html", "css" }, -- parsers to install
sync_install = false,
auto_install = true,
highlight = {
enable = true, -- enable AST-powered syntax highlighting
additional_vim_regex_highlighting = false,
},
indent = {
enable = true, -- enable Treesitter-based indentation
},
incremental_selection = {
enable = true,
keymaps = {
init_selection = "gnn", -- start selection at cursor
node_incremental = "",-- expand selection to next AST node
node_decremental = "",-- shrink selection
},
},
textobjects = {
select = {
enable = true,
lookahead = true, -- jump forward to textobj
keymaps = {
["af"] = "@function.outer", -- around function
["if"] = "@function.inner", -- inside function
["ac"] = "@class.outer", -- around class
["ic"] = "@class.inner", -- inside class
["aa"] = "@parameter.outer", -- around parameter
["ia"] = "@parameter.inner", -- inside parameter
},
},
move = {
enable = true,
set_jumps = true, -- set jumplist for motions
goto_next_start = {
["]m"] = "@function.outer", -- next function start
},
goto_previous_start = {
["[m"] = "@function.outer", -- previous function start
},
},
},
}
-- Set folding method to Treesitter expression
vim.wo.foldmethod = "expr"
vim.wo.foldexpr = "nvim_treesitter#foldexpr()"
-- Keymaps for folding
-- zM: close all folds, zR: open all folds
-- zc: close fold under cursor, zo: open fold under cursor, za: toggle fold
Key Points
- nvim-treesitter replaces regex with AST parsing for accurate syntax highlighting and indentation.
- Use ensure_installed with a list of languages to automatically download and compile parsers via :TSUpdate.
- Incremental selection lets you expand or shrink your selection based on AST nodes using customizable keymaps.
- Text objects enable selecting, moving, and swapping code structures like functions, classes, and parameters efficiently.
- Treesitter-based folding uses foldexpr for syntax-aware code folding, controlled with familiar zM/zR/zc/zo/za commands.