From 40bb137ab1d3f71e194e16de00bac8e345f1efdc Mon Sep 17 00:00:00 2001 From: Bartek Stalewski Date: Tue, 16 Sep 2025 01:14:51 +0200 Subject: [PATCH] (neovim) save-and-exit keymap will try to close just the current buffer --- config/common/nvim/lua/config/keymaps.lua | 2 +- config/common/nvim/lua/utils/quit.lua | 35 +++++++++++++++++++++++ 2 files changed, 36 insertions(+), 1 deletion(-) create mode 100644 config/common/nvim/lua/utils/quit.lua diff --git a/config/common/nvim/lua/config/keymaps.lua b/config/common/nvim/lua/config/keymaps.lua index 6e915d3..25386c0 100644 --- a/config/common/nvim/lua/config/keymaps.lua +++ b/config/common/nvim/lua/config/keymaps.lua @@ -32,7 +32,7 @@ map("n", "[w", diagnostic_goto(false, "WARN"), { desc = "prev warning" }) map("v", "/", "gc", { desc = "toggle comments", remap = true }) -map("n", "", "wqa", { desc = "save and exit", remap = true }) +map("n", "", 'lua require("utils.quit").close_buffer()', { desc = "save and exit", remap = true }) map("n", "", "w", { desc = "switch pane", remap = true }) map("n", "+", ":vertical resize +5") diff --git a/config/common/nvim/lua/utils/quit.lua b/config/common/nvim/lua/utils/quit.lua new file mode 100644 index 0000000..06c6350 --- /dev/null +++ b/config/common/nvim/lua/utils/quit.lua @@ -0,0 +1,35 @@ +local M = {} + +count_bufs_by_type = function(loaded_only) + loaded_only = (loaded_only == nil and true or loaded_only) + count = { + normal = 0, + acwrite = 0, + help = 0, + nofile = 0, + nowrite = 0, + quickfix = 0, + terminal = 0, + prompt = 0 + } + buftypes = vim.api.nvim_list_bufs() + for _, bufname in pairs(buftypes) do + if (not loaded_only) or vim.api.nvim_buf_is_loaded(bufname) then + buftype = vim.api.nvim_buf_get_option(bufname, 'buftype') + buftype = buftype ~= '' and buftype or 'normal' + count[buftype] = count[buftype] + 1 + end + end + return count +end + +function M.close_buffer() + local bufTable = count_bufs_by_type() + if (bufTable.normal <= 1) then + local result = vim.api.nvim_exec([[:wq]], true) + else + local result = vim.api.nvim_exec([[:update | bdelete]], true) + end +end + +return M