From f6314c6bde0cc5b0250b4bc7b05e20942e11878d Mon Sep 17 00:00:00 2001 From: David Marchante Date: Mon, 2 Dec 2024 13:47:15 -0500 Subject: [PATCH] fix: set alternate when using floating windows (#285) --- lua/oil/init.lua | 19 +++++++++++++++++++ tests/altbuf_spec.lua | 12 ++++++++++++ 2 files changed, 31 insertions(+) diff --git a/lua/oil/init.lua b/lua/oil/init.lua index 72d5538a..e43dbf2e 100644 --- a/lua/oil/init.lua +++ b/lua/oil/init.lua @@ -617,6 +617,25 @@ M.select = function(opts, callback) if callback then callback(err) end + + -- Set alternate for buffer + local has_orig, orig_buffer = pcall(vim.api.nvim_win_get_var, 0, "oil_original_buffer") + + if has_orig and vim.api.nvim_buf_is_valid(orig_buffer) then + if vim.api.nvim_get_current_buf() ~= orig_buffer then + -- If we are editing a new file after navigating around oil, set the alternate buffer + -- to be the last buffer we were in before opening oil + vim.fn.setreg("#", orig_buffer) + else + -- If we are editing the same buffer that we started oil from, set the alternate to be + -- what it was before we opened oil + local has_orig_alt, alt_buffer = + pcall(vim.api.nvim_win_get_var, 0, "oil_original_alternate") + if has_orig_alt and vim.api.nvim_buf_is_valid(alt_buffer) then + vim.fn.setreg("#", alt_buffer) + end + end + end end if not opts.split and (opts.horizontal or opts.vertical) then if opts.horizontal then diff --git a/tests/altbuf_spec.lua b/tests/altbuf_spec.lua index 4b516045..c7d3b582 100644 --- a/tests/altbuf_spec.lua +++ b/tests/altbuf_spec.lua @@ -141,5 +141,17 @@ a.describe("Alternate buffer", function() oil.close() assert.equals("foo", vim.fn.expand("#")) end) + + a.it("preserves alternate when traversing to a new file", function() + vim.cmd.edit({ args = { "foo" } }) + oil.open_float() + test_util.wait_for_autocmd({ "User", pattern = "OilEnter" }) + assert.equals("foo", vim.fn.expand("#")) + local last_item = vim.fn.line("$") + vim.api.nvim_win_set_cursor(0, { last_item, 5 }) + oil.select() + test_util.wait_for_autocmd("BufEnter") + assert.equals("foo", vim.fn.expand("#")) + end) end) end)