Skip to content

Instantly share code, notes, and snippets.

@jrop
Created April 9, 2026 01:19
Show Gist options
  • Select an option

  • Save jrop/4806b62d67e8f9d5a7073655cf40b27f to your computer and use it in GitHub Desktop.

Select an option

Save jrop/4806b62d67e8f9d5a7073655cf40b27f to your computer and use it in GitHub Desktop.
u.nvim bracket matcher
local Range = require 'u.Range'
local M = {}
local highlights = {}
local last_bracket_range = nil
local function clear_highlights()
for _, hl in ipairs(highlights) do
if hl and hl.clear then
hl:clear()
end
end
highlights = {}
end
local function update()
local mode = vim.fn.mode()
if mode ~= 'n' and mode ~= 'i' and mode ~= 'v' and mode ~= 'V' and mode ~= '\22' then
return
end
local bufnr = vim.api.nvim_get_current_buf()
local buftype = vim.bo[bufnr].buftype
if buftype ~= '' then
return
end
local bracket_range = Range.find_nearest_brackets()
if bracket_range and last_bracket_range
and bracket_range.start == last_bracket_range.start
and bracket_range.stop == last_bracket_range.stop then
return
end
clear_highlights()
last_bracket_range = bracket_range
if bracket_range == nil then return end
local opening = Range.new(bracket_range.start, bracket_range.start, 'v')
local closing = Range.new(bracket_range.stop, bracket_range.stop, 'v')
table.insert(highlights, opening:highlight('MatchParen', { priority = 999 }))
table.insert(highlights, closing:highlight('MatchParen', { priority = 999 }))
end
function M.setup()
local group = vim.api.nvim_create_augroup('Matcher', { clear = true })
vim.api.nvim_create_autocmd({ 'CursorMoved' }, {
group = group,
callback = update,
})
end
return M
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment