Skip to content

Commit

Permalink
feat: use matchpairs for bracket matching
Browse files Browse the repository at this point in the history
* Dynamically load bracket pairs from vim.o.matchpairs instead of hardcoding
* Fix comment matching position to align with vim behavior
* Add cpoptions=M for proper bracket matching in tests
  • Loading branch information
tris203 committed Dec 19, 2024
1 parent 8422638 commit 735d172
Show file tree
Hide file tree
Showing 3 changed files with 23 additions and 6 deletions.
21 changes: 17 additions & 4 deletions lua/precognition/horizontal_motions.lua
Original file line number Diff line number Diff line change
@@ -1,11 +1,24 @@
local M = {}

local pairs = vim.split(vim.o.matchpairs, ",")

-- local match_bracket_escape = not vim.o.cpoptions:find("M")

local supportedBrackets = {
open = { "(", "[", "{" },
middle = { nil, nil, nil },
close = { ")", "]", "}" },
open = {},
middle = {},
close = {},
}

for _, pair in ipairs(pairs) do
local open, close = pair:match("(.):(.)")
if open and close then
table.insert(supportedBrackets.open, open)
table.insert(supportedBrackets.middle, nil)
table.insert(supportedBrackets.close, close)
end
end

---@param str string
---@param _cursorcol integer
---@param _linelen integer
Expand Down Expand Up @@ -264,7 +277,7 @@ function M.matching_comment(str, cursorcol, linelen)
next_char = vim.fn.strcharpart(str, offset, 1)
if char == "*" and next_char == "/" then
-- return the slash of the closing comment
return offset + 1
return offset
end
offset = offset + 1
end
Expand Down
4 changes: 4 additions & 0 deletions tests/precognition/dts.lua
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,10 @@ local M = {}
function M.test(seed)
local data = dts.generate_random_line(seed)

--TODO: Currently bracket matching only works with M cpoptions
--see `:h %`
vim.o.cpoptions = vim.o.cpoptions .. "M"

local cur_line = data.line
local cursorcol = data.cursor_col
local line_len = vim.fn.strcharlen(cur_line)
Expand Down
4 changes: 2 additions & 2 deletions tests/precognition/horizontal_motions_spec.lua
Original file line number Diff line number Diff line change
Expand Up @@ -254,8 +254,8 @@ end)
describe("matching comments", function()
it("if cursor is over a comment it can find the pair", function()
local str = "abc /*efg*/"
eq(11, hm.matching_comment(str, 5, #str))
eq(11, hm.matching_comment(str, 6, #str))
eq(10, hm.matching_comment(str, 5, #str))
eq(10, hm.matching_comment(str, 6, #str))
eq(0, hm.matching_comment(str, 7, #str))
eq(5, hm.matching_comment(str, 10, #str))
eq(5, hm.matching_comment(str, 11, #str))
Expand Down

0 comments on commit 735d172

Please sign in to comment.