Xinqi Bao's Git

feat(nvim): retain boundaries of Tree-sitter folds
authorXinqi Bao <[email protected]>
Mon, 5 Oct 2026 12:45:10 +0000 (20:45 +0800)
committerXinqi Bao <[email protected]>
Mon, 5 Oct 2026 12:45:10 +0000 (20:45 +0800)
Trim native folds by one line at both ends, preserving visible code and its syntax highlighting. Keep short interiors visible through the default foldminlines setting.

Use a zero fold expression until a parser starts successfully, including after changing to an unsupported filetype.

.config/nvim/init.vim
.config/nvim/lua/plugin-config/nvim-treesitter.lua

index e002a88..4b7fb6c 100644 (file)
@@ -33,8 +33,9 @@ set noshowmode
 set wildmenu
 set colorcolumn=120
 highlight ColorColumn ctermbg=0 guibg=lightgrey
 set wildmenu
 set colorcolumn=120
 highlight ColorColumn ctermbg=0 guibg=lightgrey
-" Fallback for filetypes without a Tree-sitter parser.
-set foldmethod=indent
+" Create folds only after a Tree-sitter parser is started.
+set foldmethod=expr
+set foldexpr=0
 set foldlevelstart=99
 set foldlevel=99
 
 set foldlevelstart=99
 set foldlevel=99
 
index 4d17d51..bbe2824 100644 (file)
@@ -21,12 +21,30 @@ treesitter.install {
   'yaml',
 }
 
   'yaml',
 }
 
+local function foldlevel(lnum, exclude_start)
+  if lnum < 1 or lnum > vim.api.nvim_buf_line_count(0) then
+    return 0
+  end
+  local value = vim.treesitter.foldexpr(lnum)
+  local level = tonumber(value:match('%d+')) or 0
+  -- A '>N' starts a new fold even when adjacent folds have the same level.
+  return math.max(0, level - (exclude_start and value:sub(1, 1) == '>' and 1 or 0))
+end
+
+function _G.DotfilesFoldExpr()
+  local line = vim.v.lnum
+  -- Keep only levels spanning the previous, current, and next lines.
+  -- Default foldminlines keeps interiors of fewer than two lines visible.
+  return math.min(foldlevel(line - 1), foldlevel(line, true), foldlevel(line + 1, true))
+end
+
 local function enable(buf)
 local function enable(buf)
+  vim.wo[0][0].foldexpr = '0'
   if not pcall(vim.treesitter.start, buf) then
     return
   end
 
   if not pcall(vim.treesitter.start, buf) then
     return
   end
 
-  vim.wo[0][0].foldexpr = 'v:lua.vim.treesitter.foldexpr()'
+  vim.wo[0][0].foldexpr = 'v:lua.DotfilesFoldExpr()'
   vim.wo[0][0].foldmethod = 'expr'
 end
 
   vim.wo[0][0].foldmethod = 'expr'
 end