From 07af8f3d9f50ddadda014a2af1573a4afc588fa8 Mon Sep 17 00:00:00 2001 From: markoplk Date: Thu, 12 Feb 2026 20:05:19 +0100 Subject: [PATCH] fix(return): properly return from .norg buffers to alternate buffer Improve the behavior of the `return` command when exiting `.norg` buffers. - Close all open .norg buffers when triggering the return command - Switch to the alternate buffer if valid and not a .norg - Fallback to the last open buffer if alternate is unavailable - Fallback to :enew if no suitable buffer exists - Ensure all buffer operations are safe by checking buffer validity --- .../core/neorgcmd/commands/return/module.lua | 32 ++++++++++++++++--- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/lua/neorg/modules/core/neorgcmd/commands/return/module.lua b/lua/neorg/modules/core/neorgcmd/commands/return/module.lua index 7e340a8b9..8df2ac9be 100644 --- a/lua/neorg/modules/core/neorgcmd/commands/return/module.lua +++ b/lua/neorg/modules/core/neorgcmd/commands/return/module.lua @@ -30,20 +30,42 @@ module.on_event = function(event) if event.type == "core.neorgcmd.events.return" then -- Get all the buffers local buffers = vim.api.nvim_list_bufs() + local last_non_norg = nil local to_delete = {} for buffer in vim.iter(buffers):rev() do - if vim.fn.buflisted(buffer) == 1 then + if vim.fn.buflisted(buffer) == 1 and vim.api.nvim_buf_is_valid(buffer) then -- If the listed buffer we're working with has a .norg extension then remove it (not forcibly) - if not vim.endswith(vim.api.nvim_buf_get_name(buffer), ".norg") then - vim.api.nvim_win_set_buf(0, buffer) - break - else + if vim.endswith(vim.api.nvim_buf_get_name(buffer), ".norg") then table.insert(to_delete, buffer) + elseif not last_non_norg then + last_non_norg = buffer end end end + -- Determine a safe fallback buffer (alternate or last non-norg) + local target = nil + local alt = vim.fn.bufnr("#") + + if + alt ~= -1 + and vim.api.nvim_buf_is_valid(alt) + and vim.fn.buflisted(alt) == 1 + and not vim.endswith(vim.api.nvim_buf_get_name(alt), ".norg") + then + target = alt + else + target = last_non_norg + end + + if target then + vim.api.nvim_set_current_buf(target) + else + local new_buf = vim.api.nvim_create_buf(true, false) + vim.api.nvim_set_current_buf(new_buf) + end + for _, buffer in ipairs(to_delete) do vim.api.nvim_buf_delete(buffer, {}) end