|
| 1 | +vim.keymap.set('t', '<esc><esc>', '<c-\\><c-n>') |
| 2 | + |
| 3 | +local state = { |
| 4 | + floating = { |
| 5 | + buf = -1, |
| 6 | + win = -1, |
| 7 | + }, |
| 8 | +} |
| 9 | + |
| 10 | +local function create_floating_window(opts) |
| 11 | + opts = opts or {} |
| 12 | + local width = opts.width or math.floor(vim.o.columns * 0.8) |
| 13 | + local height = opts.height or math.floor(vim.o.lines * 0.8) |
| 14 | + |
| 15 | + -- Calculate the position to center the window |
| 16 | + local col = math.floor((vim.o.columns - width) / 2) |
| 17 | + local row = math.floor((vim.o.lines - height) / 2) |
| 18 | + |
| 19 | + -- Create a buffer |
| 20 | + local buf = nil |
| 21 | + if vim.api.nvim_buf_is_valid(opts.buf) then |
| 22 | + buf = opts.buf |
| 23 | + else |
| 24 | + buf = vim.api.nvim_create_buf(false, true) -- No file, scratch buffer |
| 25 | + end |
| 26 | + |
| 27 | + -- Define window configuration |
| 28 | + local win_config = { |
| 29 | + relative = 'editor', |
| 30 | + width = width, |
| 31 | + height = height, |
| 32 | + col = col, |
| 33 | + row = row, |
| 34 | + style = 'minimal', -- No borders or extra UI elements |
| 35 | + border = 'rounded', |
| 36 | + } |
| 37 | + |
| 38 | + -- Create the floating window |
| 39 | + local win = vim.api.nvim_open_win(buf, true, win_config) |
| 40 | + |
| 41 | + return { buf = buf, win = win } |
| 42 | +end |
| 43 | + |
| 44 | +local toggle_terminal = function() |
| 45 | + if not vim.api.nvim_win_is_valid(state.floating.win) then |
| 46 | + state.floating = create_floating_window { buf = state.floating.buf } |
| 47 | + if vim.bo[state.floating.buf].buftype ~= 'terminal' then |
| 48 | + vim.cmd.terminal() |
| 49 | + end |
| 50 | + else |
| 51 | + vim.api.nvim_win_hide(state.floating.win) |
| 52 | + end |
| 53 | +end |
| 54 | + |
| 55 | +-- Example usage: |
| 56 | +-- Create a floating window with default dimensions |
| 57 | +vim.api.nvim_create_user_command('Floaterminal', toggle_terminal, {}) |
| 58 | +vim.keymap.set({ 'n', 't' }, '<leader>tt', toggle_terminal, { desc = 'Open Floating Terminal' }) |
0 commit comments