buffer_picker.chat.lua (1825B)
1 local M = {} 2 3 -- Get a list of open buffers and their names 4 local function get_buffers() 5 local buffers = {} 6 for _, bufnr in ipairs(vim.api.nvim_list_bufs()) do 7 if vim.api.nvim_buf_is_loaded(bufnr) and vim.fn.buflisted(bufnr) == 1 then 8 local name = vim.fn.bufname(bufnr) 9 table.insert(buffers, { nr = bufnr, name = name }) 10 end 11 end 12 return buffers 13 end 14 15 -- Create the floating window and handle selection 16 function M.open_buffer_picker() 17 local buffers = get_buffers() 18 if #buffers == 0 then 19 print("No buffers found") 20 return 21 end 22 23 local lines = {} 24 for _, b in ipairs(buffers) do 25 table.insert(lines, string.format("[%d] %s", b.nr, b.name)) 26 end 27 28 local buf = vim.api.nvim_create_buf(false, true) 29 vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines) 30 31 -- Size and position 32 local width = math.floor(vim.o.columns * 0.6) 33 local height = #lines 34 local row = math.floor((vim.o.lines - height) / 2) 35 local col = math.floor((vim.o.columns - width) / 2) 36 37 local win = vim.api.nvim_open_win(buf, true, { 38 relative = "editor", 39 width = width, 40 height = height, 41 row = row, 42 col = col, 43 style = "minimal", 44 border = "rounded", 45 }) 46 47 -- Map <Enter> to switch buffer 48 vim.api.nvim_buf_set_keymap(buf, "n", "<CR>", "", { 49 noremap = true, 50 callback = function() 51 local line = vim.api.nvim_get_current_line() 52 local nr = tonumber(string.match(line, "%[(%d+)%]")) 53 if nr then 54 vim.cmd("b " .. nr) 55 vim.api.nvim_win_close(win, true) 56 end 57 end, 58 }) 59 60 vim.api.nvim_buf_set_keymap(buf, "n", "q", "", { 61 noremap = true, 62 callback = function() 63 vim.api.nvim_win_close(win, true) 64 end, 65 }) 66 end 67 68 -- Map the function to a command 69 vim.api.nvim_create_user_command("BufferPicker", M.open_buffer_picker, {}) 70 71 return M 72