Skip to content

Commit 30b3b50

Browse files
author
Joshua Molloy
committed
feat: Added floating terminal module
1 parent 2b754cc commit 30b3b50

File tree

2 files changed

+75
-0
lines changed

2 files changed

+75
-0
lines changed

init.lua

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -819,5 +819,6 @@ require('lazy').setup {
819819
{ import = 'custom.plugins' },
820820
}
821821

822+
require 'custom.floating-terminal'
822823
-- The line beneath this is called `modeline`. See `:help modeline`
823824
-- vim: ts=2 sts=2 sw=2 et

lua/custom/floating-terminal.lua

Lines changed: 74 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,74 @@
1+
local M = {}
2+
3+
local state = {
4+
floating = {
5+
buf = -1,
6+
win = -1,
7+
job_id = -1,
8+
},
9+
}
10+
11+
local function create_floating_term(opts)
12+
opts = opts or {}
13+
14+
local width = math.floor(vim.o.columns * 0.8)
15+
local height = math.floor(vim.o.lines * 0.8)
16+
local row = math.floor((vim.o.lines - height) / 2)
17+
local col = math.floor((vim.o.columns - width) / 2)
18+
19+
local buf = nil
20+
if not opts.buf or not vim.api.nvim_buf_is_valid(opts.buf) then
21+
buf = vim.api.nvim_create_buf(false, true)
22+
else
23+
buf = opts.buf
24+
end
25+
26+
local win_config = {
27+
relative = 'editor',
28+
width = width,
29+
height = height,
30+
row = row,
31+
col = col,
32+
style = 'minimal',
33+
border = 'rounded',
34+
}
35+
36+
local win = vim.api.nvim_open_win(buf, true, win_config)
37+
return { buf = buf, win = win }
38+
end
39+
40+
-- Function for checking if a file exists, just check that you can open it for reading
41+
local function file_exists(filepath)
42+
local f = io.open(filepath, 'r')
43+
if f then
44+
f:close()
45+
return true
46+
end
47+
return false
48+
end
49+
50+
M.toggle_terminal = function()
51+
if state.floating.win == -1 or not vim.api.nvim_win_is_valid(state.floating.win) then
52+
state.floating = create_floating_term { buf = state.floating.buf }
53+
if vim.bo[state.floating.buf].buftype ~= 'terminal' then
54+
state.floating.job_id = vim.fn.termopen(vim.o.shell)
55+
56+
if file_exists '.envrc' then
57+
vim.defer_fn(function()
58+
if state.floating.job_id then
59+
vim.fn.chansend(state.floating.job_id, 'direnv reload\n')
60+
end
61+
end, 100)
62+
end
63+
end
64+
else
65+
vim.api.nvim_win_hide(state.floating.win)
66+
state.floating.win = -1
67+
end
68+
end
69+
70+
-- Custom command for opening and closing floating terminal
71+
vim.api.nvim_create_user_command('FloatingTerminal', M.toggle_terminal, {})
72+
vim.keymap.set({ 'n', 't' }, '<leader>tt', M.toggle_terminal)
73+
74+
return M

0 commit comments

Comments
 (0)