From eeba980b8402a2f3aca96b440b1f3ba4c8d78b5a Mon Sep 17 00:00:00 2001 From: Price Hiller Date: Wed, 6 Sep 2023 23:42:28 -0500 Subject: [PATCH] feat(nvim): add keybinding to go to next/previous equal indent --- dots/.config/nvim/lua/core/mappings.lua | 44 +++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/dots/.config/nvim/lua/core/mappings.lua b/dots/.config/nvim/lua/core/mappings.lua index 09986490..e8be5f20 100755 --- a/dots/.config/nvim/lua/core/mappings.lua +++ b/dots/.config/nvim/lua/core/mappings.lua @@ -1,5 +1,46 @@ local M = {} +---Stolen with ❤️ from https://github.com/tj-moody/.dotfiles/blob/c2afec06b68cd0413c20d332672907c11f0a9c47/nvim/lua/mappings.lua#L171C1-L171C1 +---Adapted from https://vi.stackexchange.com/a/12870 +---Traverse to indent >= or > current indent +---@param direction integer 1 - forwards | -1 - backwards +---@param equal boolean include lines equal to current indent in search? +local function indent_traverse(direction, equal) -- {{{ + return function() + -- Get the current cursor position + local current_line, column = unpack(vim.api.nvim_win_get_cursor(0)) + local match_line = current_line + local match_indent = false + local match = false + + local buf_length = vim.api.nvim_buf_line_count(0) + + -- Look for a line of appropriate indent + -- level without going out of the buffer + while (not match) + and (match_line ~= buf_length) + and (match_line ~= 1) + do + match_line = match_line + direction + local match_line_str = vim.api.nvim_buf_get_lines(0, match_line - 1, match_line, false)[1] + -- local match_line_is_whitespace = match_line_str and match_line_str:match('^%s*$') + local match_line_is_whitespace = match_line_str:match('^%s*$') + + if equal then + match_indent = vim.fn.indent(match_line) <= vim.fn.indent(current_line) + else + match_indent = vim.fn.indent(match_line) < vim.fn.indent(current_line) + end + match = match_indent and not match_line_is_whitespace + end + + -- If a line is found go to line + if match or match_line == buf_length then + vim.fn.cursor({ match_line, column + 1 }) + end + end +end + M.setup = function() -- set mapleader to space vim.g.mapleader = " " @@ -76,6 +117,9 @@ M.setup = function() -- Binding to keep S-Space in terminals from not sending vim.keymap.set("t", "", "", { silent = true, desc = "Terminal: Hack S-Space to Space" }) + + vim.keymap.set("n", "", indent_traverse(1, true), { silent = true, desc = "Move: To next equal indent"}) + vim.keymap.set("n", "", indent_traverse(-1, true), { silent = true, desc = "Move: To previous equal indent"}) end return M