-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathrg.lua
More file actions
996 lines (900 loc) · 26.7 KB
/
Copy pathrg.lua
File metadata and controls
996 lines (900 loc) · 26.7 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
local M = {}
local selection_ns = vim.api.nvim_create_namespace("kide_rg_live_grep")
local match_ns = vim.api.nvim_create_namespace("kide_rg_live_grep_matches")
local count_ns = vim.api.nvim_create_namespace("kide_rg_live_grep_count")
local preview_ns = vim.api.nvim_create_namespace("kide_rg_live_grep_preview")
local session = 0
local path_utils = require("kide.path")
local file_path_limit = 40
local function stopinsert()
if vim.api.nvim_get_mode().mode == "i" then
vim.cmd("stopinsert")
end
end
local function live_grep_opts()
local columns = vim.o.columns
local lines = vim.o.lines
local width = math.floor(columns * 0.9)
local height = math.floor(lines * 0.8)
local row = math.floor((lines - height) * 0.5)
local col = math.floor((columns - width) * 0.5)
local body_height = math.max(6, height - 2)
local result_height = math.floor(body_height * 0.5)
local preview_height = body_height - result_height
return {
input = {
relative = "editor",
style = "minimal",
row = row,
col = col,
width = width,
height = 1,
focusable = true,
border = { "╭", "─", "╮", "│", "┤", "─", "├", "│" },
title = "Live Grep",
title_pos = "center",
},
result = {
relative = "editor",
style = "minimal",
row = row + 2,
col = col,
width = width,
height = result_height,
focusable = true,
border = { "├", "─", "┤", "│", "┤", "─", "├", "│" },
},
preview = {
relative = "editor",
style = "minimal",
row = row + result_height + 3,
col = col,
width = width,
height = preview_height,
focusable = true,
border = { "├", "─", "┤", "│", "╯", "─", "╰", "│" },
},
}
end
local function set_scratch_options(buf)
vim.bo[buf].buftype = "nofile"
vim.bo[buf].bufhidden = "wipe"
vim.bo[buf].buflisted = false
vim.bo[buf].swapfile = false
end
local function set_result_lines(buf, lines)
if not buf or not vim.api.nvim_buf_is_valid(buf) then
return
end
vim.bo[buf].modifiable = true
vim.api.nvim_buf_set_lines(buf, 0, -1, false, lines)
vim.bo[buf].modifiable = false
vim.bo[buf].modified = false
end
local function stop_job(state)
if state.job and state.job > 0 then
local job = state.job
state.job = nil
pcall(vim.fn.jobstop, job)
end
end
local function set_range_highlight(buf, ns, hl_group, row, start_col, end_col)
if end_col <= start_col then
return
end
vim.api.nvim_buf_set_extmark(buf, ns, row, start_col, {
end_col = end_col,
hl_group = hl_group,
priority = 100,
})
end
local function detect_filetype(filename)
if not vim.filetype or not vim.filetype.match then
return ""
end
local ok, ft = pcall(vim.filetype.match, { filename = filename })
if not ok or not ft then
return ""
end
return ft
end
local function set_preview_syntax(state, filename)
local buf = state.preview_buf
if not buf or not vim.api.nvim_buf_is_valid(buf) then
return
end
local ft = filename and detect_filetype(filename) or ""
if state.preview_ft == ft then
return
end
if state.preview_ft and state.preview_ft ~= "" then
pcall(vim.treesitter.stop, buf)
end
if ft ~= "" then
pcall(vim.treesitter.start, buf, ft)
end
vim.bo[buf].syntax = ft
state.preview_ft = ft
end
local function update_input_count(state)
if not state.input_buf or not vim.api.nvim_buf_is_valid(state.input_buf) then
return
end
local suffix = state.truncated and "+" or ""
local text = ("%d%s"):format(#state.items, suffix)
vim.api.nvim_buf_clear_namespace(state.input_buf, count_ns, 0, -1)
vim.api.nvim_buf_set_extmark(state.input_buf, count_ns, 0, 0, {
virt_text = { { " " .. text, "Comment" } },
virt_text_pos = "eol",
hl_mode = "combine",
priority = 100,
})
end
local function apply_selection(state)
if not state.result_buf or not vim.api.nvim_buf_is_valid(state.result_buf) then
return
end
vim.api.nvim_buf_clear_namespace(state.result_buf, selection_ns, 0, -1)
if vim.tbl_isempty(state.items) then
if state.result_win and vim.api.nvim_win_is_valid(state.result_win) then
vim.wo[state.result_win].cursorline = false
end
return
end
state.selected = math.max(1, math.min(state.selected, #state.items))
if state.result_win and vim.api.nvim_win_is_valid(state.result_win) then
vim.wo[state.result_win].cursorline = true
pcall(vim.api.nvim_win_set_cursor, state.result_win, { state.selected, 0 })
end
end
local function apply_preview_highlights(state)
if not state.preview_buf or not vim.api.nvim_buf_is_valid(state.preview_buf) then
return
end
vim.api.nvim_buf_clear_namespace(state.preview_buf, preview_ns, 0, -1)
for row, prefix in ipairs(state.preview_prefixes or {}) do
local virt_text = { { prefix, "LineNr" } }
if row == state.preview_target_row then
virt_text[1][2] = "Normal"
end
vim.api.nvim_buf_set_extmark(state.preview_buf, preview_ns, row - 1, 0, {
virt_text = virt_text,
virt_text_pos = "inline",
hl_mode = "combine",
priority = 90,
})
end
if state.preview_target_row then
for _, match in ipairs(state.preview_matches or {}) do
vim.api.nvim_buf_set_extmark(state.preview_buf, preview_ns, state.preview_target_row - 1, match.start, {
end_col = match.finish,
hl_group = "Search",
-- hl_mode = "replace",
priority = 200,
})
end
end
end
local function reset_preview_state(state)
state.preview_prefixes = {}
state.preview_matches = {}
state.preview_target_row = nil
end
local function set_preview_entries(state, request_id, item, entries)
vim.schedule(function()
if state.closed or request_id ~= state.preview_id then
return
end
reset_preview_state(state)
if vim.tbl_isempty(entries) then
set_preview_syntax(state)
set_result_lines(state.preview_buf, {})
apply_preview_highlights(state)
return
end
local number_width = #tostring(entries[#entries].lnum)
local lines = {}
local match_lnum = item.lnum
local start_lnum = math.max(1, match_lnum - math.floor((state.context_lines) * 0.5))
for _, entry in ipairs(entries) do
if entry.lnum >= start_lnum then
local prefix = string.format("%" .. number_width .. "d ", entry.lnum)
table.insert(lines, entry.text)
table.insert(state.preview_prefixes, prefix)
end
if entry.lnum == item.lnum then
state.preview_target_row = #lines
state.preview_matches = item.matches or {}
end
end
if state.preview_target_row then
set_result_lines(state.preview_buf, lines)
set_preview_syntax(state, item.file)
apply_preview_highlights(state)
end
end)
end
local function trim_entries(entries, limit)
while #entries > limit do
table.remove(entries, 1)
end
end
local function preview_item_key(item)
return ("%s:%d:%d:%d:%s"):format(item.file, item.lnum, item.col or 0, item.preview_version or 0, item.text or "")
end
local function update_preview(state)
if not state.preview_buf or not vim.api.nvim_buf_is_valid(state.preview_buf) then
return
end
local item = state.items[state.selected]
if not item then
state.preview_id = (state.preview_id or 0) + 1
state.preview_key = nil
reset_preview_state(state)
set_preview_syntax(state)
set_result_lines(state.preview_buf, {})
apply_preview_highlights(state)
return
end
local key = preview_item_key(item)
if state.preview_key == key then
return
end
state.preview_id = (state.preview_id or 0) + 1
state.preview_key = key
local request_id = state.preview_id
set_preview_entries(state, request_id, item, item.preview_entries or {
{ lnum = item.lnum, text = item.text },
})
end
local function apply_highlights(state)
if not state.result_buf or not vim.api.nvim_buf_is_valid(state.result_buf) then
return
end
vim.api.nvim_buf_clear_namespace(state.result_buf, match_ns, 0, -1)
for row, item in ipairs(state.items) do
if item.file_len and item.prefix_len then
set_range_highlight(state.result_buf, match_ns, "Directory", row - 1, 0, item.file_len)
set_range_highlight(state.result_buf, match_ns, "LineNr", row - 1, item.file_len, item.prefix_len)
end
local prefix_len = item.prefix_len or 0
for _, match in ipairs(item.matches or {}) do
if match.finish > match.start then
set_range_highlight(
state.result_buf,
match_ns,
"Search",
row - 1,
prefix_len + match.start,
prefix_len + match.finish
)
end
end
end
end
local function render(state)
if state.closed then
return
end
update_input_count(state)
if not state.result_buf or not vim.api.nvim_buf_is_valid(state.result_buf) then
return
end
local lines = state.display_lines
if vim.tbl_isempty(lines) then
if state.query == "" then
lines = {}
elseif state.running then
lines = {}
elseif not vim.tbl_isempty(state.stderr) then
lines = { state.stderr[#state.stderr] }
else
lines = {}
end
end
set_result_lines(state.result_buf, lines)
apply_highlights(state)
apply_selection(state)
if not state.running then
update_preview(state)
end
end
local function schedule_render(state)
if state.render_scheduled then
return
end
state.render_scheduled = true
vim.defer_fn(function()
state.render_scheduled = false
render(state)
end, 40)
end
local function parse_entry(data)
local result_path = data.path or {}
local lines = data.lines or {}
local filename = result_path.text
local lnum = data.line_number
if not filename or not lnum then
return nil
end
filename = filename:gsub("^%./", "")
local text = lines.text or ""
text = text:gsub("[\r\n]+$", "")
return {
file = filename,
lnum = lnum,
text = text,
}
end
local function parse_json(line)
local ok, item = pcall(vim.json.decode, line)
if not ok or type(item) ~= "table" then
return nil
end
local data = item.data or {}
if item.type == "context" then
local entry = parse_entry(data)
if not entry then
return nil
end
return {
kind = "context",
entry = entry,
}
end
if item.type ~= "match" then
return nil
end
local entry = parse_entry(data)
if not entry then
return nil
end
local submatches = data.submatches or {}
local first_match = submatches[1] or {}
local col = (first_match.start or 0) + 1
local display_file = path_utils.shorten(entry.file, file_path_limit)
local prefix = ("%s:%d:%d:"):format(display_file, entry.lnum, col)
local matches = {}
for _, match in ipairs(submatches) do
if match.start and match["end"] then
table.insert(matches, {
start = match.start,
finish = match["end"],
})
end
end
return {
kind = "match",
file = entry.file,
display_file = display_file,
lnum = entry.lnum,
col = col,
text = entry.text,
file_len = #display_file,
prefix_len = #prefix,
matches = matches,
preview_entries = {},
preview_version = 0,
display = prefix .. entry.text,
}
end
local function append_preview_entry(item, entry)
if not item.preview_seen then
item.preview_seen = {}
end
local key = ("%s:%d"):format(entry.file, entry.lnum)
if item.preview_seen[key] then
return false
end
item.preview_seen[key] = true
table.insert(item.preview_entries, {
lnum = entry.lnum,
text = entry.text,
})
item.preview_version = (item.preview_version or 0) + 1
return true
end
local function entry_from_match(item)
return {
file = item.file,
lnum = item.lnum,
text = item.text,
}
end
local function add_recent_entry(state, entry)
table.insert(state.recent_entries, entry)
trim_entries(state.recent_entries, state.context_lines or 3)
end
local function add_entry_to_pending_previews(state, entry)
local context_lines = state.context_lines or 3
local pending = {}
for _, pending_item in ipairs(state.pending_preview_items or {}) do
if pending_item.file == entry.file and entry.lnum > pending_item.lnum then
local distance = entry.lnum - pending_item.lnum
if distance <= context_lines then
append_preview_entry(pending_item, entry)
table.insert(pending, pending_item)
end
elseif pending_item.file == entry.file and entry.lnum <= pending_item.lnum + context_lines then
table.insert(pending, pending_item)
end
end
state.pending_preview_items = pending
end
local function append_result(state, line)
if line == "" or #state.items >= state.limit then
return
end
local item = parse_json(line)
if not item then
return
end
if item.kind == "context" then
local entry = item.entry
add_entry_to_pending_previews(state, entry)
add_recent_entry(state, entry)
return
end
local match_entry = entry_from_match(item)
add_entry_to_pending_previews(state, match_entry)
for _, entry in ipairs(state.recent_entries) do
if entry.file == item.file and entry.lnum < item.lnum and item.lnum - entry.lnum <= (state.context_lines or 3) then
append_preview_entry(item, entry)
end
end
append_preview_entry(item, match_entry)
add_recent_entry(state, match_entry)
table.insert(state.pending_preview_items, item)
table.insert(state.items, item)
table.insert(state.display_lines, item.display)
if #state.items == 1 then
state.selected = 1
end
if #state.items >= state.limit then
state.truncated = true
stop_job(state)
end
schedule_render(state)
end
local function collect_job_lines(data, partial, on_line)
if not data or vim.tbl_isempty(data) then
return partial or ""
end
data[1] = (partial or "") .. data[1]
partial = table.remove(data)
for _, line in ipairs(data) do
on_line(line)
end
return partial or ""
end
local function current_query(state)
if not state.input_buf or not vim.api.nvim_buf_is_valid(state.input_buf) then
return ""
end
local line = vim.api.nvim_buf_get_lines(state.input_buf, 0, 1, false)[1] or ""
return vim.trim(line)
end
local function start_search(state)
if state.closed then
return
end
local query = current_query(state)
state.query = query
state.search_id = state.search_id + 1
local search_id = state.search_id
stop_job(state)
state.items = {}
state.display_lines = {}
state.recent_entries = {}
state.pending_preview_items = {}
state.stderr = {}
state.stdout_partial = ""
state.stderr_partial = ""
state.selected = 1
state.truncated = false
state.preview_id = (state.preview_id or 0) + 1
state.preview_key = nil
state.running = query ~= ""
render(state)
if query == "" then
return
end
local cmd = {
"rg",
"--json",
"--color=never",
"--smart-case",
"--hidden",
"--glob",
"!.git/**",
"--line-buffered",
"--max-columns=500",
"--max-columns-preview",
"--context",
tostring(state.context_lines or 3),
"--",
query,
".",
}
local job = vim.fn.jobstart(cmd, {
stdout_buffered = false,
stderr_buffered = false,
on_stdout = function(_, data)
if state.closed or search_id ~= state.search_id then
return
end
state.stdout_partial = collect_job_lines(data, state.stdout_partial, function(line)
append_result(state, line)
end)
end,
on_stderr = function(_, data)
if state.closed or search_id ~= state.search_id then
return
end
state.stderr_partial = collect_job_lines(data, state.stderr_partial, function(line)
if line ~= "" then
table.insert(state.stderr, line)
end
end)
end,
on_exit = function()
vim.schedule(function()
if state.closed or search_id ~= state.search_id then
return
end
if state.stdout_partial ~= "" then
append_result(state, state.stdout_partial)
state.stdout_partial = ""
end
if state.stderr_partial ~= "" then
table.insert(state.stderr, state.stderr_partial)
state.stderr_partial = ""
end
state.running = false
state.job = nil
render(state)
end)
end,
})
if job <= 0 then
state.running = false
state.job = nil
state.stderr = { "rg 启动失败" }
render(state)
return
end
state.job = job
end
local function schedule_search(state)
state.debounce_id = state.debounce_id + 1
local debounce_id = state.debounce_id
vim.defer_fn(function()
if state.closed or debounce_id ~= state.debounce_id then
return
end
start_search(state)
end, state.debounce)
end
local function close(state)
if state.closed then
return
end
stopinsert()
state.closed = true
stop_job(state)
if state.group then
pcall(vim.api.nvim_del_augroup_by_id, state.group)
end
if state.input_win and vim.api.nvim_win_is_valid(state.input_win) then
pcall(vim.api.nvim_win_close, state.input_win, true)
end
if state.result_win and vim.api.nvim_win_is_valid(state.result_win) then
pcall(vim.api.nvim_win_close, state.result_win, true)
end
if state.preview_win and vim.api.nvim_win_is_valid(state.preview_win) then
pcall(vim.api.nvim_win_close, state.preview_win, true)
end
if state.input_buf and vim.api.nvim_buf_is_valid(state.input_buf) then
pcall(vim.api.nvim_buf_delete, state.input_buf, { force = true })
end
if state.result_buf and vim.api.nvim_buf_is_valid(state.result_buf) then
pcall(vim.api.nvim_buf_delete, state.result_buf, { force = true })
end
if state.preview_buf and vim.api.nvim_buf_is_valid(state.preview_buf) then
pcall(vim.api.nvim_buf_delete, state.preview_buf, { force = true })
end
end
local function state_has_window(state, win)
return (state.input_win and vim.api.nvim_win_is_valid(state.input_win) and win == state.input_win)
or (state.result_win and vim.api.nvim_win_is_valid(state.result_win) and win == state.result_win)
or (state.preview_win and vim.api.nvim_win_is_valid(state.preview_win) and win == state.preview_win)
end
local function close_on_focus_lost(state)
vim.schedule(function()
if state.closed then
return
end
if not state_has_window(state, vim.api.nvim_get_current_win()) then
close(state)
end
end)
end
local function move_selection(state, delta)
if vim.tbl_isempty(state.items) then
return
end
local selected = math.max(1, math.min(state.selected + delta, #state.items))
if selected == state.selected then
return
end
state.selected = selected
apply_selection(state)
update_preview(state)
end
local function open_item(item)
if not item then
return
end
vim.cmd("edit " .. vim.fn.fnameescape(item.file))
local col = math.max(item.col - 1, 0)
pcall(vim.api.nvim_win_set_cursor, 0, { item.lnum, col })
if col > 0 then
vim.cmd("normal! l")
end
vim.cmd("normal! zv")
end
local function terminal_safe_text(text)
text = tostring(text or "")
text = text:gsub("\t", " ")
text = text:gsub("[%c]", " ")
return text
end
local function truncate_text(text, max_width)
if vim.fn.strdisplaywidth(text) <= max_width then
return text
end
local width = math.max(1, max_width - 3)
local chars = vim.fn.strchars(text)
local truncated = vim.fn.strcharpart(text, 0, math.min(chars, width))
while vim.fn.strdisplaywidth(truncated) > width and vim.fn.strchars(truncated) > 0 do
truncated = vim.fn.strcharpart(truncated, 0, vim.fn.strchars(truncated) - 1)
end
return truncated .. "..."
end
local function fzy_item_line(item, index, max_width)
local display_file = item.display_file or path_utils.shorten(item.file, file_path_limit)
local line = ("%04d %s:%d:%d: %s"):format(index, display_file, item.lnum, item.col, terminal_safe_text(item.text))
return truncate_text(line, max_width)
end
local function confirm_selection(state)
local item = state.items[state.selected]
if not item then
return
end
stopinsert()
close(state)
open_item(item)
end
local function fzy_selection(state)
if vim.tbl_isempty(state.items) then
-- vim.notify("没有 rg 结果可交给 fzy", vim.log.levels.INFO)
return
end
local lines = {}
local item_by_line = {}
local max_width = math.max(40, math.floor(vim.o.columns * 0.9) - 4)
for index, item in ipairs(state.items) do
local line = fzy_item_line(item, index, max_width)
table.insert(lines, line)
item_by_line[line] = item
end
stopinsert()
close(state)
require("kide.fzy").select(lines, {
title = "Live Grep Results",
empty_message = "没有 rg 结果",
on_choice = function(choice)
open_item(item_by_line[choice])
end,
})
end
local function focus_input(state, insert)
if state.input_win and vim.api.nvim_win_is_valid(state.input_win) then
vim.api.nvim_set_current_win(state.input_win)
if insert then
vim.cmd("startinsert!")
end
end
end
local function map(state, buf, mode, lhs, rhs)
vim.keymap.set(mode, lhs, rhs, { buffer = buf, noremap = true, silent = true, nowait = true })
end
function M.live_grep(opts)
opts = opts or {}
if vim.fn.executable("rg") ~= 1 then
vim.notify("rg 未安装或不在 PATH 中", vim.log.levels.WARN)
return
end
stopinsert()
session = session + 1
local state = {
id = session,
query = vim.trim(opts.query or ""),
items = {},
display_lines = {},
stderr = {},
selected = 1,
search_id = 0,
debounce_id = 0,
debounce = opts.debounce or 150,
limit = opts.limit or 1000,
context_lines = opts.context,
running = false,
closed = false,
}
local opts_layout = live_grep_opts()
state.input_buf = vim.api.nvim_create_buf(false, true)
state.result_buf = vim.api.nvim_create_buf(false, true)
state.preview_buf = vim.api.nvim_create_buf(false, true)
set_scratch_options(state.input_buf)
set_scratch_options(state.result_buf)
set_scratch_options(state.preview_buf)
vim.bo[state.result_buf].modifiable = false
vim.bo[state.result_buf].filetype = "grep"
vim.bo[state.preview_buf].modifiable = false
state.input_win = vim.api.nvim_open_win(state.input_buf, true, opts_layout.input)
state.result_win = vim.api.nvim_open_win(state.result_buf, false, opts_layout.result)
state.preview_win = vim.api.nvim_open_win(state.preview_buf, false, opts_layout.preview)
state.preview_height = opts_layout.preview.height
state.context_lines = state.context_lines or math.max(2, state.preview_height - 1)
vim.wo[state.input_win].number = false
vim.wo[state.input_win].relativenumber = false
vim.wo[state.result_win].number = false
vim.wo[state.result_win].relativenumber = false
vim.wo[state.result_win].wrap = false
vim.wo[state.result_win].cursorline = true
vim.wo[state.preview_win].number = false
vim.wo[state.preview_win].relativenumber = false
vim.wo[state.preview_win].wrap = false
vim.wo[state.preview_win].cursorline = false
vim.api.nvim_buf_set_lines(state.input_buf, 0, -1, false, { state.query })
vim.api.nvim_win_set_cursor(state.input_win, { 1, #state.query })
state.group = vim.api.nvim_create_augroup("kide-rg-live-grep-" .. state.id, { clear = true })
vim.api.nvim_create_autocmd({ "TextChanged", "TextChangedI" }, {
group = state.group,
buffer = state.input_buf,
callback = function()
schedule_search(state)
end,
})
vim.api.nvim_create_autocmd("BufWipeout", {
group = state.group,
buffer = state.input_buf,
callback = function()
close(state)
end,
})
vim.api.nvim_create_autocmd("BufWipeout", {
group = state.group,
buffer = state.result_buf,
callback = function()
close(state)
end,
})
vim.api.nvim_create_autocmd("BufWipeout", {
group = state.group,
buffer = state.preview_buf,
callback = function()
close(state)
end,
})
vim.api.nvim_create_autocmd("WinLeave", {
group = state.group,
callback = function()
close_on_focus_lost(state)
end,
})
map(state, state.input_buf, "n", "q", function()
close(state)
end)
map(state, state.input_buf, { "i", "n" }, "<Esc>", function()
close(state)
end)
map(state, state.input_buf, { "i", "n" }, "<CR>", function()
confirm_selection(state)
end)
map(state, state.input_buf, { "i", "n" }, "<C-c>", function()
close(state)
end)
map(state, state.input_buf, { "i", "n" }, "<Down>", function()
move_selection(state, 1)
end)
map(state, state.input_buf, { "i", "n" }, "<Up>", function()
move_selection(state, -1)
end)
map(state, state.input_buf, "n", "j", function()
move_selection(state, 1)
end)
map(state, state.input_buf, "n", "k", function()
move_selection(state, -1)
end)
map(state, state.input_buf, { "i", "n" }, "<C-n>", function()
move_selection(state, 1)
end)
map(state, state.input_buf, { "i", "n" }, "<C-p>", function()
move_selection(state, -1)
end)
map(state, state.input_buf, { "i", "n" }, "<C-g>", function()
fzy_selection(state)
end)
map(state, state.result_buf, "n", "q", function()
close(state)
end)
map(state, state.result_buf, "n", "<Esc>", function()
close(state)
end)
map(state, state.result_buf, "n", "<CR>", function()
confirm_selection(state)
end)
map(state, state.result_buf, "n", "i", function()
focus_input(state, true)
end)
map(state, state.result_buf, "n", "/", function()
focus_input(state, true)
end)
map(state, state.result_buf, "n", "j", function()
move_selection(state, 1)
end)
map(state, state.result_buf, "n", "k", function()
move_selection(state, -1)
end)
map(state, state.result_buf, "n", "<Down>", function()
move_selection(state, 1)
end)
map(state, state.result_buf, "n", "<Up>", function()
move_selection(state, -1)
end)
map(state, state.result_buf, "n", "<C-n>", function()
move_selection(state, 1)
end)
map(state, state.result_buf, "n", "<C-p>", function()
move_selection(state, -1)
end)
map(state, state.result_buf, "n", "<C-g>", function()
fzy_selection(state)
end)
map(state, state.preview_buf, "n", "q", function()
close(state)
end)
map(state, state.preview_buf, "n", "<Esc>", function()
close(state)
end)
map(state, state.preview_buf, "n", "<CR>", function()
confirm_selection(state)
end)
map(state, state.preview_buf, "n", "i", function()
focus_input(state, true)
end)
map(state, state.preview_buf, "n", "/", function()
focus_input(state, true)
end)
map(state, state.preview_buf, "n", "j", function()
move_selection(state, 1)
end)
map(state, state.preview_buf, "n", "k", function()
move_selection(state, -1)
end)
map(state, state.preview_buf, "n", "<C-n>", function()
move_selection(state, 1)
end)
map(state, state.preview_buf, "n", "<C-p>", function()
move_selection(state, -1)
end)
map(state, state.preview_buf, "n", "<C-g>", function()
fzy_selection(state)
end)
render(state)
schedule_search(state)
focus_input(state, true)
end
return M