fix(terminal): make sure terminals opend with open() can be found with list(). Closes #2172. Closes #2173

This commit is contained in:
Folke Lemaitre 2025-10-19 10:52:52 +02:00
parent baedaf4ac5
commit 13f3006dbf
No known key found for this signature in database
GPG key ID: 9B52594D560070AB

View file

@ -67,7 +67,9 @@ Snacks.config.style("terminal", {
})
---@type table<string, snacks.win>
local terminals = {}
local terminals = setmetatable({}, {
__mode = "v",
})
local function jobstart(cmd, opts)
opts = opts or {}
@ -123,6 +125,8 @@ function M.open(cmd, opts)
end
local terminal = Snacks.win(opts.win)
local tid = M.tid(cmd, opts)
terminals[tid] = terminal
if auto_insert then
terminal:on("BufEnter", function()
@ -146,6 +150,7 @@ function M.open(cmd, opts)
end)
terminal:on("BufWipeout", function()
terminals[tid] = nil
vim.schedule(function()
terminal:close()
end)
@ -164,6 +169,19 @@ function M.open(cmd, opts)
return terminal
end
--- Get a terminal id based on the `cmd`, `cwd`, `env` and `vim.v.count1` options.
---@param cmd? string | string[]
---@param opts? snacks.terminal.Opts
function M.tid(cmd, opts)
opts = opts or {}
return vim.inspect({
cmd = type(cmd) == "table" and cmd or { cmd },
cwd = opts.cwd or vim.fn.getcwd(0),
env = opts.env,
count = opts.count or vim.v.count1,
})
end
--- Get or create a terminal window.
--- The terminal id is based on the `cmd`, `cwd`, `env` and `vim.v.count1` options.
--- `opts.create` defaults to `true`.
@ -172,14 +190,14 @@ end
---@return snacks.win? terminal, boolean? created
function M.get(cmd, opts)
opts = opts or {}
local id = vim.inspect({ cmd = cmd, cwd = opts.cwd, env = opts.env, count = opts.count or vim.v.count1 })
local id = M.tid(cmd, opts)
local created = false
if not (terminals[id] and terminals[id]:buf_valid()) and (opts.create ~= false) then
local ret = M.open(cmd, opts)
ret:on("BufWipeout", function()
terminals[id] = nil
end, { buf = true })
terminals[id] = ret
assert(terminals[id], "Terminal was not created")
created = true
end
return terminals[id], created