refactor: extract terminal logic into addons/term

This commit is contained in:
QQ 2026-06-11 17:00:29 +08:00
parent e45a3b991e
commit 131bcb8bf5
2 changed files with 44 additions and 24 deletions

37
lua/addons/term.lua Normal file
View File

@ -0,0 +1,37 @@
-- addons/term.lua — 持久化自适应终端
--
-- 用法:
-- local T = require('addons.term')
-- T.shell() -- 打开/关闭普通终端(<c-t>
-- T.open('reasonix') -- 打开/关闭 Reasonix<C-i>
--
-- 特性:
-- - 同一个终端实例持久化(关掉再开回来,对话不丢)
-- - 窗口方向自适应横屏→右侧45%竖屏→下方40%
-- - 依赖 toggleterm.nvim
local M = {}
local terms = {} -- 缓存终端实例key 是命令名nil = 普通 shell
function M.open(cmd)
local ui = vim.api.nvim_list_uis()[1]
local tall = ui.height > ui.width
local name = cmd or '__shell__'
if not terms[name] or not terms[name]:is_open() then
terms[name] = require('toggleterm.terminal').Terminal:new({
direction = tall and 'horizontal' or 'vertical',
cmd = cmd,
size = tall and math.floor(ui.height * 0.4) or math.floor(ui.width * 0.45),
})
end
terms[name]:toggle()
end
function M.shell()
M.open(nil)
end
return M

View File

@ -38,27 +38,10 @@ G.map({
{ 'n', '<right>', ':vertical resize +5<CR>' }, { 'n', '<right>', ':vertical resize +5<CR>' },
}) })
-- 终端 / Reasonix横屏→右侧45%屏宽竖屏→下方40%屏高),持久化 buffer按 c-t/c-i 切换显隐) -- 终端 / Reasonixaddons/term持久化 + 自适应分屏)
do local T = require('addons.term')
local terms = {} -- 缓存,复用同一个终端实例 G.map({
{ 'n', '<c-t>', T.shell, { noremap = true } },
local function split_term(cmd) { 'i', '<c-t>', T.shell, { noremap = true } },
local ui = vim.api.nvim_list_uis()[1] { 'n', '<C-i>', function() T.open('reasonix') end, { noremap = true } },
local tall = ui.height > ui.width })
local name = cmd or '__shell__'
if not terms[name] or not terms[name]:is_open() then
terms[name] = require('toggleterm.terminal').Terminal:new({
direction = tall and 'horizontal' or 'vertical',
cmd = cmd,
size = tall and math.floor(ui.height * 0.4) or math.floor(ui.width * 0.45),
})
end
terms[name]:toggle()
end
G.map({
{ 'n', '<c-t>', function() split_term() end, { noremap = true } },
{ 'i', '<c-t>', function() split_term() end, { noremap = true } },
{ 'n', '<C-i>', function() split_term('reasonix') end, { noremap = true } },
})
end