Repository navigation
Expand file tree
/
Copy pathcontext.lua
More file actions
1845 lines (1594 loc) · 49.5 KB
/
Copy pathcontext.lua
File metadata and controls
1845 lines (1594 loc) · 49.5 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
-- Gathers editor context
local util = require('opencode.util')
local config = require('opencode.config')
local state = require('opencode.state')
local context_cache = require('opencode.context_cache')
local M = {}
local cache = { timestamp = 0, last_changedtick = 0, data = nil }
local cwd = vim.fn.getcwd()
local function is_in_cwd(path)
if not path or path == '' then
return false
end
return vim.startswith(vim.fn.fnamemodify(path, ':p'), cwd)
end
-- Privacy filter: redact paths outside project root
local function filter_path_privacy(path)
if not path or path == '' then
return path
end
-- Check if privacy filtering is enabled in config
if config.context and config.context.privacy_filter and config.context.privacy_filter.enabled == false then
return path
end
-- If path is within project, return as-is
if is_in_cwd(path) then
return path
end
-- Redact paths outside project root
local basename = vim.fn.fnamemodify(path, ':t')
return '[EXTERNAL]/' .. basename
end
-- Secret detection: check if content contains likely secrets
local function contains_secret(content)
if not content or content == '' then
return false
end
-- Check if secret filtering is enabled in config
if config.context and config.context.secret_filter and config.context.secret_filter.enabled == false then
return false
end
-- Common secret patterns
local secret_patterns = {
-- API keys and tokens (long alphanumeric strings)
'[%w%-_]+%.[%w%-_]+%.[%w%-_]+', -- JWT tokens (xxx.yyy.zzz)
'api[_%- ]?key[_%- ]?[:=][%s]*[\'"]?[%w%-_]+[\'"]?', -- API key assignments
'token[_%- ]?[:=][%s]*[\'"]?[%w%-_]+[\'"]?', -- Token assignments
'password[_%- ]?[:=][%s]*[\'"]?[%w%-_]+[\'"]?', -- Password assignments
'secret[_%- ]?[:=][%s]*[\'"]?[%w%-_]+[\'"]?', -- Secret assignments
-- Long hex strings (potential keys)
'[0-9a-fA-F]{32,}',
-- AWS-style keys
'AKIA[0-9A-Z]{16}',
-- Private keys
'%-%-%-%-%-BEGIN [%w%s]+ PRIVATE KEY%-%-%-%-%-',
}
for _, pattern in ipairs(secret_patterns) do
if content:match(pattern) then
return true
end
end
return false
end
M.context = {
-- current file
current_file = nil,
cursor_data = nil,
-- attachments
mentioned_files = nil,
mentioned_files_content = nil,
selections = nil,
linter_errors = nil,
mentioned_subagents = nil,
-- new context types
marks = nil,
jumplist = nil,
recent_buffers = nil,
undo_history = nil,
windows_tabs = nil,
highlights = nil,
session_info = nil,
registers = nil,
command_history = nil,
search_history = nil,
debug_data = nil,
lsp_context = nil,
plugin_versions = nil,
git_info = nil,
fold_info = nil,
cursor_surrounding = nil,
quickfix_loclist = nil,
macros = nil,
terminal_buffers = nil,
session_duration = nil,
}
-- Track session start time for duration calculation
M.session_start_time = vim.loop.hrtime()
-- Helper function to get cache TTL from config
local function get_cache_ttl(key, default)
local cfg = require('opencode.config').get()
if cfg.context and cfg.context.cache_ttl and cfg.context.cache_ttl[key] then
return cfg.context.cache_ttl[key]
end
return default or context_cache.DEFAULT_TTL
end
function M.unload_attachments()
M.context.mentioned_files = nil
M.context.mentioned_files_content = nil
M.context.selections = nil
M.context.linter_errors = nil
M.context.marks = nil
M.context.jumplist = nil
M.context.recent_buffers = nil
M.context.undo_history = nil
M.context.windows_tabs = nil
M.context.highlights = nil
M.context.session_info = nil
M.context.registers = nil
M.context.command_history = nil
M.context.search_history = nil
M.context.debug_data = nil
M.context.lsp_context = nil
M.context.plugin_versions = nil
M.context.git_info = nil
M.context.fold_info = nil
M.context.cursor_surrounding = nil
M.context.quickfix_loclist = nil
M.context.macros = nil
M.context.terminal_buffers = nil
M.context.session_duration = nil
end
function M.load()
local now = vim.uv.now()
local current_buf = vim.api.nvim_get_current_buf()
local current_changedtick = vim.b[current_buf].changedtick or 0
if cache.timestamp > 0 and now - cache.timestamp < 500 and current_changedtick == cache.last_changedtick then
if cache.data then
M.context = vim.deepcopy(cache.data)
end
return
end
if util.is_current_buf_a_file() then
local current_file = M.get_current_file()
local cursor_data = M.get_current_cursor_data()
M.context.current_file = current_file
M.context.cursor_data = cursor_data
M.context.linter_errors = M.check_linter_errors()
end
local current_selection = M.get_current_selection()
if current_selection then
local selection = M.new_selection(M.context.current_file, current_selection.text, current_selection.lines)
M.add_selection(selection)
end
-- Load new context types
M.context.marks = M.get_marks()
M.context.jumplist = M.get_jumplist()
M.context.recent_buffers = M.get_recent_buffers()
M.context.undo_history = M.get_undo_history()
M.context.windows_tabs = M.get_windows_tabs()
M.context.highlights = M.get_highlights()
M.context.session_info = M.get_session_info()
M.context.registers = M.get_registers()
M.context.command_history = M.get_command_history()
M.context.search_history = M.get_search_history()
M.context.debug_data = M.get_debug_data()
M.context.lsp_context = M.get_lsp_context()
M.context.plugin_versions = M.get_plugin_versions()
M.context.git_info = M.get_git_info()
M.context.fold_info = M.get_fold_info()
M.context.cursor_surrounding = M.get_cursor_surrounding()
M.context.quickfix_loclist = M.get_quickfix_loclist()
M.context.macros = M.get_macros()
M.context.terminal_buffers = M.get_terminal_buffers()
M.context.session_duration = M.get_session_duration()
cache.timestamp = now
cache.data = vim.deepcopy(M.context)
cache.last_changedtick = current_changedtick
end
function M.check_linter_errors()
local diagnostic_conf = config.context and config.context.diagnostics
if not diagnostic_conf then
return nil
end
local severity_levels = {}
if diagnostic_conf.error then
table.insert(severity_levels, vim.diagnostic.severity.ERROR)
end
if diagnostic_conf.warning then
table.insert(severity_levels, vim.diagnostic.severity.WARN)
end
if diagnostic_conf.info then
table.insert(severity_levels, vim.diagnostic.severity.INFO)
end
local diagnostics = vim.diagnostic.get(0, { severity = severity_levels })
if #diagnostics == 0 then
return nil
end
local lines = { 'Found ' .. #diagnostics .. ' error' .. (#diagnostics > 1 and 's' or '') .. ':' }
for _, diagnostic in ipairs(diagnostics) do
local line_number = diagnostic.lnum + 1
local short_message = diagnostic.message:gsub('%s+', ' '):gsub('^%s', ''):gsub('%s$', '')
table.insert(lines, string.format(' Line %d: %s', line_number, short_message))
end
return table.concat(lines, '\n')
end
function M.new_selection(file, content, lines)
return {
file = file,
content = util.indent_code_block(content),
lines = lines,
}
end
function M.add_selection(selection)
if not M.context.selections then
M.context.selections = {}
end
table.insert(M.context.selections, selection)
end
function M.add_file(file)
--- TODO: probably need a way to remove a file once it's been added?
--- maybe a keymap like clear all context?
if not M.context.mentioned_files then
M.context.mentioned_files = {}
end
local is_file = vim.fn.filereadable(file) == 1
local is_dir = vim.fn.isdirectory(file) == 1
if not is_file and not is_dir then
vim.notify('File not added to context. Could not read.')
return
end
file = vim.fn.fnamemodify(file, ':p')
if not vim.tbl_contains(M.context.mentioned_files, file) then
table.insert(M.context.mentioned_files, file)
end
end
M.clear_files = function()
M.context.mentioned_files = nil
M.context.mentioned_files_content = nil
end
function M.add_subagent(subagent)
if not M.context.mentioned_subagents then
M.context.mentioned_subagents = {}
end
if not vim.tbl_contains(M.context.mentioned_subagents, subagent) then
table.insert(M.context.mentioned_subagents, subagent)
end
end
M.clear_subagents = function()
M.context.mentioned_subagents = nil
end
---@param opts OpencodeContextConfig
function M.delta_context(opts)
opts = opts or config.context
if opts.enabled == false then
return {
current_file = nil,
mentioned_files = nil,
selections = nil,
linter_errors = nil,
cursor_data = nil,
mentioned_subagents = nil,
marks = nil,
jumplist = nil,
recent_buffers = nil,
undo_history = nil,
windows_tabs = nil,
highlights = nil,
session_info = nil,
registers = nil,
command_history = nil,
search_history = nil,
debug_data = nil,
lsp_context = nil,
plugin_versions = nil,
git_info = nil,
fold_info = nil,
cursor_surrounding = nil,
quickfix_loclist = nil,
macros = nil,
terminal_buffers = nil,
session_duration = nil,
}
end
local context = vim.deepcopy(M.context)
local last_context = state.last_sent_context
if not last_context then
return context
end
-- no need to send file context again
if
context.current_file
and last_context.current_file
and context.current_file.name == last_context.current_file.name
then
context.current_file = nil
end
-- no need to send subagents again
if
context.mentioned_subagents
and last_context.mentioned_subagents
and vim.deep_equal(context.mentioned_subagents, last_context.mentioned_subagents)
then
context.mentioned_subagents = nil
end
return context
end
function M.get_current_file()
if
not (
config.context
and config.context.enabled
and config.context.current_file
and config.context.current_file.enabled
)
then
return nil
end
local file = vim.fn.expand('%:p')
if not file or file == '' or vim.fn.filereadable(file) ~= 1 then
return nil
end
local bufnr = vim.api.nvim_get_current_buf()
local result = {
path = filter_path_privacy(file),
name = vim.fn.fnamemodify(file, ':t'),
extension = vim.fn.fnamemodify(file, ':e'),
}
-- Add filetype if available
local filetype = vim.bo[bufnr].filetype
if filetype and filetype ~= '' then
result.filetype = filetype
end
-- Add LSP client names if available
local clients = vim.lsp.get_active_clients({ bufnr = bufnr })
if #clients > 0 then
result.lsp_clients = {}
for _, client in ipairs(clients) do
table.insert(result.lsp_clients, client.name)
end
end
return result
end
function M.get_current_cursor_data()
if
not (
config.context
and config.context.enabled
and config.context.cursor_data
and config.context.cursor_data.enabled
)
then
return nil
end
local cursor_pos = vim.fn.getcurpos()
local cursor_content = vim.trim(vim.api.nvim_get_current_line())
return { line = cursor_pos[2], col = cursor_pos[3], line_content = cursor_content }
end
function M.get_current_selection()
if
not (config.context and config.context.enabled and config.context.selection and config.context.selection.enabled)
then
return nil
end
-- Return nil if not in a visual mode
if not vim.fn.mode():match('[vV\022]') then
return nil
end
-- Save current position and register state
local current_pos = vim.fn.getpos('.')
local old_reg = vim.fn.getreg('x')
local old_regtype = vim.fn.getregtype('x')
-- Capture selection text and position
vim.cmd('normal! "xy')
local text = vim.fn.getreg('x')
-- Get line numbers
vim.cmd('normal! `<')
local start_line = vim.fn.line('.')
vim.cmd('normal! `>')
local end_line = vim.fn.line('.')
-- Restore state
vim.fn.setreg('x', old_reg, old_regtype)
vim.cmd('normal! gv')
vim.api.nvim_feedkeys(vim.api.nvim_replace_termcodes('<Esc>', true, false, true), 'nx', true)
vim.fn.setpos('.', current_pos)
return {
text = text and text:match('[^%s]') and text or nil,
lines = start_line .. ', ' .. end_line,
}
end
-- Get marks (10 most recent)
function M.get_marks()
if not (config.context and config.context.enabled and config.context.marks and config.context.marks.enabled) then
return nil
end
local marks = vim.fn.getmarklist()
local limit = config.context.marks.limit or 10
local result = {}
for i = 1, math.min(#marks, limit) do
local mark = marks[i]
if mark.mark and mark.pos then
local file = vim.fn.fnamemodify(mark.file or vim.fn.bufname(mark.pos[1] or 0), ':p')
table.insert(result, {
mark = mark.mark,
line = mark.pos[2],
col = mark.pos[3],
file = file,
})
end
end
return #result > 0 and result or nil
end
-- Get jumplist (last 10 jumps)
function M.get_jumplist()
if
not (config.context and config.context.enabled and config.context.jumplist and config.context.jumplist.enabled)
then
return nil
end
local ok, jumplist, current = pcall(vim.fn.getjumplist)
if not ok or type(jumplist) ~= 'table' then
return nil
end
local limit = config.context.jumplist.limit or 10
local result = {}
-- Get the most recent jumps
local start_idx = math.max(1, #jumplist - limit + 1)
for i = start_idx, #jumplist do
local jump = jumplist[i]
if type(jump) == 'table' and jump.bufnr and jump.lnum then
table.insert(result, {
bufnr = jump.bufnr,
filename = filter_path_privacy(vim.fn.bufname(jump.bufnr)),
line = jump.lnum,
col = jump.col,
})
end
end
return #result > 0 and { jumps = result, current = current } or nil
end
-- Get recent buffers - unified function supporting both legacy and new API
-- Legacy API (no args): returns array of buffer info
-- New API (prompt, opts): returns OpencodeMessagePart[] for synthetic context
-- Get undo history (last 10 branches/changesets)
function M.get_undo_history()
if
not (
config.context
and config.context.enabled
and config.context.undo_history
and config.context.undo_history.enabled
)
then
return nil
end
local ok, undotree = pcall(vim.fn.undotree)
if not ok or not undotree or not undotree.entries then
return nil
end
local limit = config.context.undo_history.limit or 10
local result = {}
-- Get the most recent entries
local start_idx = math.max(1, #undotree.entries - limit + 1)
for i = start_idx, #undotree.entries do
local entry = undotree.entries[i]
table.insert(result, {
seq = entry.seq,
time = entry.time,
newhead = entry.newhead,
})
end
-- Check if current buffer has unsaved changes
local bufnr = vim.api.nvim_get_current_buf()
local has_unsaved_changes = vim.bo[bufnr].modified
-- Count total unsaved changes across all buffers
local unsaved_buffers = {}
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_is_loaded(buf) and vim.bo[buf].modified then
local bufname = vim.api.nvim_buf_get_name(buf)
if bufname and bufname ~= '' then
table.insert(unsaved_buffers, {
bufnr = buf,
name = filter_path_privacy(bufname),
})
end
end
end
return #result > 0
and {
entries = result,
seq_cur = undotree.seq_cur,
current_buffer_modified = has_unsaved_changes,
unsaved_buffers = #unsaved_buffers > 0 and unsaved_buffers or nil,
}
or nil
end
-- Get window and tab context
function M.get_windows_tabs()
if
not (
config.context
and config.context.enabled
and config.context.windows_tabs
and config.context.windows_tabs.enabled
)
then
return nil
end
local windows = {}
for _, win in ipairs(vim.api.nvim_list_wins()) do
local bufnr = vim.api.nvim_win_get_buf(win)
local filename = vim.fn.bufname(bufnr)
if is_in_cwd(filename) or filename == '' then -- Include empty buffers
table.insert(windows, {
id = win,
bufnr = bufnr,
filename = filter_path_privacy(filename),
})
end
end
local tabs = {}
for _, tab in ipairs(vim.api.nvim_list_tabpages()) do
table.insert(tabs, {
id = tab,
windows = vim.api.nvim_tabpage_list_wins(tab),
})
end
return { windows = windows, tabs = tabs, current_win = vim.api.nvim_get_current_win() }
end
-- Get buffer line highlights
function M.get_highlights()
if
not (config.context and config.context.enabled and config.context.highlights and config.context.highlights.enabled)
then
return nil
end
-- Cache based on buffer and changedtick to invalidate on buffer changes
local bufnr = vim.api.nvim_get_current_buf()
local changedtick = vim.b[bufnr].changedtick or 0
local cache_key = 'highlights_' .. bufnr .. '_' .. changedtick
local cached = context_cache.get(cache_key, get_cache_ttl('highlights', 2000))
if cached then
return cached
end
local matches = vim.fn.getmatches()
local result = {}
for _, match in ipairs(matches) do
table.insert(result, {
group = match.group,
pattern = match.pattern,
priority = match.priority,
})
end
-- Also get extmarks from current buffer if available
local ok, extmarks = pcall(vim.api.nvim_buf_get_extmarks, bufnr, -1, 0, -1, { details = true })
if ok and extmarks then
for _, extmark in ipairs(extmarks) do
if extmark[4] and extmark[4].hl_group then
table.insert(result, {
id = extmark[1],
line = extmark[2],
col = extmark[3],
hl_group = extmark[4].hl_group,
})
end
end
end
local final_result = #result > 0 and result or nil
context_cache.set(cache_key, final_result)
return final_result
end
-- Get session information
function M.get_session_info()
if
not (
config.context
and config.context.enabled
and config.context.session_info
and config.context.session_info.enabled
)
then
return nil
end
local session_name = vim.v.this_session
if session_name and session_name ~= '' then
return {
name = session_name,
cwd = vim.fn.getcwd(),
}
end
return nil
end
-- Get registers
function M.get_registers()
if
not (config.context and config.context.enabled and config.context.registers and config.context.registers.enabled)
then
return nil
end
local include = config.context.registers.include or { '"', '/', 'q' }
local result = {}
for _, reg in ipairs(include) do
local contents = vim.fn.getreg(reg)
local regtype = vim.fn.getregtype(reg)
if contents and contents ~= '' then
-- Filter out registers containing secrets
if not contains_secret(contents) then
result[reg] = {
contents = contents,
regtype = regtype,
}
else
result[reg] = {
contents = '[REDACTED: Potential secret detected]',
regtype = regtype,
}
end
end
end
return vim.tbl_count(result) > 0 and result or nil
end
-- Get command history
function M.get_command_history()
if
not (
config.context
and config.context.enabled
and config.context.command_history
and config.context.command_history.enabled
)
then
return nil
end
local limit = config.context.command_history.limit or 5
local result = {}
-- Get the last N commands
for i = -1, -limit, -1 do
local cmd = vim.fn.histget('cmd', i)
if cmd and cmd ~= '' then
table.insert(result, cmd)
end
end
return #result > 0 and result or nil
end
-- Get search history
function M.get_search_history()
if
not (
config.context
and config.context.enabled
and config.context.search_history
and config.context.search_history.enabled
)
then
return nil
end
local limit = config.context.search_history.limit or 5
local result = {}
-- Get the last N searches
for i = -1, -limit, -1 do
local search = vim.fn.histget('/', i)
if search and search ~= '' then
table.insert(result, search)
end
end
return #result > 0 and result or nil
end
-- Get debug data (nvim-dap)
function M.get_debug_data()
if
not (config.context and config.context.enabled and config.context.debug_data and config.context.debug_data.enabled)
then
return nil
end
local ok, dap = pcall(require, 'dap')
if not ok then
return nil
end
local session = dap.session()
if not session then
return nil
end
local breakpoints = dap.breakpoints.get()
local result = {
session_active = true,
breakpoints = {},
}
for buf, bps in pairs(breakpoints) do
local bufname = vim.fn.bufname(buf)
for _, bp in ipairs(bps) do
table.insert(result.breakpoints, {
file = bufname,
line = bp.line,
condition = bp.condition,
})
end
end
return result
end
-- Get LSP context
function M.get_lsp_context()
if
not (
config.context
and config.context.enabled
and config.context.lsp_context
and config.context.lsp_context.enabled
)
then
return nil
end
local bufnr = vim.api.nvim_get_current_buf()
local result = {}
-- Get diagnostics with more details
local diagnostics = vim.diagnostic.get(bufnr) or {}
local limit = config.context.lsp_context.diagnostics_limit or 10
result.diagnostics = {}
for i = 1, math.min(#diagnostics, limit) do
local diag = diagnostics[i]
table.insert(result.diagnostics, {
line = diag.lnum,
col = diag.col,
severity = diag.severity,
message = diag.message,
source = diag.source,
code = diag.code,
user_data = vim.inspect(diag.user_data), -- Add variables/context if available
})
end
-- Get code actions if enabled
if config.context.lsp_context.code_actions then
result.code_actions_available = false
-- Note: Getting code actions is async, so we just note if LSP is available
local clients = vim.lsp.get_active_clients({ bufnr = bufnr })
if #clients > 0 then
result.code_actions_available = true
result.lsp_clients = {}
for _, client in ipairs(clients) do
table.insert(result.lsp_clients, {
name = client.name,
id = client.id,
root_dir = client.config.root_dir,
})
end
end
end
-- Get document symbols
local params = vim.lsp.util.make_position_params()
local ok_sym, symbols_resp = pcall(vim.lsp.buf_request_sync, bufnr, 'textDocument/documentSymbol', params, 1000)
if ok_sym and symbols_resp and symbols_resp[1] and symbols_resp[1].result then
local symbols = symbols_resp[1].result
local flat_symbols = {}
local function flatten(s)
-- Filter out structural noise symbols (e.g., "[1]", "[2]", etc.)
if s.name and not s.name:match('^%[%d+%]$') then
table.insert(flat_symbols, {
name = s.name,
kind = s.kind,
range = s.range or { start = { 0, 0 }, ['end'] = { 0, 0 } },
detail = s.detail or '',
})
end
if s.children then
for _, c in ipairs(s.children) do
flatten(c)
end
end
end
for _, s in ipairs(symbols) do
flatten(s)
end
if #flat_symbols > 20 then
flat_symbols = vim.list_slice(flat_symbols, 1, 20)
end
result.symbols = flat_symbols
end
return (#result.diagnostics > 0 or result.code_actions_available or (result.symbols and #result.symbols > 0))
and result
or nil
end
-- Get Git information
function M.get_git_info()
if
not (config.context and config.context.enabled and config.context.git_info and config.context.git_info.enabled)
then
return nil
end
-- Check cache first (5 second TTL for git info)
local cache_key = 'git_info'
local cached = context_cache.get(cache_key, get_cache_ttl('git_info', 5000))
if cached then
return cached
end
local result = {}
-- Get current branch
local branch_ok, branch = pcall(vim.fn.systemlist, 'git rev-parse --abbrev-ref HEAD 2>/dev/null')
if branch_ok and branch[1] and branch[1] ~= '' then
result.branch = branch[1]
else
return nil
end
-- Get HEAD commit SHA (short form)
local sha_ok, sha = pcall(vim.fn.systemlist, 'git rev-parse --short HEAD 2>/dev/null')
if sha_ok and sha[1] and sha[1] ~= '' then
result.head_sha = sha[1]
end
-- Check if working tree is dirty
local status_ok, status = pcall(vim.fn.systemlist, 'git status --porcelain 2>/dev/null')
if status_ok and status then
result.is_dirty = #status > 0
-- Count staged and unstaged changes
local staged_count = 0
local unstaged_count = 0
for _, line in ipairs(status) do
if line and line ~= '' then
local index_status = line:sub(1, 1)
local work_status = line:sub(2, 2)
-- Staged changes (index column not space or ?)
if index_status ~= ' ' and index_status ~= '?' then
staged_count = staged_count + 1
end
-- Unstaged changes (work tree column not space)
if work_status ~= ' ' then
unstaged_count = unstaged_count + 1
end
end
end
if staged_count > 0 then
result.staged_changes = staged_count
end
if unstaged_count > 0 then
result.unstaged_changes = unstaged_count
end
end
-- Get file diff
local current_file = vim.fn.expand('%:p')
if current_file and current_file ~= '' and is_in_cwd(current_file) then
local diff_limit = config.context.git_info.diff_limit or 10
local diff_ok, diff = pcall(vim.fn.systemlist, string.format('git diff HEAD -- %s 2>/dev/null', current_file))
if diff_ok and diff then
result.file_diff = {}
for i = 1, math.min(#diff, diff_limit) do
table.insert(result.file_diff, diff[i])
end
end
end
-- Get recent changes
local changes_limit = config.context.git_info.changes_limit or 5
local log_ok, log = pcall(vim.fn.systemlist, string.format('git log --oneline -n %d 2>/dev/null', changes_limit))
if log_ok and log then
result.recent_changes = log
end
-- Cache the result
context_cache.set(cache_key, result)
return result
end
-- Get plugin versions from lazy-lock.json
function M.get_plugin_versions()
if
not (
config.context
and config.context.enabled
and config.context.plugin_versions
and config.context.plugin_versions.enabled
)
then
return nil
end
local lock_path = vim.fn.stdpath('data') .. '/lazy/lazy-lock.json'
if vim.fn.filereadable(lock_path) ~= 1 then
return nil
end
-- Check cache first with file modification time