From 6f04f459eb7f8413ac55207c86070084c171e0aa Mon Sep 17 00:00:00 2001 From: Ben Lubas Date: Sun, 28 Jul 2024 11:54:07 -0400 Subject: [PATCH] docs: add example hook usages to README --- README.md | 83 +++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 83 insertions(+) diff --git a/README.md b/README.md index 348d22c..41d1335 100644 --- a/README.md +++ b/README.md @@ -103,6 +103,89 @@ hunk.setup({ }) ``` +### Using Hooks + +Hooks can be used to bind keys with "complex" logic, or to set buffer/window local options on the +three or diff splits. + +
+ Skipping Folders in the File Tree + +These bindings allow `j`/`k` to skip over folders in the file tree (b/c they're generally not +relevant). You can still access folders with `gj`/`gk`. + +```lua +-- track all the lines of leaf nodes so we don't have to recompute them on each key press +local jumpable_lines +local function set_jumpabe_lines(context) + jumpable_lines = {} + local i = 1 + local n, _, _ = context.tree:get_node(i) + while n do + if not n:has_children() then + table.insert(jumpable_lines, i) + end + i = i + 1 + n, _, _ = context.tree:get_node(i) + end +end +require("hunk").setup({ + hooks = { + on_tree_mount = function(context) + vim.keymap.set("n", "j", function() + -- unfortunately we have to recompute every time because folding ruins these computed values + set_jumpabe_lines(context) + local row = vim.api.nvim_win_get_cursor(0)[1] + if row < jumpable_lines[1] then + vim.api.nvim_win_set_cursor(0, { jumpable_lines[1], 0 }) + return + end + for idx = #jumpable_lines, 1, -1 do + if jumpable_lines[idx] <= row then + if jumpable_lines[idx + 1] then + vim.api.nvim_win_set_cursor(0, { jumpable_lines[idx + 1], 0 }) + end + return + end + end + end, { buffer = context.buf }) + + vim.keymap.set("n", "k", function() + set_jumpabe_lines(context) + local row = vim.api.nvim_win_get_cursor(0)[1] + if row > jumpable_lines[#jumpable_lines] then + vim.api.nvim_win_set_cursor(0, { jumpable_lines[#jumpable_lines], 0 }) + return + end + for idx, node_row in ipairs(jumpable_lines) do + if node_row >= row then + if jumpable_lines[idx - 1] then + vim.api.nvim_win_set_cursor(0, { jumpable_lines[idx - 1], 0 }) + end + return + end + end + end, { buffer = context.buf }) + end, + }, +}) +``` +
+ +
+ Set `nospell` in File Tree + +```lua +require("hunk").setup({ + hooks = { + on_tree_mount = function(context) + vim.api.nvim_set_option_value("spell", false, { win = context.win }) + end, + } +}) +``` +
+ ## Using with Jujutsu [Jujutsu](https://github.com/martinvonz/jj) is an alternative VCS that has a focus on working with individual commits