Skip to content

Commit

Permalink
feat: treesitter node jumping
Browse files Browse the repository at this point in the history
  • Loading branch information
folke committed Jun 10, 2023
1 parent 864aa86 commit 119643f
Show file tree
Hide file tree
Showing 2 changed files with 78 additions and 0 deletions.
4 changes: 4 additions & 0 deletions lua/flash/state.lua
Original file line number Diff line number Diff line change
Expand Up @@ -146,6 +146,10 @@ function M:update(pattern)
if self.labels then
self.labeler:update()
end
self:highlight()
end

function M:highlight()
Highlight.update(self)
end

Expand Down
74 changes: 74 additions & 0 deletions lua/flash/treesitter.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,74 @@
local State = require("flash.state")

local M = {}

function M.get_nodes()
local ret = {} ---@type TSNode[]
local node = vim.treesitter.get_node()
while node do
local range = { node:range() }
if not vim.deep_equal(range, ret[#ret]) then
table.insert(ret, range)
end
node = node:parent()
end
return ret
end

M.state = nil
function M.jump()
local nodes = M.get_nodes()

if M.state then
M.state:clear()
M.state = nil
end

M.state = State.new({
config = {
labels = "abcdefghijklmnopqrstuvwxyz",
search = { multi_window = false },
jump = { auto_jump = false },
highlight = {
backdrop = true,
label = {
before = true,
after = true,
style = "inline",
},
matches = false,
},
},
})

for _, range in ipairs(nodes) do
table.insert(M.state.results, {
win = M.state.win,
from = { range[1] + 1, range[2] },
to = { range[3] + 1, range[4] - 1 },
visible = true,
next = "",
})
end

M.state.labeler:update()
M.state:highlight()
vim.cmd.redraw()
local ok, c = pcall(vim.fn.getchar)
local char = ok and type(c) == "number" and vim.fn.nr2char(c) or nil
if char then
if vim.fn.mode() == "v" then
vim.cmd("normal! v")
end
local match = M.state:jump(char)
if match then
vim.cmd("normal! v")
vim.api.nvim_win_set_cursor(M.state.win, match.to)
else
vim.api.nvim_input(char)
end
end
M.state:clear()
end

return M

0 comments on commit 119643f

Please sign in to comment.