Skip to content

Commit

Permalink
vim: factor out reusable functions into a separate module
Browse files Browse the repository at this point in the history
  • Loading branch information
fschauen committed Jul 15, 2023
1 parent d845b74 commit 3670b76
Show file tree
Hide file tree
Showing 3 changed files with 46 additions and 20 deletions.
7 changes: 2 additions & 5 deletions config/nvim/lua/user/plugins/completion.lua
Original file line number Diff line number Diff line change
@@ -1,11 +1,8 @@
local config = function()
local cmp = require('cmp')

-- flip(f)(a, b) == f(b, a)
local flip = function(f) return function(a, b) return f(b, a) end end

-- partial(f, x)(...) == f(x, ...)
local partial = function(f, x) return function(...) return f(x, ...) end end
local partial = require('user.util').partial
local flip = require('user.util').flip

-- assign('i', { key = func, ... }) == { key = { i = func }, ... }
-- assign({'i', 'c'}, { key = func, ... }) == { key = { i = func, c = func }, ...}
Expand Down
16 changes: 1 addition & 15 deletions config/nvim/lua/user/plugins/telescope.lua
Original file line number Diff line number Diff line change
Expand Up @@ -103,21 +103,7 @@ local config = function()
telescope.load_extension 'file_browser'
telescope.load_extension 'fzf'

local with_saved_register = function(register, func)
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 get_selected_text = require('user.util').get_selected_text

local custom = {
all_files = function()
Expand Down
43 changes: 43 additions & 0 deletions config/nvim/lua/user/util.lua
Original file line number Diff line number Diff line change
@@ -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

0 comments on commit 3670b76

Please sign in to comment.