From 663119c828c5f471de41da2a5d399b6f9c972438 Mon Sep 17 00:00:00 2001 From: Daniel Lundin Date: Sun, 10 Nov 2024 14:18:24 +0100 Subject: [PATCH] nvim: sort buffers by most recent use --- home/common/nvim/mini.lua | 54 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 54 insertions(+) diff --git a/home/common/nvim/mini.lua b/home/common/nvim/mini.lua index 0b41ecd..2c71357 100644 --- a/home/common/nvim/mini.lua +++ b/home/common/nvim/mini.lua @@ -78,6 +78,60 @@ MiniPick.registry.grep_live_root = function(local_opts) return MiniPick.builtin.grep_live(local_opts, { source = { cwd = root_dir } }) end +require("mini.pick").registry.buffers = function(local_opts, opts) + local_opts = vim.tbl_deep_extend( + "force", + { sort_lastused = false, sort_mru = true, include_current = true, include_unlisted = false }, + local_opts or {} + ) + local buffers_output = vim.api.nvim_exec("buffers" .. (local_opts.include_unlisted and "!" or ""), true) + local cur_buf_id, include_current = vim.api.nvim_get_current_buf(), local_opts.include_current + local items = {} + local default_selection_idx = 1 + for _, l in ipairs(vim.split(buffers_output, "\n")) do + local buf_str, name = l:match("^%s*%d+"), l:match('"(.*)"') + local buf_id = tonumber(buf_str) + local flag = buf_id == vim.fn.bufnr("") and "%" or (buf_id == vim.fn.bufnr("#") and "#" or " ") + local item = { text = name, bufnr = buf_id, flag = flag } + if buf_id ~= cur_buf_id or include_current then + if local_opts.sort_lastused and not local_opts.ignore_current_buffer and flag == "#" then + default_selection_idx = 2 + end + if local_opts.sort_lastused and (flag == "#" or flag == "%") then + local idx = ((items[1] ~= nil and items[1].flag == "%") and 2 or 1) + table.insert(items, idx, item) + else + table.insert(items, item) + end + end + end + if local_opts.sort_mru then + table.sort(items, function(a, b) + return vim.fn.getbufinfo(a.bufnr)[1].lastused > vim.fn.getbufinfo(b.bufnr)[1].lastused + end) + end + + local show = function(buf_id, items, query) + require("mini.pick").default_show(buf_id, items, query, { show_icons = true }) + end + local default_opts = { source = { name = "Buffers", show = show } } + opts = vim.tbl_deep_extend("force", default_opts, opts or {}, { source = { items = items } }) + if default_selection_idx > 1 then + vim.api.nvim_create_autocmd("User", { + pattern = "MiniPickStart", + once = true, + callback = function() + local mappings = require("mini.pick").get_picker_opts().mappings + local keys = vim.fn["repeat"](mappings.move_down, default_selection_idx - 1) + vim.api.nvim_input(vim.api.nvim_replace_termcodes(keys, true, true, true)) + end, + }) + end + return require("mini.pick").start(opts) + end + + + local miniclue = require('mini.clue') miniclue.setup({ -- cute prompts about bindings