From 8a2ed4198954909870f64005fc6444445166a766 Mon Sep 17 00:00:00 2001 From: Calvin Bochulak Date: Sun, 17 Mar 2024 14:28:31 -0600 Subject: [PATCH] refactor: don't save on Grapple.{select, cycle} + make cursor optional --- lua/grapple.lua | 4 ++-- lua/grapple/tag.lua | 24 ++++++++++++++++-------- 2 files changed, 18 insertions(+), 10 deletions(-) diff --git a/lua/grapple.lua b/lua/grapple.lua index a646657..6398f8a 100644 --- a/lua/grapple.lua +++ b/lua/grapple.lua @@ -137,7 +137,7 @@ function Grapple.select(opts) opts = opts or {} local app = App.get() - app:enter_with_save(opts.scope, function(container) + app:enter_without_save(opts.scope, function(container) local path, _ = extract_path(opts) opts.path = path @@ -223,7 +223,7 @@ function Grapple.cycle(direction, opts) opts = opts or {} local app = require("grapple.app").get() - app:enter_with_save(opts.scope, function(container) + app:enter_without_save(opts.scope, function(container) if container:is_empty() then return end diff --git a/lua/grapple/tag.lua b/lua/grapple/tag.lua index 5a35501..51a2055 100644 --- a/lua/grapple/tag.lua +++ b/lua/grapple/tag.lua @@ -3,7 +3,7 @@ local Path = require("grapple.path") ---@class grapple.tag ---@field path string absolute path ---@field name string | nil (optional) tag name ----@field cursor integer[] (1, 0)-indexed cursor position +---@field cursor integer[] | nil (optional) (1, 0)-indexed cursor position local Tag = {} Tag.__index = Tag @@ -14,7 +14,7 @@ function Tag:new(path, name, cursor) return setmetatable({ path = path, name = name, - cursor = cursor or { 1, 0 }, + cursor = cursor, }, self) end @@ -29,12 +29,20 @@ function Tag:select(command) command = command or vim.cmd.edit command(short_path) - -- If the cursor has already been set, update instead - local current_cursor = vim.api.nvim_win_get_cursor(0) - if current_cursor[1] > 1 or current_cursor[2] > 0 then - self.cursor = current_cursor - else - pcall(vim.api.nvim_win_set_cursor, 0, self.cursor) + if self.cursor then + local current_cursor = vim.api.nvim_win_get_cursor(0) + local last_line = vim.api.nvim_buf_line_count(0) + + -- Clamp the cursor to the last line + local cursor = { + math.min(self.cursor[1], last_line), + self.cursor[2], + } + + -- If the cursor has already been set, don't set again + if current_cursor[1] == 1 or current_cursor[2] == 0 then + pcall(vim.api.nvim_win_set_cursor, 0, cursor) + end end end