summaryrefslogtreecommitdiff
path: root/lua/config/treesitter.lua
blob: 249bd79bd1e37fd164ba8a52637c87717bdf8720 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
-- ~/.config/nvim/lua/config/treesitter.lua
return function()
	-- New nvim-treesitter (main branch) API for Neovim 0.12+
	-- The plugin now only handles parser installation and queries.
	-- Highlighting, folding, etc. are handled by Neovim core.

	require("nvim-treesitter").setup({
		-- Directory to install parsers and queries to
		install_dir = vim.fn.stdpath("data") .. "/site",
	})

	-- Install parsers (no-op if already installed)
	require("nvim-treesitter").install({
		"c",
		"lua",
		"vim",
		"vimdoc",
		"query",
		"markdown",
		"markdown_inline",
		"python",
		"javascript",
		"cpp",
		"rust",
		"haskell",
		"commonlisp",
		"scheme",
		"clojure",
		"fennel",
		"java",
		"fortran",
	})

	-- Enable treesitter highlighting for all filetypes with a parser
	-- (Neovim 0.12 already enables this for Markdown by default,
	--  but this covers all other languages too.)
	vim.api.nvim_create_autocmd("FileType", {
		callback = function()
			-- Skip latex as before
			if vim.bo.filetype == "latex" or vim.bo.filetype == "tex" then
				return
			end
			pcall(vim.treesitter.start)
		end,
	})

	-- Treesitter-based folding (Neovim 0.12 native)
	vim.opt.foldlevelstart = 99
	vim.api.nvim_create_autocmd("FileType", {
		callback = function()
			if pcall(vim.treesitter.get_parser) then
				vim.wo[0][0].foldmethod = "expr"
				vim.wo[0][0].foldexpr = "v:lua.vim.treesitter.foldexpr()"
			else
				vim.wo[0][0].foldmethod = "indent"
			end
		end,
	})

	-- Textobjects (nvim-treesitter-textobjects)
	require("nvim-treesitter-textobjects").setup({
		select = {
			lookahead = true,
		},
	})

	vim.keymap.set({ "x", "o" }, "af", function()
		require("nvim-treesitter-textobjects.select").select_textobject("@function.outer", "textobjects")
	end)
	vim.keymap.set({ "x", "o" }, "if", function()
		require("nvim-treesitter-textobjects.select").select_textobject("@function.inner", "textobjects")
	end)
	vim.keymap.set({ "x", "o" }, "ac", function()
		require("nvim-treesitter-textobjects.select").select_textobject("@class.outer", "textobjects")
	end)
	vim.keymap.set({ "x", "o" }, "ic", function()
		require("nvim-treesitter-textobjects.select").select_textobject("@class.inner", "textobjects")
	end)
end