From 543f4902b86b744ac9e158c0730f7ab1db452e53 Mon Sep 17 00:00:00 2001 From: psychhim Date: Sun, 14 Sep 2025 14:00:42 +0530 Subject: [PATCH] Modified Custom Keybind of q to give the options to save, discard changes or cancel --- init.lua | 34 ++++++++++++++++++++++++++++------ 1 file changed, 28 insertions(+), 6 deletions(-) diff --git a/init.lua b/init.lua index dd865ac..9b8b031 100644 --- a/init.lua +++ b/init.lua @@ -298,9 +298,6 @@ vim.keymap.set('n', 'n', 'cd %:p:h | Neotree toggle float') --Terminal open in new tab vim.keymap.set('n', 't', 'tabnew +termi') ---Close current window -vim.keymap.set('n', 'q', 'q') - -- Save current buffer (asks for filename if new/unsaved) vim.keymap.set('n', 'w', function() if vim.api.nvim_buf_get_name(0) == "" then @@ -316,8 +313,31 @@ vim.keymap.set('n', 'w', function() end end, { desc = "Save buffer (prompt if new file)" }) ---Discard changes and Close current window -vim.keymap.set('n', 'qn', 'q!') +-- Close current window (asks if buffer is unsaved) +vim.keymap.set('n', 'q', function() + if vim.bo.modified then + local choice = vim.fn.input("Buffer modified! Save (y), Discard (n), Cancel (any other key)? ") + if choice:lower() == "y" then + if vim.api.nvim_buf_get_name(0) == "" then + local filename = vim.fn.input("Save as: ", "", "file") + if filename ~= "" then + vim.cmd("saveas " .. vim.fn.fnameescape(filename)) + vim.cmd("q") + else + print("Save cancelled") + end + else + vim.cmd("wq") + end + elseif choice:lower() == "n" then + vim.cmd("q!") + else + print("Quit cancelled") + end + else + vim.cmd("q") + end +end, { desc = "Close buffer (prompt if modified)" }) -- Save changes and close current window (asks for filename if new/unsaved) vim.keymap.set('n', 'qy', function() @@ -335,13 +355,15 @@ vim.keymap.set('n', 'qy', function() end end, { desc = "Save & quit (prompt if new file)" }) +--Discard changes and Close current window +vim.keymap.set('n', 'qn', 'q!') + --Switch below/right split windows vim.keymap.set('n', '', '') --Switch above/left split windows vim.keymap.set('n', '', 'W') - -- [[ Highlight on yank ]] -- See `:help vim.highlight.on_yank()` local highlight_group = vim.api.nvim_create_augroup('YankHighlight', { clear = true })