If you use a toggleable terminal like toggleterm.nvim, you can configure flatten.nvim to open new buffers in your last active window instead of the current terminal window by setting window.open to "alternate".
To handle blocking modes (like git commits) gracefully, you can use hooks to hide and reopen the terminal. This prevents the terminal from being inaccessible or cluttered during blocking operations.
Key hooks used in this integration:
hooks.should_block: Determines if a command should trigger blocking mode (e.g., checking for the -b flag in argv).hooks.pre_open: Used to capture the current terminal instance before a file opens.hooks.post_open: Used to hide the terminal if the file is blocking, or switch windows if it is not.hooks.block_end: Used to reopen the terminal once the blocking operation completes.
local flatten = {
"willothy/flatten.nvim",
opts = function()
---@type Terminal?
local saved_terminal
return {
window = {
open = "alternate",
},
hooks = {
should_block = function(argv)
return vim.tbl_contains(argv, "-b")
end,
pre_open = function()
local term = require("toggleterm.terminal")
local termid = term.get_focused_id()
saved_terminal = term.get(termid)
end,
post_open = function(bufnr, winnr, ft, is_blocking)
if is_blocking and saved_terminal then
saved_terminal:close()
else
vim.api.nvim_set_current_win(winnr)
end
if ft == "gitcommit" or ft == "gitrebase" then
vim.api.nvim_create_autocmd("BufWritePost", {
buffer = bufnr,
once = true,
callback = vim.schedule_wrap(function()
vim.api.nvim_buf_delete(bufnr, {})
end),
})
end
end,
block_end = function()
vim.schedule(function()
if saved_terminal then
saved_terminal:open()
saved_terminal = nil
end
end)
end,
},
}
end,
}