nvim: Implement buffer switching through fzy
Anirudh Oppiliappan x@icyphox.sh
Wed, 03 Feb 2021 10:54:23 +0530
3 files changed,
71 insertions(+),
11 deletions(-)
M
config/nvim/lua/fzy.lua
→
config/nvim/lua/fzy/shell.lua
@@ -1,9 +1,8 @@
--- returns the fzy output, do with it what you will local fn = vim.fn local cmd = vim.cmd local M = {} -function M.fzy(fzy_cmd, action) +function M.fzy_shell_cmd(fzy_cmd, action) -- save shell output to a temp file file = fn.tempname() shell_cmd = {@@ -38,8 +37,6 @@ -- run action against output
-- ex: ':e somefile' vim.cmd(table.concat({ action, fzy_out }, ' ')) end }) - - return fzy_out end return M
A
config/nvim/lua/fzy/buffers.lua
@@ -0,0 +1,62 @@
+local fn = vim.fn +local cmd = vim.cmd +local M = {} + +function M.fzy_buffers() + local buffers = {} + + -- list of buffers + local nbuf = fn.range(1, fn.bufnr('$')) + + winid = fn.win_getid() + -- filter out buffers that don't have 'buflisted' set + for _, n in ipairs(nbuf) do + if fn.buflisted(n) then + buffers[fn.bufname(n)] = n + end + end + + -- write buffer names to file to feed to fzy + buffile = fn.tempname() + local f = io.open(buffile, "a") + for b, _ in pairs(buffers) do + f:write(b, '\n') + end + f:close() + + -- file to store fzy selection + outfile = fn.tempname() + + shell_cmd = { + '/bin/sh', + '-c', + 'fzy < ' .. buffile .. ' > ' .. outfile + } + + -- start a new buffer + cmd('botright 10 new') + cmd('startinsert') + + fn.termopen(shell_cmd, { on_exit = function() + -- delete buffer on exit + cmd('bd!') + fn.win_gotoid(winid) + + -- read contents of file + local f = io.open(outfile, 'r') + buf_choice = f:read('*all') + + -- strip '\n' + buf_choice, _ = string.gsub(buf_choice, '\n', '') + + -- housekeeping + f:close() + os.remove(outfile) + os.remove(buffile) + + -- switch to selected buffer + cmd(':buffer ' .. buffers[buf_choice]) + end }) +end + +return M
M
config/nvim/lua/maps.lua
→
config/nvim/lua/maps.lua
@@ -30,21 +30,22 @@ end
-- fzy mappings if vim.fn.executable('fzy') then - _G.fzy = require('fzy').fzy + _G.fzy_shell_cmd = require('fzy.shell').fzy_shell_cmd map( '', '<leader>e', - -- TODO: Rework this directory ignores into a table string.format( - ':call v:lua.fzy("find -L . -type f %s", ":e")<cr>', - fzy_ignore({'*.git/*', '*node_modules*'}) + ':call v:lua.fzy_shell_cmd("find -L . -type f %s", ":e")<cr>', + fzy_ignore{'*.git/*', '*node_modules*', '*.pyc'} ), { noremap=true, silent=true } ) - --map('', - --'<leader>f', - --'') + _G.fzy_buffers = require('fzy.buffers').fzy_buffers + map('', + '<leader>b', + ':call v:lua.fzy_buffers()<cr>', + { noremap=true, silent=true }) else print('fzy not in PATH!') end