Luigit
repositories / dotfiles

dotfiles

bugabingas dorkfiles

owned by admin

neovim/lua/bugabinga/terminal.lua

Raw
local map = require 'std.map'
local user_command = require 'std.user_command'

local state = {
	float = {
		buffer = -1,
		window = -1,
	},
}

local open_float = function ( options )
	options = options or {}
	local max_width = vim.o.columns
	local max_height = vim.o.lines
	local size = options.size or 0.88
	local width = options.width or math.floor( max_width * size )
	local height = options.height or math.floor( max_height * size )
	local center_col = math.floor( (max_width - width) / 2 )
	local center_row = math.floor( (max_height - height) / 2 )
	local buffer_created = false
	local create_buffer = function ()
		buffer_created = true
		return vim.api.nvim_create_buf( false, true )
	end
	local buffer = vim.api.nvim_buf_is_valid( options.buffer ) and options.buffer
		or create_buffer()
	local window_settings = {
		relative = 'editor',
		width = width,
		height = height,
		col = center_col,
		row = center_row,
		style = 'minimal',
		border = options.border or vim.g.border_style,
	}
	local window = vim.api.nvim_open_win( buffer, true, window_settings )
	if buffer_created then
		vim.cmd.terminal 'nu --login'
	end
	vim.cmd.startinsert()
	local buffer_options = {
		buflisted = false,
	}
	for buffer_option, value in pairs( buffer_options ) do
		vim.api.nvim_set_option_value( buffer_option, value, {
			buf = buffer,
		} )
	end
	local window_options = {
		winbar = '',
	}
	for window_option, value in pairs( window_options ) do
		vim.api.nvim_set_option_value( window_option, value, {
			win = window,
		} )
	end
	return {
		buffer = buffer,
		window = window,
	}
end

local toggle_terminal = function ()
	if vim.api.nvim_win_is_valid( state.float.window ) then
		vim.api.nvim_win_hide( state.float.window )
	else
		state.float = open_float( state.float )
	end
end

user_command.Terminal 'Toggle Terminal in floating window' ( toggle_terminal )
map.normal.terminal {
	description = 'Toggle terminal',
	category = 'terminal',
	keys = '<leader>tf',
	command = toggle_terminal,
}

map.terminal {
	description = 'Enter normal mode',
	category = 'terminal',
	keys = '<esc><esc>',
	command = '<c-\\><c-n>',
}