Skip to content
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 3 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -157,8 +157,9 @@ local snacks_terminal_opts = {
position = 'right',
enter = false,
on_win = function(win)
-- Set up keymaps and cleanup for an arbitrary terminal
require('opencode.terminal').setup(win.win)
-- Set up keymaps and cleanup for an arbitrary terminal.
-- `restore_focus = false` preserves the terminal backend's focus choice.
require('opencode.terminal').setup(win.win, { restore_focus = false })
end,
},
}
Expand Down
27 changes: 26 additions & 1 deletion lua/opencode/terminal.lua
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
local M = {}

---@class opencode.terminal.Opts : vim.api.keyset.win_config
---@class opencode.terminal.SetupOpts
---@field restore_focus? boolean Return focus to the previously focused window after the initial redraw workaround. Defaults to true.

local winid
local bufnr
Expand Down Expand Up @@ -142,7 +144,12 @@ end
--- - Keymaps for Neovim-like message navigation.
--- - Properly clean up `opencode` process on close.
---@param win integer
function M.setup(win)
---@param opts? opencode.terminal.SetupOpts
function M.setup(win, opts)
opts = vim.tbl_extend("keep", opts or {}, {
restore_focus = true,
})

local buf = vim.api.nvim_win_get_buf(win)
---@type integer|nil
local pid
Expand All @@ -161,6 +168,24 @@ function M.setup(win)
end,
})

-- Redraw terminal buffer on initial render.
-- Fixes empty columns on the right side.
local auid
auid = vim.api.nvim_create_autocmd("TermRequest", {
buffer = buf,
callback = function(ev)
if ev.data.cursor[1] > 1 then
vim.api.nvim_del_autocmd(auid)
vim.api.nvim_set_current_win(win)
if opts.restore_focus then
vim.cmd([[startinsert | call feedkeys("\<C-\>\<C-n>\<C-w>p", "n")]])
else
vim.cmd("startinsert")
end
end
end,
})

-- When the terminal's job stops normally
vim.api.nvim_create_autocmd("TermClose", {
buffer = buf,
Expand Down
Loading