From 848a2d64d8726d214c2019c4029c3ee4f3dd882d Mon Sep 17 00:00:00 2001 From: Andrew Date: Fri, 14 Mar 2025 11:43:31 -0700 Subject: [PATCH] add floating terminal --- plugin/floaterminal.lua | 77 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 77 insertions(+) create mode 100644 plugin/floaterminal.lua diff --git a/plugin/floaterminal.lua b/plugin/floaterminal.lua new file mode 100644 index 00000000..f53a9dca --- /dev/null +++ b/plugin/floaterminal.lua @@ -0,0 +1,77 @@ +local terminals = {} + +local function create_floating_window(opts) + local opts = opts or {} + + -- Get editor dimensions + local width = vim.o.columns + local height = vim.o.lines + + -- Default size (80% of editor width and centered) + local win_width = opts.width or math.ceil(width * 0.8) + local win_height = opts.height or math.ceil(height * 0.8) + + -- Position (centered) + local row = math.ceil((height - win_height) / 2) + local col = math.ceil((width - win_width) / 2) + + -- Create a new buffer + local buf = nil + if opts.buf and vim.api.nvim_buf_is_valid(opts.buf) then + buf = opts.buf + else + buf = vim.api.nvim_create_buf(false, true) + end + + -- Set window options + local win_opts = { + title = 'Terminal ' .. opts.name, + relative = 'editor', + width = win_width, + height = win_height, + row = row, + col = col, + style = 'minimal', + border = 'rounded', + } + + -- Open the floating window + local win = vim.api.nvim_open_win(buf, true, win_opts) + + return { buf = buf, win = win } +end + +local function toggle_terminal(name) + if not name or name == '' then + return + end + + -- Check if terminal exists for the given name + if terminals[name] and vim.api.nvim_buf_is_valid(terminals[name].buf) then + if vim.api.nvim_win_is_valid(terminals[name].win) then + -- If window exists, hide it + vim.api.nvim_win_hide(terminals[name].win) + return + else + -- Otherwise, reopen the floating terminal + terminals[name] = create_floating_window { buf = terminals[name].buf, name = name } + vim.cmd 'normal i' + return + end + end + + -- If it doesn't exist, create a new floating terminal + terminals[name] = create_floating_window { name = name } + vim.cmd.terminal() + vim.cmd 'normal i' +end + +local function handle_terminal_key() + vim.ui.input({ prompt = 'Enter terminal name: ' }, function(input) + if input then + toggle_terminal(input) + end + end) +end + +vim.keymap.set('n', 't', handle_terminal_key, { noremap = true, silent = true })