vim: factor out reusable functions into a separate module

This commit is contained in:
Fernando Schauenburg 2023-07-16 01:21:58 +02:00
parent d845b74036
commit 3670b76dc9
3 changed files with 46 additions and 20 deletions

View file

@ -1,11 +1,8 @@
local config = function() local config = function()
local cmp = require('cmp') local cmp = require('cmp')
-- flip(f)(a, b) == f(b, a) local partial = require('user.util').partial
local flip = function(f) return function(a, b) return f(b, a) end end local flip = require('user.util').flip
-- partial(f, x)(...) == f(x, ...)
local partial = function(f, x) return function(...) return f(x, ...) end end
-- assign('i', { key = func, ... }) == { key = { i = func }, ... } -- assign('i', { key = func, ... }) == { key = { i = func }, ... }
-- assign({'i', 'c'}, { key = func, ... }) == { key = { i = func, c = func }, ...} -- assign({'i', 'c'}, { key = func, ... }) == { key = { i = func, c = func }, ...}

View file

@ -103,21 +103,7 @@ local config = function()
telescope.load_extension 'file_browser' telescope.load_extension 'file_browser'
telescope.load_extension 'fzf' telescope.load_extension 'fzf'
local with_saved_register = function(register, func) local get_selected_text = require('user.util').get_selected_text
local saved = vim.fn.getreg(register)
local result = func()
vim.fn.setreg(register, saved)
return result
end
local get_selected_text = function()
if vim.fn.mode() ~= 'v' then return vim.fn.expand '<cword>' end
return with_saved_register('v', function()
vim.cmd [[noautocmd sil norm "vy]]
return vim.fn.getreg 'v'
end)
end
local custom = { local custom = {
all_files = function() all_files = function()

View file

@ -0,0 +1,43 @@
local M = {}
-- Flip function arguments.
--
-- flip(f)(a, b) == f(b, a)
--
M.flip = function(f)
return function(a, b)
return f(b, a)
end
end
-- Partial function application:
--
-- partial(f, x)(...) == f(x, ...)
--
M.partial = function(f, x)
return function(...)
return f(x, ...)
end
end
-- Perform `func` (which can freely use register `reg`) and make sure `reg`
-- is restored afterwards.
M.with_saved_register = function(reg, func)
local saved = vim.fn.getreg(reg)
local result = func()
vim.fn.setreg(reg, saved)
return result
end
-- Get selected text, or word under cursor if not in visual mode.
M.get_selected_text = function()
if vim.fn.mode() ~= 'v' then return vim.fn.expand '<cword>' end
return M.with_saved_register('v', function()
vim.cmd [[noautocmd sil norm "vy]]
return vim.fn.getreg 'v'
end)
end
return M