nvim/lua/fzy/buffers.lua (view raw)
1local fn = vim.fn
2local cmd = vim.cmd
3local M = {}
4
5local function normalize_path(path)
6 return vim.fn.fnamemodify(vim.fn.expand(path), ':p:~:.')
7end
8
9function M.fzy_buffers(exclude)
10 local buffers = {}
11
12 -- list of buffers
13 local nbuf = fn.range(1, fn.bufnr('$'))
14
15 -- filter out buffers that don't have 'buflisted' set
16 for _, n in ipairs(nbuf) do
17 if fn.buflisted(n) then
18 buffers[fn.bufname(n)] = n
19 end
20 end
21
22 -- write buffer names to file to feed to fzy
23 local buffile = fn.tempname()
24 local f = io.open(buffile, "a")
25 for b, _ in pairs(buffers) do
26 local path = normalize_path(b)
27 if not string.match(path, exclude) then
28 f:write(path, '\n')
29 end
30 end
31 f:close()
32
33 local fzy_cmd = {
34 'fzy -p "buf > " ',
35 '< ' .. buffile,
36 }
37
38 require('fzy/fzy').fzy_search(table.concat(fzy_cmd), function(stdout)
39 -- strip '\n'
40 local selected, _ = stdout:gsub('\n', '')
41 cmd('bd!')
42
43 cmd('buffer ' .. buffers[ selected ])
44 -- housekeeping
45 os.remove(buffile)
46 end
47 )
48
49end
50
51return M