From 131bcb8bf54f3cad6cc2b521f328e35b34f891cb Mon Sep 17 00:00:00 2001 From: newbieQQ Date: Thu, 11 Jun 2026 17:00:29 +0800 Subject: [PATCH] refactor: extract terminal logic into addons/term --- lua/addons/term.lua | 37 +++++++++++++++++++++++++++++++++++++ lua/keymap.lua | 31 +++++++------------------------ 2 files changed, 44 insertions(+), 24 deletions(-) create mode 100644 lua/addons/term.lua diff --git a/lua/addons/term.lua b/lua/addons/term.lua new file mode 100644 index 0000000..42b5610 --- /dev/null +++ b/lua/addons/term.lua @@ -0,0 +1,37 @@ +-- addons/term.lua — 持久化自适应终端 +-- +-- 用法: +-- local T = require('addons.term') +-- T.shell() -- 打开/关闭普通终端() +-- T.open('reasonix') -- 打开/关闭 Reasonix() +-- +-- 特性: +-- - 同一个终端实例持久化(关掉再开回来,对话不丢) +-- - 窗口方向自适应:横屏→右侧(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 diff --git a/lua/keymap.lua b/lua/keymap.lua index a316c09..35010cf 100644 --- a/lua/keymap.lua +++ b/lua/keymap.lua @@ -38,27 +38,10 @@ G.map({ { 'n', '', ':vertical resize +5' }, }) --- 终端 / Reasonix:横屏→右侧(45%屏宽),竖屏→下方(40%屏高),持久化 buffer(按 c-t/c-i 切换显隐) -do - local terms = {} -- 缓存,复用同一个终端实例 - - local function split_term(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 - - G.map({ - { 'n', '', function() split_term() end, { noremap = true } }, - { 'i', '', function() split_term() end, { noremap = true } }, - { 'n', '', function() split_term('reasonix') end, { noremap = true } }, - }) -end +-- 终端 / Reasonix(addons/term:持久化 + 自适应分屏) +local T = require('addons.term') +G.map({ + { 'n', '', T.shell, { noremap = true } }, + { 'i', '', T.shell, { noremap = true } }, + { 'n', '', function() T.open('reasonix') end, { noremap = true } }, +})