diff dot_config/nvim/lua/terminal.lua @ 336:7a8b66395d69

Add floating terminal to be toggled via c-z
author zegervdv <zegervdv@me.com>
date Thu, 21 Jan 2021 09:17:28 +0100
parents
children
line wrap: on
line diff
--- /dev/null	Thu Jan 01 00:00:00 1970 +0000
+++ b/dot_config/nvim/lua/terminal.lua	Thu Jan 21 09:17:28 2021 +0100
@@ -0,0 +1,80 @@
+-- Copied from: https://github.com/kutsan/dotfiles/blob/b2046a6c0bcc754fc381351119c14c374721fd4d/.config/nvim/lua/kutsan/mappings/normal/terminal.lua
+
+local api = vim.api
+local fn = vim.fn
+
+local terminal = {
+  buf = nil,
+  win = nil,
+  pid = nil
+}
+
+terminal.open = function ()
+  -- Create buffer.
+  local buf = nil
+
+  if terminal.buf and api.nvim_buf_is_loaded(terminal.buf) then
+    buf = terminal.buf
+  else
+    buf = api.nvim_create_buf(false, true)
+  end
+
+  -- Create window.
+  local width = math.ceil(vim.o.columns * 0.8)
+  local height = math.ceil(vim.o.lines * 0.9)
+
+  local win = api.nvim_open_win(buf, true, {
+    relative = 'editor',
+    style = 'minimal',
+    width = width,
+    height = height,
+    col = math.ceil((vim.o.columns - width) / 2),
+    row = math.ceil((vim.o.lines - height) / 2 - 1),
+  })
+  api.nvim_win_set_option(win, 'winhighlight', 'Normal:CursorLine')
+
+  -- Launch terminal.
+  if not terminal.buf then
+    terminal.pid = fn.termopen(string.format('%s --login', os.getenv('SHELL')))
+  end
+
+  vim.cmd('startinsert')
+  vim.cmd("autocmd! TermClose <buffer> lua require('terminal').close(true)")
+
+  -- Save current handles.
+  terminal.win = win
+  terminal.buf = buf
+end
+
+terminal.close = function (force)
+  if not terminal.win then
+    return
+  end
+
+  if api.nvim_win_is_valid(terminal.win) then
+    api.nvim_win_close(terminal.win, false)
+    terminal.win = nil
+  end
+
+  -- Force close upon terminal exit.
+  if force then
+    if api.nvim_buf_is_loaded(terminal.buf) then
+      api.nvim_buf_delete(terminal.buf, { force = true })
+    end
+
+    fn.jobstop(terminal.pid)
+
+    terminal.buf = nil
+    terminal.pid = nil
+  end
+end
+
+terminal.toggle = function ()
+  if not terminal.win then
+    terminal.open()
+  else
+    terminal.close()
+  end
+end
+
+return terminal