feat: prompt when closing modified/term buffers (#2658)

This commit is contained in:
kylo252 2022-05-26 13:28:04 +02:00 committed by GitHub
parent 6dbba1f959
commit a11c46c29a
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23

View file

@ -142,26 +142,42 @@ M.setup = function()
end end
end end
--stylua: ignore
-- Common kill function for bdelete and bwipeout -- Common kill function for bdelete and bwipeout
-- credits: based on bbye and nvim-bufdel -- credits: based on bbye and nvim-bufdel
---@param kill_command string defaults to "bd" ---@param kill_command? string defaults to "bd"
---@param bufnr? number defaults to the current buffer ---@param bufnr? number defaults to the current buffer
---@param force? boolean defaults to false ---@param force? boolean defaults to false
function M.buf_kill(kill_command, bufnr, force) function M.buf_kill(kill_command, bufnr, force)
kill_command = kill_command or "bd"
local bo = vim.bo local bo = vim.bo
local api = vim.api local api = vim.api
local fmt = string.format
local fnamemodify = vim.fn.fnamemodify
if bufnr == 0 or bufnr == nil then if bufnr == 0 or bufnr == nil then
bufnr = api.nvim_get_current_buf() bufnr = api.nvim_get_current_buf()
end end
kill_command = kill_command or "bd" local bufname = api.nvim_buf_get_name(bufnr)
-- If buffer is modified and force isn't true, print error and abort if not force then
if not force and bo[bufnr].modified then local warning
return api.nvim_err_writeln( if bo[bufnr].modified then
string.format("No write since last change for buffer %d (set force to true to override)", bufnr) warning = fmt([[No write since last change for (%s)]], fnamemodify(bufname, ":t"))
) elseif api.nvim_buf_get_option(bufnr, "buftype") == "terminal" then
warning = fmt([[Terminal %s will be killed]], bufname)
end
if warning then
vim.ui.input({
prompt = string.format([[%s. Close it anyway? [y]es or [n]o (default: no): ]], warning),
}, function(choice)
if choice:match "ye?s?" then force = true end
end)
if not force then return end
end
end end
-- Get list of windows IDs with the buffer to close -- Get list of windows IDs with the buffer to close
@ -169,9 +185,7 @@ function M.buf_kill(kill_command, bufnr, force)
return api.nvim_win_get_buf(win) == bufnr return api.nvim_win_get_buf(win) == bufnr
end, api.nvim_list_wins()) end, api.nvim_list_wins())
if #windows == 0 then if #windows == 0 then return end
return
end
if force then if force then
kill_command = kill_command .. "!" kill_command = kill_command .. "!"