Skip to content

Instantly share code, notes, and snippets.

@Chattille
Last active May 19, 2023 02:44
Show Gist options
  • Save Chattille/15e092c3e523834cf5aab74b0793766c to your computer and use it in GitHub Desktop.
Save Chattille/15e092c3e523834cf5aab74b0793766c to your computer and use it in GitHub Desktop.
Quit NeoVim or current tab if there is only one non-autoclosable window.
---Filetypes ignored on quit
local autoclosables = {
'NvimTree',
'Outline',
'dap-repl',
'dapui_console',
'dapui_scopes',
'dapui_stacks',
'dapui_watches',
'dapui_breakpoints',
'toggleterm',
}
---Print out less verbose error messages.
---
---@param cmd string NeoVim command.
local function call(cmd)
xpcall(vim.cmd, function(msg)
local err = string.gsub(msg, '^.+Vim%(%w+%):', '')
vim.notify(err, vim.log.levels.ERROR)
end, 'silent ' .. cmd)
end
---Count non-autoclosable windows.
---
---@param wins number[] List of windows.
local function nonauto_count(wins)
return #vim.tbl_filter(function(win)
local buf = vim.api.nvim_win_get_buf(win)
local ft = vim.api.nvim_buf_get_option(buf, 'filetype')
return not vim.tbl_contains(autoclosables, ft)
end, wins)
end
---Quit NeoVim or tab on last non-autoclosable window.
local function quit()
local wins = vim.api.nvim_tabpage_list_wins(0)
if
vim.tbl_contains(autoclosables, vim.bo.filetype)
or nonauto_count(wins) >= 2
then
call 'quit'
return
end
-- last non-autoclosable window
for _, win in ipairs(wins) do -- close every window
call('call win_execute(' .. win .. ', "quit")')
end
end
vim.keymap.set(
'n',
'<Leader>q',
quit,
{ desc = 'Quit NeoVim or tab on last non-autoclosable window' }
)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment