Last active
July 19, 2025 02:23
-
-
Save rlychrisg/b69a0d90d798525051cd69d61360a152 to your computer and use it in GitHub Desktop.
smart closing of nvim buffers, quits if current buffer is last and asks for confirmation if buffer has unsaved changes
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| -- this probably isn't the most efficient way of doing this | |
| -- but i'm quite happy with it so i want to share it. | |
| -- function to check whether current buffer is modified | |
| local function modcheck() | |
| local current_buf = vim.api.nvim_get_current_buf() | |
| if vim.api.nvim_buf_get_option(current_buf, 'modified') then | |
| return true | |
| else | |
| return false | |
| end | |
| end | |
| -- check if buffer is last before deleting buffer or quitting nvim | |
| local function smart_bdelete() | |
| local listed_buffers = vim.fn.getbufinfo({ buflisted = 1 }) | |
| if #listed_buffers <= 1 then | |
| if modcheck() then | |
| local choice = vim.fn.confirm("Buffer has unsaved changes", "&Save\n&Ignore\n&Cancel", 3) | |
| if choice == 1 then | |
| vim.cmd("wq") | |
| elseif choice == 2 then | |
| vim.cmd("q!") | |
| end | |
| else | |
| vim.cmd("q") | |
| end | |
| else | |
| if modcheck() then | |
| local choice = vim.fn.confirm("Buffer has unsaved changes", "&Save\n&Ignore\n&Cancel", 3) | |
| if choice == 1 then | |
| vim.cmd("w") | |
| vim.cmd("bdelete") | |
| elseif choice == 2 then | |
| vim.cmd("bdelete!") | |
| end | |
| else | |
| vim.cmd("bdelete") | |
| end | |
| end | |
| end | |
| vim.keymap.set("n", "<leader>q", smart_bdelete, { desc = "Smart close buffer or quit" }) | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment