feat nvim: fold程式碼折疊功能(補上更多官方範例)

This commit is contained in:
Yuan Chiu 2025-05-08 16:37:29 +08:00
parent a09036b303
commit 3eee006f55
Signed by: yuan
GPG Key ID: 50FBE4156404B98D

View File

@ -1,3 +1,9 @@
local ftMap = {
vim = 'indent',
python = {'indent'},
git = ''
}
return { return {
{ {
'kevinhwang91/nvim-ufo', 'kevinhwang91/nvim-ufo',
@ -6,29 +12,32 @@ return {
}, },
event = "VeryLazy", event = "VeryLazy",
opts = { opts = {
open_fold_hl_timeout = 400, open_fold_hl_timeout = 150,
provider_selector = function(bufnr, filetype, buftype) close_fold_kinds_for_ft = {
return {'treesitter', 'indent'} default = {'imports', 'comment'},
end, json = {'array'},
close_fold_kinds_for_ft = { c = {'comment', 'region'}
default = {'imports', 'comment'}
},
fold_virt_text_handler = nil,
enable_get_fold_virt_text = false,
preview = {
win_config = {
border = 'rounded',
winblend = 12,
winhighlight = 'Normal:Normal',
maxheight = 20
}, },
mappings = { preview = {
-- 這裡你可以加上對應的快捷鍵,如: win_config = {
-- scrollB = '<C-b>', border = {'', '', '', '', '', '', '', ''},
-- scrollF = '<C-f>', winhighlight = 'Normal:Folded',
-- 或留空(等你有需要再補) winblend = 0
} },
} mappings = {
scrollU = '<C-u>',
scrollD = '<C-d>',
jumpTop = '[',
jumpBot = ']'
}
},
provider_selector = function(bufnr, filetype, buftype)
-- if you prefer treesitter provider rather than lsp,
-- return ftMap[filetype] or {'treesitter', 'indent'}
return ftMap[filetype]
-- refer to ./doc/example.lua for detail
end
}, },
init = function() init = function()
vim.o.foldcolumn = '1' -- '0' is not bad vim.o.foldcolumn = '1' -- '0' is not bad
@ -37,6 +46,35 @@ return {
vim.o.foldenable = true vim.o.foldenable = true
end, end,
config = function(_, opts) config = function(_, opts)
local handler = function(virtText, lnum, endLnum, width, truncate)
local newVirtText = {}
local suffix = (' 󰁂 %d '):format(endLnum - lnum)
local sufWidth = vim.fn.strdisplaywidth(suffix)
local targetWidth = width - sufWidth
local curWidth = 0
for _, chunk in ipairs(virtText) do
local chunkText = chunk[1]
local chunkWidth = vim.fn.strdisplaywidth(chunkText)
if targetWidth > curWidth + chunkWidth then
table.insert(newVirtText, chunk)
else
chunkText = truncate(chunkText, targetWidth - curWidth)
local hlGroup = chunk[2]
table.insert(newVirtText, {chunkText, hlGroup})
chunkWidth = vim.fn.strdisplaywidth(chunkText)
-- str width returned from truncate() may less than 2nd argument, need padding
if curWidth + chunkWidth < targetWidth then
suffix = suffix .. (' '):rep(targetWidth - curWidth - chunkWidth)
end
break
end
curWidth = curWidth + chunkWidth
end
table.insert(newVirtText, {suffix, 'MoreMsg'})
return newVirtText
end
opts["fold_virt_text_handler"] = handler
-- ufo官方範例 -- ufo官方範例
-- Using ufo provider need remap `zR` and `zM`. If Neovim is 0.6.1, remap yourself -- Using ufo provider need remap `zR` and `zM`. If Neovim is 0.6.1, remap yourself
vim.keymap.set('n', 'zR', require('ufo').openAllFolds) vim.keymap.set('n', 'zR', require('ufo').openAllFolds)