Skip to content

Instantly share code, notes, and snippets.

@bantya
Created January 6, 2025 05:08
Show Gist options
  • Select an option

  • Save bantya/640cd573a5ef2ec9410fb5a662ea3507 to your computer and use it in GitHub Desktop.

Select an option

Save bantya/640cd573a5ef2ec9410fb5a662ea3507 to your computer and use it in GitHub Desktop.
Floating terminal in neovim
mkdir ~/.config/nvim/plugin
touch ~/.config/nvim/plugin/Floterminal.lua
local state = {
floating = {
buf = -1,
win = -1,
},
}
local function create_floating_window(opts)
opts = opts or {}
local width = opts.width or math.floor(vim.o.columns * 0.8)
local height = opts.height or math.floor(vim.o.lines * 0.8)
-- calculate the position to the center of the window
local col = math.floor((vim.o.columns - width) / 2)
local row = math.floor((vim.o.lines - height) / 2)
-- create a buffer
local buf = nil
if vim.api.nvim_buf_is_valid(opts.buf) then
buf = opts.buf
else
buf = vim.api.nvim_create_buf(false, true)
-- listed, scratch
end
-- define window configuration
local win_config = {
relative = "editor",
title = "Floterminal",
width = width,
height = height,
col = col,
row = row,
style = "minimal", -- no borders or extra ui elements
border = "rounded",
}
-- create a floating window
local win = vim.api.nvim_open_win(buf, true, win_config)
-- buffer, enter, config
-- Set the buffer to editable mode
vim.api.nvim_buf_set_option(buf, "modifiable", true)
vim.api.nvim_buf_set_option(buf, "bufhidden", "wipe")
-- Start in insert mode (edit mode)
vim.cmd("startinsert")
return { buf = buf, win = win }
end
local toggle_terminal = function()
if not vim.api.nvim_win_is_valid(state.floating.win) then
state.floating = create_floating_window({ buf = state.floating.buf })
if vim.bo[state.floating.buf].buftype ~= "terminal" then
vim.cmd.terminal()
end
else
vim.api.nvim_win_hide(state.floating.win)
end
end
-- example usage
vim.api.nvim_create_user_command("Floterminal", toggle_terminal, {})
vim.keymap.set({ "n", "t" }, "<leader>tt", toggle_terminal)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment