Repository navigation
Expand file tree
/
Copy pathbase_picker.lua
More file actions
1027 lines (924 loc) · 32.8 KB
/
Copy pathbase_picker.lua
File metadata and controls
1027 lines (924 loc) · 32.8 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
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
local config = require('opencode.config')
local util = require('opencode.util')
local Promise = require('opencode.promise')
---@class PickerAction
---@field key? OpencodeKeymapEntry|string The key binding for this action
---@field label string The display label for this action
---@field fn fun(selected: any|any[], opts: PickerOptions): any[]|Promise<any[]>? The action function
---@field reload? boolean Whether to reload the picker after action
---@field multi_selection? boolean Whether this action supports multi-selection
---@class PickerOptions
---@field items any[] The list of items to pick from
---@field format_fn fun(item: any, width?: number): PickerItem Function to format items for display
---@field actions table<string, PickerAction> Available actions for the picker
---@field callback fun(selected: any?) Callback when item is selected
---@field multi_select_fn? fun(selected: any[], opts: PickerOptions): any|Promise<any> Action for multiple items confirmed together
---@field title string|fun(): string The picker title
---@field width? number Optional width for the picker (defaults to config or current window width)
---@field multi_selection? table<string, boolean> Actions that support multi-selection
---@field preview? "file"|"custom"|"none"|false Preview mode: "file" for file preview, "custom" for custom preview via preview_fn, "none" or false to disable
---@field preview_fn? fun(item: any, target: PickerPreviewTarget): nil Custom preview function, called when preview = 'custom' and a selection changes
---@field layout_opts? OpencodeUIPickerConfig
---@field close? fun() Close the picker programmatically (set by the backend)
---@class PickerPreviewTarget
---@field get_bufnr fun(self: PickerPreviewTarget): integer?
---@field is_valid fun(self: PickerPreviewTarget): boolean
---@field set_lines fun(self: PickerPreviewTarget, lines: string[]): nil
---@field with_window fun(self: PickerPreviewTarget, fn: fun(): nil): nil
---@class TelescopeEntry
---@field value any
---@field display fun(entry: TelescopeEntry): string[]
---@field ordinal string
---@class FzfLuaOptions
---@field fn_fzf_index fun(line: string): integer?
---@class FzfAction
---@field fn fun(selected: string[], fzf_opts: FzfLuaOptions): nil|Promise<nil>
---@field header string
---@field reload boolean
---@class FzfLuaActions
---@field [string] FzfAction|fun(selected: string[], fzf_opts: FzfLuaOptions): nil
---@class MiniPickItem
---@field text string
---@field item any
---@class MiniPickSelected
---@field current MiniPickItem?
---@class PickerItemPart
---@field text string The text content
---@field highlight? string Optional highlight group
---@class PickerItem
---@field parts PickerItemPart[] Array of text parts with optional highlights
---@field to_string fun(self: PickerItem): string
---@field to_formatted_text fun(self: PickerItem): table
---@class SnacksPreview
---@field reset fun(self: SnacksPreview)
---@field set_lines? fun(self: SnacksPreview, lines: string[])
---@class SnacksPickerPreviewContext
---@field buf integer?
---@field win integer?
---@field item any?
---@field preview? SnacksPreview
---@class SnacksPickerLayout
---@field preset string
---@field config? fun(layout: any)
---@field preview? string|boolean
---@class SnacksPickerConfig
---@field title? string
---@field layout? SnacksPickerLayout|table
---@field finder? fun(): any[]
---@field matcher? table
---@field sort? table
---@field transform? fun(item: any, ctx: any)
---@field format? fun(item: any): table
---@field on_close? fun()
---@field actions table<string, fun(picker: any, item: any)>
---@field preview? 'file'|boolean|fun(ctx: SnacksPickerPreviewContext): boolean?
---@field win? {input: {keys: table<string, any>}}
---@class BasePicker
local M = {}
local picker = require('opencode.ui.picker')
---@param bufnr integer?
---@return PickerPreviewTarget
local function create_buffer_preview_target(bufnr)
return {
get_bufnr = function()
return bufnr
end,
is_valid = function()
return bufnr ~= nil and vim.api.nvim_buf_is_valid(bufnr)
end,
set_lines = function(_, lines)
if bufnr == nil or not vim.api.nvim_buf_is_valid(bufnr) then
return
end
local modifiable = vim.bo[bufnr].modifiable
vim.bo[bufnr].modifiable = true
vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
vim.bo[bufnr].modifiable = modifiable
end,
with_window = function(_, fn)
if bufnr == nil or not vim.api.nvim_buf_is_valid(bufnr) then
return
end
local win = vim.fn.bufwinid(bufnr)
if win ~= -1 then
vim.api.nvim_win_call(win, fn)
end
end,
}
end
---@param ctx SnacksPickerPreviewContext
---@return PickerPreviewTarget
local function create_snacks_preview_target(ctx)
return {
get_bufnr = function()
return ctx.buf
end,
is_valid = function()
return ctx.buf ~= nil and vim.api.nvim_buf_is_valid(ctx.buf)
end,
set_lines = function(_, lines)
if ctx.preview and ctx.preview.set_lines then
ctx.preview:set_lines(lines)
elseif ctx.buf and vim.api.nvim_buf_is_valid(ctx.buf) then
create_buffer_preview_target(ctx.buf):set_lines(lines)
end
end,
with_window = function(_, fn)
if ctx.win and vim.api.nvim_win_is_valid(ctx.win) then
vim.api.nvim_win_call(ctx.win, fn)
return
end
create_buffer_preview_target(ctx.buf):with_window(fn)
end,
}
end
---Build title with action legend
---@param base_title string The base title
---@param actions table<string, PickerAction> The available actions
---@param support_multi? boolean Whether multi-selection is supported
---@return string title The formatted title with action legend
local function build_title(base_title, actions, support_multi)
local icons = require('opencode.ui.icons')
local legend = {}
for _, action in pairs(actions) do
if action.key and action.key[1] then
local label = action.label .. (action.multi_selection and support_multi ~= false and '*' or '')
table.insert(legend, action.key[1] .. ' ' .. label)
end
end
return base_title .. (#legend > 0 and icons.get('separator') .. table.concat(legend, icons.get('separator')) or '')
end
---Telescope UI implementation
---@param opts PickerOptions The picker options
local function telescope_ui(opts)
---@diagnostic disable-next-line: unresolved-require
local pickers = require('telescope.pickers') --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local finders = require('telescope.finders') --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local conf = require('telescope.config').values --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local actions = require('telescope.actions') --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local action_state = require('telescope.actions.state') --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local action_utils = require('telescope.actions.utils') --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local entry_display = require('telescope.pickers.entry_display') --[[@as any]]
-- Create displayer dynamically based on number of parts
---@param picker_item PickerItem
---@return fun(formatted: table): string
local function create_displayer(picker_item)
local items = {}
for _ in ipairs(picker_item.parts) do
table.insert(items, {})
end
return entry_display.create({
separator = ' ',
items = items,
})
end
local current_picker
---Creates entry maker function for telescope
---@param item any
---@return TelescopeEntry
local function make_entry(item)
local picker_item = opts.format_fn(item)
local displayer = create_displayer(picker_item)
local entry = {
value = item,
display = function(telescope_entry)
local formatted = opts.format_fn(telescope_entry.value):to_formatted_text()
return displayer(formatted)
end,
ordinal = picker_item:to_string(),
}
if type(item) == 'table' then
entry.path = item.file or item.file_path or item.path or item.filename
entry.lnum = item.line or item.lnum
entry.col = item.column or item.col
-- Support line ranges for preview highlighting
if item.end_pos and type(item.end_pos) == 'table' and item.end_pos[1] then
entry.lnend = item.end_pos[1]
end
elseif type(item) == 'string' then
entry.path = item
end
return entry
end
---@return unknown
local function refresh_picker()
return current_picker
and current_picker:refresh(
finders.new_table({ results = opts.items, entry_maker = make_entry }),
{ reset_prompt = false }
)
end
local selection_made = false
current_picker = pickers.new({}, {
prompt_title = opts.title,
finder = finders.new_table({ results = opts.items, entry_maker = make_entry }),
sorter = conf.generic_sorter({}),
previewer = (function()
if opts.preview == 'file' then
---@diagnostic disable-next-line: unresolved-require
local previewers = require('telescope.previewers') --[[@as any]]
return previewers.vim_buffer_vimgrep.new({})
elseif opts.preview == 'custom' and opts.preview_fn then
---@diagnostic disable-next-line: unresolved-require
local previewers = require('telescope.previewers') --[[@as any]]
local preview_fn = opts.preview_fn
return previewers.new_buffer_previewer({
define_preview = function(self, entry)
if not entry then
return
end
preview_fn(entry.value, create_buffer_preview_target(self.state.bufnr))
end,
})
else
return nil
end
end)(),
layout_config = opts.width and {
width = opts.width + 7, -- extra space for telescope UI
} or nil,
attach_mappings = function(prompt_bufnr, map)
opts.close = function()
selection_made = true
actions.close(prompt_bufnr)
end
actions.select_default:replace(function()
selection_made = true
local multi_selection = {}
action_utils.map_selections(prompt_bufnr, function(entry)
table.insert(multi_selection, entry.value)
end)
if #multi_selection > 1 and opts.multi_select_fn then
actions.close(prompt_bufnr)
opts.multi_select_fn(multi_selection, opts)
return
end
local selection = action_state.get_selected_entry()
actions.close(prompt_bufnr)
if selection then
opts.callback(selection.value)
end
end)
actions.close:enhance({
post = function()
if not selection_made then
vim.schedule(function()
opts.callback(nil)
end)
end
end,
})
for _, action in pairs(opts.actions) do
if action.key and action.key[1] then
local modes = action.key.mode or { 'i', 'n' }
if type(modes) == 'string' then
modes = { modes }
end
local action_fn = function()
local items_to_process
if action.multi_selection then
local multi_selection = {}
action_utils.map_selections(prompt_bufnr, function(entry, _index)
table.insert(multi_selection, entry.value)
end)
if #multi_selection > 0 then
items_to_process = multi_selection
else
local selection = action_state.get_selected_entry()
items_to_process = selection and selection.value or nil
end
else
local selection = action_state.get_selected_entry()
items_to_process = selection and selection.value or nil
end
if items_to_process then
local new_items = action.fn(items_to_process, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
if #resolved_items == 0 and opts.close then
opts.close()
else
opts.items = resolved_items
refresh_picker()
end
end
end)
end
end
for _, mode in ipairs(modes) do
map(mode, action.key[1], action_fn)
end
end
end
return true
end,
})
current_picker:find()
end
---FZF-Lua UI implementation
---@param opts PickerOptions The picker options
local function fzf_ui(opts)
---@diagnostic disable-next-line: unresolved-require
local fzf_lua = require('fzf-lua') --[[@as any]]
local function finder(fzf_cb, width)
for idx, item in ipairs(opts.items) do
local line_str = opts.format_fn(item, width):to_string()
-- Prepend index with SOH delimiter for reliable matching
local indexed_line = tostring(idx) .. '\x01' .. line_str
-- For file preview support, append file:line:col format
-- fzf-lua's builtin previewer automatically parses this format
if opts.preview == 'file' and type(item) == 'table' then
local file_path = item.file_path or item.path or item.filename or item.file
local line = item.line or item.lnum
local col = item.column or item.col
if file_path then
-- fzf-lua parses "path:line:col:" format for preview positioning
local pos_info = file_path
if line then
pos_info = pos_info .. ':' .. tostring(line)
if col then
pos_info = pos_info .. ':' .. tostring(col)
end
pos_info = pos_info .. ':'
end
-- Append position info after nbsp separator (fzf-lua standard)
-- nbsp is U+2002 EN SPACE, not regular tab
local nbsp = '\xe2\x80\x82'
indexed_line = indexed_line .. nbsp .. pos_info
end
end
fzf_cb(indexed_line)
end
fzf_cb()
end
local preview_fn = opts.preview_fn
local has_custom_preview = opts.preview == 'custom' and preview_fn ~= nil
local format_width
-- defer item processing until preview if using custom preview_fn
-- so we can pass the width of the fzf window to the format_fn for optimal formatting
local width_callback = has_custom_preview
and function(_, _, _, ctx)
format_width = (ctx.env.FZF_COLUMNS or vim.o.columns) - (ctx.env.FZF_PREVIEW_COLUMNS or 0)
format_width = math.min(format_width, vim.o.columns - 8)
end
or nil
---@return table
local function create_fzf_config()
local has_multi_action = util.some(opts.actions, function(action)
return action.multi_selection
end)
return {
fzf_cli_args = width_callback and (function()
---@diagnostic disable-next-line: unresolved-require
local libuv = require('fzf-lua.libuv') --[[@as any]]
---@diagnostic disable-next-line: unresolved-require
local shell = require('fzf-lua.shell') --[[@as any]]
return '--bind=' .. libuv.shellescape('start:+transform:' .. shell.stringify_data(width_callback, opts))
end)() or nil,
winopts = opts.width and {
width = opts.width + 8, -- extra space for fzf UI
} or nil,
fzf_opts = {
['--prompt'] = opts.title .. ' > ',
['--multi'] = has_multi_action and true or nil,
['--with-nth'] = '2..', -- hide the index prefix from display
['--delimiter'] = '\x01', -- use SOH as delimiter (invisible char)
['--read0'] = true,
},
_headers = { 'actions' },
previewer = (function()
if opts.preview == 'file' then
return 'builtin'
elseif opts.preview == 'custom' and preview_fn then
local custom_preview_fn = preview_fn
return {
_ctor = function()
---@diagnostic disable-next-line: unresolved-require
local builtin = require('fzf-lua.previewer.builtin') --[[@as any]]
local previewer = builtin.buffer_or_file:extend()
function previewer:populate_preview_buf(entry_str)
if not self.win or not self.win:validate_preview() then
return
end
local idx_str = entry_str:match('^(%d+)\x01')
local idx = tonumber(idx_str)
if not idx or not opts.items[idx] then
return
end
-- Create scratch buffer, attach to preview window first
-- so preview_fn can use bufwinid for window-local ops (folds)
local buf = self:get_tmp_buffer()
self:set_preview_buf(buf, true) -- min_winopts=true
custom_preview_fn(opts.items[idx], create_buffer_preview_target(buf))
end
return previewer
end,
}
else
return nil
end
end)(),
fn_fzf_index = function(line)
-- Extract the numeric index prefix before the SOH delimiter
local idx_str = line:match('^(%d+)\x01')
if idx_str then
return tonumber(idx_str)
end
return nil
end,
}
end
---Reopen fzf-lua to reflect updated picker items.
local function refresh_fzf()
vim.schedule(function()
fzf_ui(opts)
end)
end
local closed = false
opts.close = function()
if closed then
return
end
closed = true
vim.schedule(function()
local ok, fzf_win = pcall(require, 'fzf-lua.win')
if ok and fzf_win.__SELF then
local win = fzf_win.__SELF()
if win then
win:close()
end
end
opts.callback(nil)
end)
end
---@type FzfLuaActions
local actions_config = {
['default'] = function(selected, fzf_opts)
if closed then
return
end
if not selected or #selected == 0 then
opts.callback(nil)
return
end
if #selected > 1 and opts.multi_select_fn then
local multi_selection = {}
for _, sel in ipairs(selected) do
local idx = fzf_opts.fn_fzf_index(sel --[[@as string]])
if idx and opts.items[idx] then
table.insert(multi_selection, opts.items[idx])
end
end
opts.multi_select_fn(multi_selection, opts)
return
end
local idx = fzf_opts.fn_fzf_index(selected[1] --[[@as string]])
if idx and opts.items[idx] then
opts.callback(opts.items[idx])
end
end,
['esc'] = function()
if closed then
return
end
opts.callback(nil)
end,
}
for _, action in pairs(opts.actions) do
if action.key and action.key[1] then
---@diagnostic disable-next-line: unresolved-require
local fzf_utils = require('fzf-lua.utils') --[[@as any]]
local key = fzf_utils.neovim_bind_to_fzf(action.key[1])
actions_config[key] = {
fn = function(selected, fzf_opts)
if not selected or #selected == 0 then
return
end
local items_to_process
if action.multi_selection and #selected > 1 then
items_to_process = {}
for _, sel in ipairs(selected) do
local idx = fzf_opts.fn_fzf_index(sel --[[@as string]])
if idx and opts.items[idx] then
table.insert(items_to_process, opts.items[idx])
end
end
else
local idx = fzf_opts.fn_fzf_index(selected[1] --[[@as string]])
if idx and opts.items[idx] then
items_to_process = opts.items[idx]
end
end
if items_to_process then
local new_items = action.fn(items_to_process, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
---@cast resolved_items any[]
if #resolved_items == 0 and opts.close then
opts.close()
else
opts.items = resolved_items
refresh_fzf()
end
end
end)
end
end,
header = action.label,
reload = action.reload or false,
}
end
end
local fzf_config = create_fzf_config()
fzf_config.actions = actions_config
fzf_lua.fzf_exec(function(fzf_cb)
if width_callback then
vim.wait(1000, function()
return format_width
end)
end
finder(fzf_cb, format_width)
end, fzf_config)
end
---Mini.pick UI implementation
---@param opts PickerOptions The picker options
local function mini_pick_ui(opts)
---@diagnostic disable-next-line: unresolved-require
local mini_pick = require('mini.pick') --[[@as any]]
---@type MiniPickItem[]
local items = vim.tbl_map(function(item)
return { text = opts.format_fn(item):to_string(), item = item }
end, opts.items)
local mappings = {}
opts.close = function()
mini_pick.stop()
end
for action_name, action in pairs(opts.actions) do
if action.key and action.key[1] then
mappings[action_name] = {
char = action.key[1],
func = function()
local current = mini_pick.get_picker_matches().current
if current and current.item then
-- Mini.pick doesn't have native multi-selection, we fallback single selection
local new_items = action.fn(current.item, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
if #resolved_items == 0 and opts.close then
opts.close()
else
opts.items = resolved_items
mini_pick_ui(opts)
end
end
end)
end
return true
end,
}
end
end
local selection_made = false
mini_pick.start({
window = opts.width and {
config = {
width = opts.width + 2, -- extra space for mini.pick UI
},
} or nil,
source = {
items = items,
name = opts.title,
choose = function(selected)
if selected and selected.item and opts.callback then
selection_made = true
opts.callback(selected.item)
end
return false
end,
on_done = function()
if not selection_made and opts.callback then
vim.schedule(function()
opts.callback(nil)
end)
end
end,
},
mappings = mappings,
})
end
---Snacks picker UI implementation
---@param opts PickerOptions The picker options
local function snacks_picker_ui(opts)
---@diagnostic disable-next-line: unresolved-require
local Snacks = require('snacks') --[[@as any]]
local preview_fn = opts.preview_fn
local has_custom_preview = opts.preview == 'custom' and preview_fn ~= nil
local has_preview = opts.preview == 'file' or has_custom_preview
local title = type(opts.title) == 'function' and opts.title() or opts.title
---@cast title string
local layout_opts = opts.layout_opts and opts.layout_opts.snacks_layout or nil
local selection_made = false
---@type SnacksPickerLayout
local default_layout = {
preset = has_custom_preview and 'default' or 'select',
config = function(layout)
local width = opts.width and (opts.width + 3) or nil -- extra space for snacks UI
if not has_preview then
layout.layout.width = width
layout.layout.max_width = width
layout.layout.min_width = width
end
end,
}
if opts.preview == 'file' then
default_layout.preview = 'main'
elseif not has_preview then
default_layout.preview = false
end
---@type SnacksPickerConfig
local snack_opts = {
title = title,
layout = layout_opts or default_layout,
finder = function()
return opts.items
end,
matcher = {
sort_empty = false,
},
sort = {
fields = { 'score:desc', 'idx' },
},
transform = function(item, ctx)
if type(item) == 'table' then
if item.idx == nil then
item.idx = ctx.idx
end
if item.favorite_index and item.favorite_index < 999 then
item.score_add = (item.score_add or 0) + (1000 - item.favorite_index) * 1000
end
if not item.text then
local picker_item = opts.format_fn(item)
item.text = picker_item:to_string()
end
end
end,
format = function(item)
return opts.format_fn(item):to_formatted_text()
end,
on_close = function()
if not selection_made then
vim.schedule(function()
opts.callback(nil)
end)
end
end,
actions = {
confirm = function(_picker, item)
selection_made = true
local multi_selection = _picker:selected({ fallback = true })
if #multi_selection > 1 and opts.multi_select_fn then
_picker:close()
vim.schedule(function()
opts.multi_select_fn(multi_selection, opts)
end)
return
end
_picker:close()
if item then
vim.schedule(function()
opts.callback(item)
end)
end
end,
},
}
if opts.preview == 'file' then
snack_opts.preview = 'file'
elseif has_custom_preview then
snack_opts.preview = function(ctx)
if ctx.item and ctx.preview and preview_fn then
ctx.preview:reset()
preview_fn(ctx.item, create_snacks_preview_target(ctx))
end
end
else
snack_opts.preview = function()
return false
end
end
snack_opts.win = { input = { keys = {} } }
local input_keys = snack_opts.win.input.keys
for action_name, action in pairs(opts.actions) do
if action.key and action.key[1] then
input_keys[action.key[1]] = { action_name, mode = action.key.mode or 'i' }
snack_opts.actions[action_name] = function(_picker, item)
if not opts.close then
opts.close = function()
selection_made = true
_picker:close()
end
end
if item then
local items_to_process
if action.multi_selection then
local selected_items = _picker:selected({ fallback = true })
items_to_process = #selected_items > 1 and selected_items or item
else
items_to_process = item
end
if not action.reload then
selection_made = true
_picker:close()
end
vim.schedule(function()
local new_items = action.fn(items_to_process, opts)
Promise.wrap(new_items):and_then(function(resolved_items)
if action.reload and resolved_items then
if #resolved_items == 0 and opts.close then
opts.close()
else
opts.items = resolved_items
_picker:refresh()
_picker:find()
end
end
end)
end)
end
end
end
end
---@generic T
Snacks.picker.pick(snack_opts)
end
---vim.ui.select UI implementation
---@param opts PickerOptions The picker options
local function select_picker_ui(opts)
vim.ui.select(opts.items, {
format_item = function(item)
return opts.format_fn(item, opts.width):to_string()
end,
prompt = opts.title --[[@as string]],
}, opts.callback)
end
---@param text? string
---@param width integer
---@param opts? {align?: "left" | "right" | "center", truncate?: boolean}
function M.align(text, width, opts)
text = text or ''
opts = opts or {}
opts.align = opts.align or 'left'
local tw = vim.api.nvim_strwidth(text)
if tw > width then
return opts.truncate and (vim.fn.strcharpart(text, 0, width - 1) .. '…') or text
end
local left = math.floor((width - tw) / 2)
local right = width - tw - left
if opts.align == 'left' then
left, right = 0, width - tw
elseif opts.align == 'right' then
left, right = width - tw, 0
end
return (' '):rep(left) .. text .. (' '):rep(right)
end
---Creates a generic picker item that can format itself for different pickers
---@param parts PickerItemPart[] Array of text parts with optional highlights
---@return PickerItem
function M.create_picker_item(parts)
local item = {
parts = parts,
}
---@return string
function item:to_string()
local texts = {}
for _, part in ipairs(self.parts) do
table.insert(texts, part.text)
end
return table.concat(texts, ' ')
end
---@return table
function item:to_formatted_text()
local formatted = {}
for _, part in ipairs(self.parts) do
if part.highlight then
table.insert(formatted, { ' ' .. part.text, part.highlight })
else
table.insert(formatted, { part.text })
end
end
return formatted
end
return item
end
---Helper function to create a simple picker item with content, time, and debug text
---This is a convenience wrapper around create_picker_item for common use cases
---@param text string Main content text
---@param time? number Optional time to format
---@param debug_text? string Optional debug text to append
---@param width? number Optional width override
---@return PickerItem
function M.create_time_picker_item(text, time, debug_text, width)
local time_width = time and #util.format_time(time) + 1 or 0
local debug_width = config.debug.show_ids and debug_text and #debug_text + 1 or 0
local item_width = width or vim.api.nvim_win_get_width(0)
local text_width = item_width - (debug_width + time_width)
local parts = {
{
text = M.align(text, text_width --[[@as integer]], { truncate = true }),
},
}
if time then
table.insert(parts, {
text = M.align(util.format_time(time), time_width, { align = 'right' }),
highlight = 'OpencodePickerTime',
})
end
if config.debug.show_ids and debug_text then
table.insert(parts, {
text = debug_text,
highlight = 'OpencodeDebugText',
})
end
return M.create_picker_item(parts)
end
---Generic picker that abstracts common logic for different picker UIs
---@param opts PickerOptions The picker options
---@return boolean success Whether the picker was successfully launched
function M.pick(opts)
local picker_type = picker.get_best_picker()
if not opts.width then
opts.width = config.ui.picker_width
end
-- picker_width = false means "use picker backend defaults, no override"
if opts.width == false then
opts.width = nil
end
-- Resolve relative width (0 < w <= 1) to absolute columns so that
-- format functions and all picker backends receive a consistent value.
if opts.width and opts.width > 0 and opts.width <= 1 then
opts.width = math.floor(vim.o.columns * opts.width)
end
-- When width is nil (picker_width = false or unset), derive a content width
-- from the picker backend's default window size so format functions can
-- produce correctly-sized output that fills the backend's content area.
local format_width = opts.width
if not format_width then
if picker_type == 'fzf' then
-- Read fzf-lua's effective winopts.width (respects user customization).
local fzf_win_width = 0.8
local ok, fzf_config = pcall(require, 'fzf-lua.config')
if ok and fzf_config and fzf_config.globals and fzf_config.globals.winopts then
fzf_win_width = fzf_config.globals.winopts.width or fzf_win_width
end
-- Resolve fraction to absolute columns
if fzf_win_width > 0 and fzf_win_width <= 1 then
fzf_win_width = math.floor(vim.o.columns * fzf_win_width)
end
-- Subtract the same chrome offset used when we set winopts ourselves (+8),
-- which covers borders, padding, and fzf's pointer indicator.
format_width = fzf_win_width - 8
else
format_width = math.floor(vim.o.columns * 0.8)
end
end
local has_preview = opts.preview == 'file' or opts.preview == 'custom'
if picker_type == 'fzf' and has_preview and format_width then
local window_cols = format_width + 8
-- Match fzf-lua's default right:60% preview split so item formatting
-- targets the visible list pane instead of the full window width.
format_width = math.floor(window_cols * 0.4) - 4
end
local original_format_fn = opts.format_fn
opts.format_fn = function(item, width)
return original_format_fn(item, width or format_width)
end