-
-
Notifications
You must be signed in to change notification settings - Fork 83
Expand file tree
/
Copy pathutils.lua
More file actions
110 lines (92 loc) · 2.43 KB
/
utils.lua
File metadata and controls
110 lines (92 loc) · 2.43 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
local wait = require('async.waits.wait')
local List = require('java-core.utils.list')
local M = {}
---Async vim.ui.select function
---@generic T
---@param prompt string
---@param values T[]
---@param format_item? fun(item: T): string
---@param opts? { return_one: boolean }
---@return T | nil
function M.select(prompt, values, format_item, opts)
opts = opts or { prompt_single = false }
return wait(function(callback)
if not opts.prompt_single and #values == 1 then
callback(values[1])
return
end
vim.ui.select(values, {
prompt = prompt,
format_item = format_item,
}, callback)
end)
end
--Sync vim.ui.select function
---@generic T
---@param prompt string
---@param values T[]
---@param format_item? fun(item: T, index: number): string
---@param opts? { return_one: boolean }
---@return T | nil
function M.select_sync(prompt, values, format_item, opts)
opts = opts or { prompt_single = false }
if not opts.prompt_single and #values == 1 then
return values[1]
end
local labels = { prompt }
for index, value in ipairs(values) do
table.insert(labels, format_item and format_item(value, index) or value)
end
local selected_index = vim.fn.inputlist(labels)
return values[selected_index]
end
---Async vim.ui.select function
---@generic T
---@param prompt string
---@param values T[]
---@param format_item? fun(item: T): string
---@return T[] | nil
function M.multi_select(prompt, values, format_item)
return wait(function(callback)
local wrapped_items = List:new(values):map(function(item, index)
return {
index = index,
is_selected = false,
value = item,
}
end)
local open_select
open_select = function()
vim.ui.select(wrapped_items, {
prompt = prompt,
format_item = function(item)
local prefix = item.is_selected and '* ' or ''
return prefix .. (format_item and format_item(item.value) or item.value)
end,
}, function(selected)
if not selected then
local selected_items = wrapped_items
:filter(function(item)
return item.is_selected
end)
:map(function(item)
return item.value
end)
callback(#selected_items > 0 and selected_items or nil)
return
end
wrapped_items[selected.index].is_selected = not wrapped_items[selected.index].is_selected
open_select()
end)
end
open_select()
end)
end
function M.input(prompt)
return wait(function(callback)
vim.ui.input({
prompt = prompt,
}, callback)
end)
end
return M