-
Notifications
You must be signed in to change notification settings - Fork 239
Expand file tree
/
Copy pathbuiltin.lua
More file actions
1999 lines (1858 loc) · 68.8 KB
/
builtin.lua
File metadata and controls
1999 lines (1858 loc) · 68.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 path = require "fzf-lua.path"
local shell = require "fzf-lua.shell"
local utils = require "fzf-lua.utils"
local libuv = require "fzf-lua.libuv"
local Object = require "fzf-lua.class"
---@diagnostic disable-next-line: deprecated
local uv = vim.uv or vim.loop
local api = vim.api
local fn = vim.fn
---@class fzf-lua.TSContext
---@field private _winids table<integer, integer>
local TSContext = {}
---@param opts TSContext.UserConfig
---@return boolean
function TSContext.setup(opts)
if TSContext._setup then return true end
if not package.loaded["treesitter-context"] then
return false
end
-- Our temp nvim-treesitter-context config
TSContext._setup_opts = {}
for k, v in pairs(opts) do
TSContext._setup_opts[k] = { v }
end
local config = require("treesitter-context.config")
TSContext._config = utils.tbl_deep_clone(config)
for k, v in pairs(TSContext._setup_opts) do
v[2] = config[k]
config[k] = v[1]
end
TSContext._winids = {}
TSContext._setup = true
return true
end
function TSContext.deregister()
if not TSContext._setup then return end
for winid, _ in pairs(TSContext._winids) do
TSContext.close(winid)
end
local config = require("treesitter-context.config")
for k, v in pairs(TSContext._setup_opts) do
config[k] = v[2]
end
TSContext._config = nil
TSContext._winids = nil
TSContext._setup = nil
end
---@param winid integer
---@return boolean?
function TSContext.is_attached(winid)
if not TSContext._setup then return false end
return TSContext._winids[winid] and true or false
end
---@param winid integer
function TSContext.close(winid)
if not TSContext._setup then return end
require("treesitter-context.render").close(winid)
TSContext._winids[winid] = nil
end
---@param winid integer
---@param bufnr integer
function TSContext.toggle(winid, bufnr)
if not TSContext._setup then return end
if TSContext.is_attached(winid) then
TSContext.close(winid)
else
TSContext.update(winid, bufnr)
end
end
function TSContext.inc_dec_maxlines(num, winid, bufnr)
if not TSContext._setup then return end
local n = tonumber(num)
if not n then return end
local config = require("treesitter-context.config")
local max_lines = config.max_lines or 0
config.max_lines = math.max(0, max_lines + n)
utils.info("treesitter-context `max_lines` set to %d.", config.max_lines)
if TSContext.is_attached(winid) then
for _, t in ipairs({ 0, 20 }) do
vim.defer_fn(function() TSContext.update(winid, bufnr) end, t)
end
end
end
---@alias TSContext.UserConfig table
---@param winid integer
---@param bufnr integer
---@param opts? TSContext.UserConfig
function TSContext.update(winid, bufnr, opts)
opts = opts or {}
if not TSContext.setup(opts) then return end
assert(not api.nvim_win_is_valid(winid) or bufnr == api.nvim_win_get_buf(winid))
local render = require("treesitter-context.render")
local context_ranges, context_lines = require("treesitter-context.context").get(winid)
if not context_ranges or #context_ranges == 0 then
TSContext.close(winid)
else
assert(context_lines)
local function open()
if api.nvim_buf_is_valid(bufnr) and api.nvim_win_is_valid(winid) then
-- ensure context win is above
local fix = function(win, zindex)
if win and api.nvim_win_is_valid(win) then
utils.win_set_config(win, { zindex = zindex })
-- noautocmd don't ignore WinResized/WinScrolled
utils.wo[win].eventignorewin = "WinResized"
end
end
api.nvim_win_call(winid, function()
render.open(winid, context_ranges, context_lines)
TSContext.window_contexts = TSContext.window_contexts or
utils.upvfind(render.open, "window_contexts")
if not TSContext.window_contexts then return end
local window_context = TSContext.window_contexts[winid]
if not window_context then return end
fix(window_context.context_winid, TSContext.zindex)
fix(window_context.gutter_winid, TSContext.zindex)
end)
TSContext._winids[winid] = bufnr
end
end
-- NOTE: no longer required since adding `eventignore` to `FzfWin:set_winopts`
-- if TSContext.is_attached(winid) == bufnr then
open()
-- else
-- -- HACK: but the entire nvim-treesitter-context is essentially a hack
-- -- https://github.com/ibhagwan/fzf-lua/issues/1552#issuecomment-2525456813
-- for _, t in ipairs({ 0, 20 }) do
-- vim.defer_fn(function() open() end, t)
-- end
-- end
end
end
local Previewer = {}
---@class fzf-lua.previewer.Builtin : fzf-lua.Object,{}
---@field last_entry? string
---@field type "builtin"
---@field new function
---@field setup_opts function
---@field opts table
---@field win fzf-lua.Win
---@field delay integer
---@field title any
---@field title_pos "center"|"left"|"right"
---@field title_fnamemodify fun(title: string, width: integer?): string
---@field render_markdown table
---@field snacks_image table
---@field winopts fzf-lua.config.PreviewerWinopts
---@field syntax boolean
---@field syntax_delay integer
---@field syntax_limit_b integer
---@field syntax_limit_l integer
---@field limit_b integer
---@field _ts_limit_b_per_line integer
---@field treesitter table
---@field toggle_behavior "default"|"extend"
---@field winopts_orig table
---@field extensions { [string]: string[]? }
---@field ueberzug_scaler "crop"|"distort"|"contain"|"fit_contain"|"cover"|"forced_cover"
---@field cached_bufnrs table<integer, [integer, integer]|true?> items are cached_pos
---@field cached_buffers table<string, fzf-lua.buffer_or_file.Bcache?>
---@field listed_buffers table<integer, boolean?>
---@field clear_on_redraw boolean?
---@field timers? table<string, uv.uv_timer_t?>
---@field orig_pos? [integer, integer]
Previewer.base = Object:extend()
---@param o table
---@param opts table
---@return fzf-lua.previewer.Builtin
function Previewer.base:new(o, opts)
local default = vim.F.if_nil
o = o or {}
self.type = "builtin"
self.opts = opts
self.title_fnamemodify = o.title_fnamemodify
self.render_markdown = type(o.render_markdown) == "table" and o.render_markdown or {}
self.render_markdown.filetypes =
type(self.render_markdown.filetypes) == "table" and self.render_markdown.filetypes or {}
self.snacks_image = type(o.snacks_image) == "table" and o.snacks_image or {}
self.syntax = default(o.syntax, true)
self.syntax_delay = tonumber(default(o.syntax_delay, 0))
self.syntax_limit_b = tonumber(default(o.syntax_limit_b, 1024 * 1024))
self.syntax_limit_l = tonumber(default(o.syntax_limit_l, 0))
self.limit_b = tonumber(default(o.limit_b, 1024 * 1024 * 10))
self._ts_limit_b_per_line = tonumber(default(o._ts_limit_b_per_line, 1000))
self.treesitter = type(o.treesitter) == "table" and o.treesitter or {}
self.toggle_behavior = o.toggle_behavior
self.winopts_orig = {}
-- convert extension map to lower case
if o.extensions then
self.extensions = {}
for k, v in pairs(o.extensions) do
self.extensions[k:lower()] = v
end
end
-- validate the ueberzug image scaler
local uz_scalers = {
["crop"] = "crop",
["distort"] = "distort",
["contain"] = "contain",
["fit_contain"] = "fit_contain",
["cover"] = "cover",
["forced_cover"] = "forced_cover",
}
self.ueberzug_scaler = o.ueberzug_scaler and uz_scalers[o.ueberzug_scaler]
if o.ueberzug_scaler and not self.ueberzug_scaler then
utils.warn(("Invalid ueberzug image scaler '%s', option will be omitted.")
:format(o.ueberzug_scaler))
end
-- cached buffers
self.cached_bufnrs = {}
self.cached_buffers = {}
-- store currently listed buffers, this helps us determine which buffers
-- navigated with 'vim.lsp.util.show_document' we can safely unload
-- since show_document reuses buffers and I couldn't find a better way
-- to determine if the destination buffer was listed prior to the jump
local is_listed = function(b) return fn.buflisted(b) == 1 end ---@type fun(b: integer): boolean
self.listed_buffers = utils.list_to_map(vim.tbl_map(is_listed, api.nvim_list_bufs()))
return self
end
---@param opts table
---@return table
function Previewer.base:setup_opts(opts)
-- Set the preview command line
opts.preview = self:cmdline()
opts.fzf_opts["--preview-window"] = self:preview_window()
-- fzf 0.40 added 'zero' event for when there's no match
-- clears the preview when there are no matching entries
if utils.has(opts, "fzf", { 0, 40 }) then
table.insert(opts._fzf_cli_args, "--bind=" .. libuv.shellescape("zero:+" .. self:zero()))
end
return opts
end
---@param do_not_clear_cache boolean?
function Previewer.base:close(do_not_clear_cache)
TSContext.deregister()
self:restore_winopts()
self:clear_preview_buf()
if not do_not_clear_cache then
self:clear_cached_buffers()
end
self.winopts_orig = {}
end
function Previewer.base:gen_winopts()
local winopts = { wrap = self.win.preview_wrap }
return vim.tbl_extend("keep", winopts, self.winopts)
end
function Previewer.base:backup_winopts()
if rawequal(next(self.winopts_orig), nil) then
self.winopts_orig = self.win:get_winopts(self.win.src_winid, self:gen_winopts())
end
end
function Previewer.base:restore_winopts()
self.win:set_winopts(self.win.preview_winid, self.winopts_orig)
end
function Previewer.base:set_style_winopts()
-- NOTE: `true` to ignore events for initial TSContext.update
self.win:set_winopts(self.win.preview_winid, self:gen_winopts(), true)
end
---@param win integer
function Previewer.base:reset_winhl(win)
local hls = self.win.hls
local winopts = self:gen_winopts()
self.win:reset_winhl(win, winopts.winhl or winopts.winhighlight or {
Normal = hls.preview_normal,
NormalFloat = hls.preview_normal,
FloatBorder = hls.preview_border,
CursorLine = hls.cursorline,
CursorLineNr = hls.cursorlinenr,
})
end
---@diagnostic disable-next-line: unused
---@return integer
function Previewer.base:get_tmp_buffer()
local tmp_buf = api.nvim_create_buf(false, true)
vim.bo[tmp_buf].modeline = true
vim.bo[tmp_buf].modifiable = true
vim.bo[tmp_buf].bufhidden = "wipe"
return tmp_buf
end
---@param bufnr? integer
---@param del_cached? boolean
function Previewer.base:safe_buf_delete(bufnr, del_cached)
-- can be nil after closing preview with <F4>
if not bufnr then return end
assert(type(bufnr) == "number" and bufnr > 0)
if self.listed_buffers[bufnr] then
-- print("safe_buf_delete LISTED", bufnr)
return
elseif not api.nvim_buf_is_valid(bufnr) then
-- print("safe_buf_delete INVALID", bufnr)
return
elseif not del_cached and self.cached_bufnrs[bufnr] then
-- print("safe_buf_delete CACHED", bufnr)
return
end
-- print("safe_buf_delete DELETE", bufnr)
-- delete buffer marks
api.nvim_buf_call(bufnr, function()
vim.cmd([[delm \"]])
end)
-- delete the buffer
api.nvim_buf_delete(bufnr, { force = true })
end
---@param newbuf integer
---@param min_winopts boolean?
---@param no_wipe boolean?
function Previewer.base:set_preview_buf(newbuf, min_winopts, no_wipe)
if not self.win or not self.win:validate_preview() then return end
-- Set the preview window to the new buffer
local curbuf = api.nvim_win_get_buf(self.win.preview_winid)
if curbuf == newbuf then return end
-- Something went terribly wrong
assert(curbuf ~= newbuf)
utils.win_set_buf_noautocmd(self.win.preview_winid, newbuf)
-- to make gc work, don't reference `win._previewer` in a callback
local winid = self.win.fzf_winid
vim.keymap.set("", "i", function()
api.nvim_set_current_win(winid)
vim.cmd("startinsert")
end, { buffer = newbuf })
self.preview_bufnr = newbuf
-- set preview window options
-- sets the style defined by `winopts.preview.winopts`
self:set_style_winopts()
if min_winopts then
-- removes 'number', 'signcolumn', 'cursorline', etc
self.win:set_style_minimal(self.win.preview_winid, true)
end
if not no_wipe then
-- although the buffer has 'bufhidden:wipe' it sometimes doesn't
-- get wiped when pressing `ctrl-g` too quickly
self:safe_buf_delete(curbuf)
end
end
---@param bufnr integer
---@param key string
---@param min_winopts boolean?
---@return fzf-lua.buffer_or_file.Bcache
function Previewer.base:cache_buffer(bufnr, key, min_winopts)
local cached = self.cached_buffers[key]
if cached then
if cached.bufnr == bufnr then
-- already cached, nothing to do
return cached
else
-- new cached buffer for key, wipe current cached buf
self.cached_bufnrs[cached.bufnr] = nil
self:safe_buf_delete(cached.bufnr)
end
end
self.cached_bufnrs[bufnr] = true
self.cached_buffers[key] = { bufnr = bufnr, min_winopts = min_winopts }
-- remove buffer auto-delete since it's now cached
vim.bo[bufnr].bufhidden = "hide"
return self.cached_buffers[key]
end
function Previewer.base:clear_cached_buffers()
-- clear the buffer cache
for _, c in pairs(self.cached_buffers) do
self:safe_buf_delete(c.bufnr, true)
end
self.cached_bufnrs = {}
self.cached_buffers = {}
end
---@param newbuf boolean?
---@return integer?
function Previewer.base:clear_preview_buf(newbuf)
local retbuf = nil
if ((self.win and self.win._reuse) or newbuf)
-- Attach a temp buffer to the window when reusing (`ctrl-g`)
-- so we don't invalidate the window when deting the buffer
-- in `safe_buf_delete` call below
-- We don't use 'self.win:validate_preview()' because we want
-- to detach the buffer even when 'self.win.closing = true'
and self.win and self.win.preview_winid
and tonumber(self.win.preview_winid) > 0
and api.nvim_win_is_valid(self.win.preview_winid) then
-- attach a temp buffer to the window
-- so we can safely delete the buffer
-- ('nvim_buf_delete' removes the attached win)
retbuf = self:get_tmp_buffer()
utils.win_set_buf_noautocmd(self.win.preview_winid, retbuf)
-- redraw the title line and clear the scrollbar
self.win:close_preview_scrollbar()
end
-- since our temp buffers have 'bufhidden=wipe' the tmp
-- buffer will be automatically wiped and 'nvim_buf_is_valid'
-- will return false
-- one case where the buffer may remain valid after detaching
-- from the preview window is with URI type entries after calling
-- 'vim.lsp.util.show_document' which can reuse existing buffers,
-- so technically this should never be executed unless the
-- user wrote an fzf-lua extension and set the preview buffer to
-- a random buffer without the 'bufhidden' property
self:safe_buf_delete(self.preview_bufnr)
self.preview_bufnr = nil
self.loaded_entry = nil
return retbuf
end
function Previewer.base:display_last_entry()
self:display_entry(self.last_entry)
end
---@diagnostic disable-next-line: unused
function Previewer.base:should_clear_preview(_) end -- for lint
---@diagnostic disable-next-line: unused
function Previewer.base:populate_preview_buf(_) end -- for lint
---@param name string
---@param delay integer
---@param func function
function Previewer.base:debounce(name, delay, func)
self.timers = self.timers or {} ---@type table<string, uv.uv_timer_t?>
local timer = self.timers[name]
if tonumber(delay) > 0 then
if not timer or timer:is_closing() then
timer = assert(uv.new_timer())
self.timers[name] = timer
end
timer:start(delay, 0, function()
timer:close()
self.timers[name] = nil
vim.schedule(func)
end)
else
func()
end
end
---@param entry_str string?
function Previewer.base:display_entry(entry_str)
if not entry_str then return end
if not self.win or not self.win:validate_preview() then return end
-- verify backup the current window options
-- will store only of `winopts_orig` is nil
self:backup_winopts()
-- clears the current preview buffer and set to a new temp buffer
-- recommended to return false from 'should_clear_preview' and use
-- 'self:set_preview_buf()' instead for flicker-free experience
if self:should_clear_preview(entry_str) then
self.preview_bufnr = self:clear_preview_buf(true)
end
---@async
local populate_preview_buf = function(entry_str_)
if not self.win or not self.win:validate_preview() then return end
-- specialized previewer populate function
---@cast self fzf-lua.previewer.BufferOrFile base class def don't make sense here
if self:populate_preview_buf(entry_str_) == false then return end
-- reset the preview window highlights
self:reset_winhl(self.win.preview_winid)
end
-- debounce preview entries
self:debounce("preview", self.delay, coroutine.wrap(function()
populate_preview_buf(entry_str)
end))
end
function Previewer.base:cmdline(_)
local act = shell.stringify_data(function(items, _, _)
---@type string?, string?, string?
local entry, query, idx = unpack(items, 1, 3)
-- NOTE: see comment regarding {n} in `core.convert_exec_silent_actions`
-- convert empty string to nil
if not tonumber(idx) then entry = nil end
-- upvalue incase previewer was detached/re-attached (global picker)
self = self.win._previewer or self ---@type fzf-lua.previewer.Builtin
-- on windows, query may not be expanded to a string: #1887
FzfLua.get_info().query = query or ""
self:display_entry(entry)
-- save last entry even if we don't display
self.last_entry = entry
return ""
end, self.opts, "{} {q} {n}")
return act
end
function Previewer.base:zero(_)
--
-- debounce the zero event call to prevent reentry which may
-- cause a hang of fzf or the nvim RPC server (#909)
-- mkdir is an atomic operation and will fail if the directory
-- already exists effectively creating a singleton shell command
--
-- currently awaiting an upstream fix:
-- https://github.com/junegunn/fzf/issues/3516
--
self._zero_lock = self._zero_lock or path.normalize(fn.tempname())
local act = string.format("execute-silent(mkdir %s && %s)",
libuv.shellescape(self._zero_lock),
shell.stringify_data(function(_, _, _)
-- upvalue incase previewer was detached/re-attached (global picker)
self = self.win._previewer or self ---@type fzf-lua.previewer.Builtin
vim.defer_fn(function()
if self.win:validate_preview() then
self:clear_preview_buf(true)
TSContext.close(self.win.preview_winid)
self.win:update_preview_title("")
end
if self.loaded_entry then self.last_entry = nil end
fn.delete(self._zero_lock, "d")
end, self.delay)
end, self.opts, ""))
return act
end
function Previewer.base:preview_window(_)
if self.win and not self.win.winopts.split then
return "nohidden:right:0"
else
return nil
end
end
---@param direction "top"|"bottom"|"half-page-up"|"half-page-down"|"page-up"|"page-down"|"line-up"|"line-down"|"reset"
function Previewer.base:scroll(direction)
local preview_winid = self.win.preview_winid
if not self.preview_bufnr or preview_winid < 0 or not direction then return end
if not api.nvim_win_is_valid(preview_winid) then return end
-- map direction to scroll commands ('g8' on char to display)
local input = ({
["top"] = "gg",
["bottom"] = "G",
["half-page-up"] = ("%c"):format(0x15), -- [[]]
["half-page-down"] = ("%c"):format(0x04), -- [[]]
["page-up"] = ("%c"):format(0x02), -- [[]]
["page-down"] = ("%c"):format(0x06), -- [[]]
-- ^Y/^E doesn't seem to work
["line-up"] = "Hgk",
["line-down"] = "Lgj",
["reset"] = true, -- dummy for exit condition
})[direction]
if not input then return end
local scroll = function()
pcall(api.nvim_win_call, preview_winid, function()
vim.cmd([[norm! ]] .. input)
-- `zb` at bottom?
local height = api.nvim_win_get_height(preview_winid)
local topline = fn.line("w0")
local botline = fn.line("w$")
if height > (botline - topline) then
api.nvim_win_set_cursor(0, { botline, 1 })
vim.cmd("norm! zvzb")
end
end)
end
if direction == "reset" then
pcall(api.nvim_win_call, preview_winid, function()
-- for some reason 'nvim_win_set_cursor'
-- only moves forward, so set to (1,0) first
api.nvim_win_set_cursor(0, { 1, 0 })
if self.orig_pos then
api.nvim_win_set_cursor(0, self.orig_pos)
end
utils.zz()
end)
else
if utils.is_term_buffer(self.preview_bufnr) and api.nvim_get_mode().mode == "t" then
vim.cmd.stopinsert()
vim.schedule(function()
scroll()
vim.cmd.startinsert()
end)
else
scroll()
end
end
-- 'cursorline' is effectively our match highlight. Once the
-- user scrolls, the highlight is no longer relevant (#462).
-- Conditionally toggle 'cursorline' based on cursor position
self:maybe_set_cursorline(preview_winid, self.orig_pos)
-- HACK: Hijack cached bufnr value as last scroll position
if self.cached_bufnrs[self.preview_bufnr] then
if direction == "reset" then
self.cached_bufnrs[self.preview_bufnr] = true
else
self.cached_bufnrs[self.preview_bufnr] = api.nvim_win_get_cursor(preview_winid)
end
end
self.win:update_preview_scrollbar()
self:update_render_markdown()
self:update_ts_context()
end
-- https://github.com/kevinhwang91/nvim-bqf/blob/b51a37fcd808edafd52511458467c8c9a701ea8d/lua/bqf/preview/extmark.lua#L20
-- copy extmarks from src_buf to buf
---@param src_buf integer
---@param buf integer
---@param win integer
---@param topline integer 0-based
---@param botline integer 0-based
---@param ns integer
local copy_extmarks = function(src_buf, buf, win, topline, botline, ns)
local src_win = fn.win_findbuf(src_buf)[1]
local src_leftcol = src_win and api.nvim_win_call(src_win, fn.winsaveview).leftcol or nil
-- virt_text is related to screen https://github.com/neovim/neovim/issues/14050
local no_virt_text = api.nvim_win_call(win, fn.winsaveview).leftcol ~= src_leftcol
api.nvim_buf_clear_namespace(buf, ns, topline, botline)
local extmarks = api.nvim_buf_get_extmarks(src_buf, -1, { topline, 0 }, { botline, -1 },
{ details = true })
local namespaces = api.nvim_get_namespaces()
local ignore = {}
if namespaces["snacks.image"] then ignore[namespaces["snacks.image"]] = true end
for _, m in ipairs(extmarks) do
local _, row, col, details = unpack(m) ---@cast details -?
if not ignore[details.ns_id] then
details.ns_id = nil
if no_virt_text and details.virt_text then details.virt_text = nil end
pcall(api.nvim_buf_set_extmark, buf, ns, row, col, details)
end
end
end
---@return fun()
function Previewer.base:copy_extmarks()
self.ns_extmarks = self.ns_extmarks or api.nvim_create_namespace("fzf-lua.preview.extmarks")
api.nvim_set_decoration_provider(self.ns_extmarks, {
on_win = function(_, win, buf, topline, botline)
if win ~= self.win.preview_winid then return end
local src_buf = self.loaded_entry and self.loaded_entry.bufnr
if not src_buf or not api.nvim_buf_is_valid(src_buf) then return end
copy_extmarks(src_buf, buf, win, topline, botline, self.ns_extmarks)
return false
end,
})
return function()
api.nvim_set_decoration_provider(self.ns_extmarks, {})
end
end
function Previewer.base:ts_ctx_toggle()
local bufnr, winid = self.preview_bufnr, self.win.preview_winid
if not bufnr or winid < 0 or not api.nvim_win_is_valid(winid) then return end
if self.treesitter.context then
self.treesitter._context = self.treesitter.context
self.treesitter.context = nil
else
self.treesitter.context = self.treesitter._context or true
self.treesitter._context = nil
end
TSContext.toggle(winid, bufnr)
end
function Previewer.base:ts_ctx_inc_dec_maxlines(num)
local bufnr, winid = self.preview_bufnr, self.win.preview_winid
if winid < 0 or not api.nvim_win_is_valid(winid) then return end
TSContext.inc_dec_maxlines(num, winid, bufnr)
end
---@class fzf-lua.previewer.BufferOrFile : fzf-lua.previewer.Builtin,{}
---@field match_id? integer
---@field super fzf-lua.previewer.Builtin
Previewer.buffer_or_file = Previewer.base:extend()
function Previewer.buffer_or_file:new(o, opts)
Previewer.buffer_or_file.super.new(self, o, opts)
return self
end
function Previewer.buffer_or_file:close(do_not_clear_cache)
Previewer.base.close(self, do_not_clear_cache)
self:stop_ueberzug()
end
---@param entry_str string
---@return fzf-lua.path.Entry
function Previewer.buffer_or_file:entry_to_file(entry_str)
return path.entry_to_file(entry_str, self.opts)
end
---async result can be return by "_cb(res)"
---@param entry_str string
---@param _cb? function
---@return fzf-lua.buffer_or_file.Entry
function Previewer.buffer_or_file:parse_entry(entry_str, _cb)
---@type fzf-lua.buffer_or_file.Entry
local entry = self:entry_to_file(entry_str)
local buf = entry.bufnr
local loaded = buf and api.nvim_buf_is_loaded(buf)
if loaded then
entry.tick = vim.b[buf].changedtick
return entry
end
-- buffer is not loaded, can happen when calling "lines" with `set nohidden`
-- or when starting nvim with an arglist, fix entry.path since it contains
-- filename only
if buf and api.nvim_buf_is_valid(buf) then
entry.path = path.relative_to(api.nvim_buf_get_name(buf), utils.cwd())
if entry.path:find("^fugitive://") then
api.nvim_buf_call(buf, function()
api.nvim_exec_autocmds("BufReadCmd", {
group = fn.exists("#fugitive#BufReadCmd") == 1 and "fugitive" or nil,
pattern = entry.path
})
end)
return entry
end
end
if entry.path then
entry.tick = vim.tbl_get(uv.fs_stat(entry.path) or {}, "mtime", "nsec")
end
return entry
end
---@diagnostic disable-next-line: unused
---@return boolean
function Previewer.buffer_or_file:should_clear_preview(_)
return false
end
---@param entry fzf-lua.buffer_or_file.Entry|{}
---@return boolean
function Previewer.buffer_or_file:should_load_buffer(entry)
-- we don't have a previous entry to compare to or `do_not_cache` is set meaning
-- it's a terminal command (chafa, viu, ueberzug) which requires a reload
-- return 'true' so the buffer will be loaded in ::populate_preview_buf
if not self.loaded_entry or self.loaded_entry.do_not_cache then return true end
return self.loaded_entry.cached ~= entry.cached
end
function Previewer.buffer_or_file:start_ueberzug()
if self._ueberzug_fifo then return self._ueberzug_fifo end
self._ueberzug_fifo = path.join({
fn.fnamemodify(fn.tempname(), ":h"),
string.format("fzf-lua-%d-ueberzug", fn.getpid())
})
utils.io_system({ "mkfifo", self._ueberzug_fifo })
self._ueberzug_job = fn.jobstart({ "sh", "-c",
string.format(
"tail -f %s | ueberzug layer --parser json",
libuv.shellescape(self._ueberzug_fifo))
}, {
on_exit = function(_, rc, _)
if rc ~= 0 and rc ~= 143 then
utils.warn(("ueberzug exited with error %d"):format(rc) ..
", run ':messages' to see the detailed error.")
end
end,
on_stderr = function(_, data, _)
for _, l in ipairs(data or {}) do
if #l > 0 then
utils.info("ueberzug: " .. l)
end
end
-- populate the preview buffer with the error message
if self.preview_bufnr and self.preview_bufnr > 0 and
api.nvim_buf_is_valid(self.preview_bufnr) then
local lines = api.nvim_buf_get_lines(self.preview_bufnr, 0, -1, false)
for _, l in ipairs(data or {}) do
table.insert(lines, l)
end
api.nvim_buf_set_lines(self.preview_bufnr, 0, -1, false, lines)
end
end
}
)
self._ueberzug_pid = fn.jobpid(self._ueberzug_job)
return self._ueberzug_fifo
end
function Previewer.buffer_or_file:stop_ueberzug()
if self._ueberzug_job then
fn.jobstop(self._ueberzug_job)
if type(uv.os_getpriority(self._ueberzug_pid)) == "number" then
uv.kill(self._ueberzug_pid, 9)
end
self._ueberzug_job = nil
self._ueberzug_pid = nil
end
if self._ueberzug_fifo and uv.fs_stat(self._ueberzug_fifo) then
fn.delete(self._ueberzug_fifo)
self._ueberzug_fifo = nil
end
end
function Previewer.buffer_or_file:populate_terminal_cmd(tmpbuf, cmd, entry)
if not cmd then return end
cmd = type(cmd) == "table" and utils.deepcopy(cmd) or { cmd }
if not cmd[1] or fn.executable(cmd[1]) ~= 1 then
return false
end
-- no caching: preview buf must be reattached for
-- terminal image previews to have the correct size
entry.do_not_cache = true
-- when terminal execution ends last line in the buffer
-- will display "[Process exited 0]", this will enable
-- the scrollbar which we wish to hide
entry.no_scrollbar = true
-- both ueberzug and terminal cmds need a clear
-- on redraw to fit the new window dimensions
self.clear_on_redraw = true
-- 2nd arg `true`: minimal style window
self:set_preview_buf(tmpbuf, true)
if cmd[1]:match("ueberzug") then
local fifo = self:start_ueberzug()
if not fifo then return end
local wincfg = api.nvim_win_get_config(self.win.preview_winid)
local winpos = api.nvim_win_get_position(self.win.preview_winid)
local params = {
action = "add",
identifier = "preview",
x = winpos[2] + 1,
y = winpos[1] + 2,
width = wincfg.width - 2,
height = wincfg.height - 2,
scaler = self.ueberzug_scaler,
path = path.is_absolute(entry.path) and entry.path or
path.join({ self.opts.cwd or utils.cwd(), entry.path }),
}
local json = vim.json.encode(params)
-- both 'fs_open|write|close' and 'fn.system' work.
-- We prefer the libuv method as it doesn't rely on the shell
-- cmd = { "sh", "-c", ("echo '%s' > %s"):format(json, self._ueberzug_fifo) }
-- fn.system(cmd)
local fd = uv.fs_open(self._ueberzug_fifo, "a", -1)
if fd then
uv.fs_write(fd, json .. "\n", nil, function(_)
uv.fs_close(fd)
end)
end
else
-- replace `{file}` placeholder with the filename
local add_file = true
for i, arg in ipairs(cmd) do
if type(arg) == "string" and arg:match("[<{]file[}>]") then
cmd[i] = entry.path
add_file = false
end
end
-- or add filename as last parameter
if add_file then
table.insert(cmd, entry.path)
end
-- must be modifiable or 'termopen' fails
vim.bo[tmpbuf].modifiable = true
api.nvim_buf_call(tmpbuf, function()
self._job_id = utils.termopen(cmd, {
cwd = self.opts.cwd,
on_exit = function()
-- run post only after terminal job finished
if self._job_id then
self:preview_buf_post(entry, true)
self._job_id = nil
end
end
})
end)
end
-- run here so title gets updated
-- even if the image is still loading
self:preview_buf_post(entry, true)
return true
end
---@diagnostic disable-next-line: unused
---@param entry fzf-lua.buffer_or_file.Entry
---@return string?
function Previewer.buffer_or_file:key_from_entry(entry)
if entry.do_not_cache then return nil end
return (entry.bufnr and string.format("bufnr:%d", entry.bufnr) or entry.uri or entry.path) or nil
end
---get and check if cached is update-to-date to be reuse
---@param entry fzf-lua.buffer_or_file.Entry
---@return fzf-lua.buffer_or_file.Bcache?
function Previewer.buffer_or_file:check_bcache(entry)
local key = self:key_from_entry(entry)
if not key then return end
local cached = self.cached_buffers[key]
if not cached then return end
entry.cached = cached
assert(self.cached_bufnrs[cached.bufnr])
assert(api.nvim_buf_is_valid(cached.bufnr))
if entry.tick ~= cached.tick then
cached.invalid = true
cached.tick = entry.tick
end
return cached
end
---@alias fzf-lua.line (string|[string,string])[]
---@param content (string|fzf-lua.line)[]
---@return string[], table
local parse_rich = function(content)
local lines, extmarks = {}, {}
for i, line in ipairs(content) do
-- If the line is a string, just add it directly.
-- Otherwise, it's a table of parts (rich text line)
if type(line) == "string" then
lines[#lines + 1] = line
else
local parts = {}
local col = 0
for _, part in ipairs(line) do
local norm_part = type(part) == "string" and { part } or part
local text, hl = norm_part[1] or "", norm_part[2]
parts[#parts + 1] = text
local end_col = col + #text
if hl then
extmarks[#extmarks + 1] = { row = i - 1, col = col, end_col = end_col, hl_group = hl }
end
col = end_col
end
lines[#lines + 1] = table.concat(parts, "")
end
end
return lines, extmarks
end
---@param buf integer
---@param entry fzf-lua.cmd.Entry
---@param opts table
local start_cmd = function(buf, entry, opts)
local chan ---@type integer?
local obj ---@type vim.SystemObj?
local close = function(err)
if chan then
pcall(fn.chanclose, chan)
chan = nil
end
if obj and not obj:is_closing() then
obj:kill(vim.uv.constants.SIGTERM)
obj = nil
end
if err then error(err) end
end
local try_send = function(data)
if not opts.cancel() and chan and pcall(api.nvim_chan_send, chan, data) then
return opts.on_send(data)
end
end
local stdout, on_exit
if entry.cmd_stream ~= false then
chan = api.nvim_open_term(buf, {})
stdout = vim.schedule_wrap(function(err, data)
if err then close(err) end
if data then try_send(data) end
end)
end
on_exit = vim.schedule_wrap(function(obj0)
if not api.nvim_buf_is_valid(buf) then return end
if entry.cmd_stream ~= false then
opts.on_exit()
else
chan = api.nvim_open_term(buf, {})
try_send(vim.trim(obj0.stderr or "") ~= "" and obj0.stderr or obj0.stdout or "")
end
end)
local sopts = entry.cmd_opts or {}
sopts = vim.tbl_deep_extend("force", sopts, { stdout = stdout, stderr = stdout })
obj = vim.system(entry.cmd, sopts, on_exit)
end
---@async
---@param entry_str string
---@return false? no preview
function Previewer.buffer_or_file:populate_preview_buf(entry_str)
if not self.win or not self.win:validate_preview() then return end
-- stop ueberzug shell job
self:stop_ueberzug()
local co = coroutine.running()
-- schedule can avoid "cannot resume running coroutine"