diff --git a/README.md b/README.md index e7e29ecd..4f876f56 100644 --- a/README.md +++ b/README.md @@ -373,6 +373,7 @@ require'treesitter-context'.setup{ separator = nil, zindex = 20, -- The Z-index of the context window on_attach = nil, -- (fun(buf: integer): boolean) return false to disable attaching + hide_lines = nil, -- Lines matching the regex will not be displayed. Example for hiding single '{': "^%s*{%s*$" } ``` diff --git a/lua/treesitter-context/config.lua b/lua/treesitter-context/config.lua index 3b8f79b2..f9afeea8 100644 --- a/lua/treesitter-context/config.lua +++ b/lua/treesitter-context/config.lua @@ -10,6 +10,7 @@ --- @field mode 'cursor'|'topline' --- @field separator? string --- @field on_attach? fun(buf: integer): boolean +--- @field hide_lines? string --- @class (exact) TSContext.UserConfig : TSContext.Config --- @@ -45,6 +46,10 @@ --- --- Callback when attaching. Return false to disable attaching --- @field on_attach? fun(buf: integer): boolean +--- +--- Regular expression for hiding undesired lines in the context window, like single '{'. +--- Lines that match regex will be hidden. +--- @field hide_lines? string --- @type TSContext.Config local default_config = { @@ -57,6 +62,7 @@ local default_config = { trim_scope = 'outer', zindex = 20, mode = 'cursor', + hide_lines = nil, } local config = vim.deepcopy(default_config) diff --git a/lua/treesitter-context/context.lua b/lua/treesitter-context/context.lua index 6f12e82b..74cdfbbe 100644 --- a/lua/treesitter-context/context.lua +++ b/lua/treesitter-context/context.lua @@ -224,6 +224,28 @@ local function get_text_for_range(range, bufnr) return { start_row, 0, end_row, end_col }, lines end +--- In-place drop lines that match `config.hide_lines`. +--- @param range Range4 +--- @param lines string[] +local function line_filter(range, lines) + local regex = config.hide_lines + if regex == nil then + return + end + local no_dropped = 0 + for i, line in ipairs(lines) do + if line:match(regex) then + no_dropped = no_dropped + 1 + else + lines[i - no_dropped] = lines[i] + end + end + for i = 1, no_dropped do + lines[#lines] = nil + end + range[3] = range[3] - no_dropped +end + local M = {} --- @param bufnr integer @@ -377,6 +399,7 @@ function M.get(winid) local range0 = context_range(parent, bufnr, query) if range0 and range_is_valid(range0) then local range, lines = get_text_for_range(range0, bufnr) + line_filter(range, lines) if range_is_valid(range) then local last_context = context_ranges[#context_ranges] if last_context and parent_start_row == last_context[1] then