forked from CopilotC-Nvim/CopilotChat.nvim
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinit.lua
1414 lines (1216 loc) · 38.2 KB
/
init.lua
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 async = require('plenary.async')
local log = require('plenary.log')
local default_config = require('CopilotChat.config')
local Copilot = require('CopilotChat.copilot')
local context = require('CopilotChat.context')
local prompts = require('CopilotChat.prompts')
local utils = require('CopilotChat.utils')
local Chat = require('CopilotChat.ui.chat')
local Diff = require('CopilotChat.ui.diff')
local Overlay = require('CopilotChat.ui.overlay')
local Debug = require('CopilotChat.ui.debug')
local M = {}
local PLUGIN_NAME = 'CopilotChat'
local WORD = '([^%s]+)'
--- @class CopilotChat.source
--- @field bufnr number
--- @field winnr number
--- @class CopilotChat.state
--- @field copilot CopilotChat.Copilot?
--- @field source CopilotChat.source?
--- @field last_prompt string?
--- @field last_response string?
--- @field chat CopilotChat.ui.Chat?
--- @field diff CopilotChat.ui.Diff?
--- @field debug CopilotChat.ui.Debug?
--- @field overlay CopilotChat.ui.Overlay?
local state = {
copilot = nil,
-- Current state tracking
source = nil,
-- Last state tracking
last_prompt = nil,
last_response = nil,
-- Overlays
chat = nil,
diff = nil,
overlay = nil,
debug = nil,
}
---@param config CopilotChat.config.shared
---@return CopilotChat.select.selection?
local function get_selection(config)
local bufnr = state.source and state.source.bufnr
local winnr = state.source and state.source.winnr
if
config
and config.selection
and utils.buf_valid(bufnr)
and winnr
and vim.api.nvim_win_is_valid(winnr)
then
return config.selection(state.source)
end
return nil
end
--- Highlights the selection in the source buffer.
---@param clear boolean
---@param config CopilotChat.config.shared
local function highlight_selection(clear, config)
local selection_ns = vim.api.nvim_create_namespace('copilot-chat-selection')
for _, buf in ipairs(vim.api.nvim_list_bufs()) do
vim.api.nvim_buf_clear_namespace(buf, selection_ns, 0, -1)
end
if clear or not config.highlight_selection then
return
end
local selection = get_selection(config)
if
not selection
or not utils.buf_valid(selection.bufnr)
or not selection.start_line
or not selection.end_line
then
return
end
vim.api.nvim_buf_set_extmark(selection.bufnr, selection_ns, selection.start_line - 1, 0, {
hl_group = 'CopilotChatSelection',
end_row = selection.end_line,
strict = false,
})
end
--- Updates the selection based on previous window
---@param config CopilotChat.config.shared
local function update_selection(config)
local prev_winnr = vim.fn.win_getid(vim.fn.winnr('#'))
if prev_winnr ~= state.chat.winnr and vim.fn.win_gettype(prev_winnr) == '' then
state.source = {
bufnr = vim.api.nvim_win_get_buf(prev_winnr),
winnr = prev_winnr,
}
end
highlight_selection(false, config)
end
---@param config CopilotChat.config.shared
---@return CopilotChat.ui.Diff.Diff?
local function get_diff(config)
local block = state.chat:get_closest_block()
-- If no block found, return nil
if not block then
return nil
end
-- Initialize variables with selection if available
local header = block.header
local selection = get_selection(config)
local reference = selection and selection.content
local start_line = selection and selection.start_line
local end_line = selection and selection.end_line
local filename = selection and selection.filename
local filetype = selection and selection.filetype
local bufnr = selection and selection.bufnr
-- If we have header info, use it as source of truth
if header.start_line and header.end_line then
-- Try to find matching buffer and window
bufnr = nil
for _, win in ipairs(vim.api.nvim_list_wins()) do
local win_buf = vim.api.nvim_win_get_buf(win)
if utils.filename_same(vim.api.nvim_buf_get_name(win_buf), header.filename) then
bufnr = win_buf
break
end
end
filename = header.filename
filetype = header.filetype or vim.filetype.match({ filename = filename })
start_line = header.start_line
end_line = header.end_line
-- If we found a valid buffer, get the reference content
if bufnr and utils.buf_valid(bufnr) then
reference =
table.concat(vim.api.nvim_buf_get_lines(bufnr, start_line - 1, end_line, false), '\n')
filetype = vim.bo[bufnr].filetype
end
end
-- If we are missing info, there is no diff to be made
if not start_line or not end_line or not filename then
return nil
end
return {
change = block.content,
reference = reference or '',
filetype = filetype or '',
filename = filename,
start_line = start_line,
end_line = end_line,
bufnr = bufnr,
}
end
---@param winnr number
---@param bufnr number
---@param start_line number
---@param end_line number
---@param config CopilotChat.config.shared
local function jump_to_diff(winnr, bufnr, start_line, end_line, config)
pcall(vim.api.nvim_win_set_cursor, winnr, { start_line, 0 })
pcall(vim.api.nvim_buf_set_mark, bufnr, '<', start_line, 0, {})
pcall(vim.api.nvim_buf_set_mark, bufnr, '>', end_line, 0, {})
pcall(vim.api.nvim_buf_set_mark, bufnr, '[', start_line, 0, {})
pcall(vim.api.nvim_buf_set_mark, bufnr, ']', end_line, 0, {})
update_selection(config)
end
---@param diff CopilotChat.ui.Diff.Diff?
---@param config CopilotChat.config.shared
local function apply_diff(diff, config)
if not diff or not diff.bufnr then
return
end
local winnr = vim.fn.win_findbuf(diff.bufnr)[1]
if not winnr then
return
end
local lines = vim.split(diff.change, '\n', { trimempty = false })
vim.api.nvim_buf_set_lines(diff.bufnr, diff.start_line - 1, diff.end_line, false, lines)
jump_to_diff(winnr, diff.bufnr, diff.start_line, diff.start_line + #lines - 1, config)
end
---@param prompt string
---@param config CopilotChat.config.shared
---@return string, CopilotChat.config
local function resolve_prompts(prompt, config)
local prompts_to_use = M.prompts()
local depth = 0
local MAX_DEPTH = 10
local function resolve(inner_prompt, inner_config)
if depth >= MAX_DEPTH then
return inner_prompt, inner_config
end
depth = depth + 1
inner_prompt = string.gsub(inner_prompt, '/' .. WORD, function(match)
local p = prompts_to_use[match]
if p then
local resolved_prompt, resolved_config = resolve(p.prompt or '', p)
inner_config = vim.tbl_deep_extend('force', inner_config, resolved_config)
return resolved_prompt
end
return '/' .. match
end)
depth = depth - 1
return inner_prompt, inner_config
end
return resolve(prompt, config)
end
---@param prompt string
---@param config CopilotChat.config.shared
---@return table<CopilotChat.context.embed>, string
local function resolve_embeddings(prompt, config)
local contexts = {}
local function parse_context(prompt_context)
local split = vim.split(prompt_context, ':')
local context_name = table.remove(split, 1)
local context_input = vim.trim(table.concat(split, ':'))
if M.config.contexts[context_name] then
table.insert(contexts, {
name = context_name,
input = (context_input ~= '' and context_input or nil),
})
return true
end
return false
end
prompt = prompt:gsub('#' .. WORD, function(match)
if parse_context(match) then
return ''
end
return '#' .. match
end)
if config.context then
if type(config.context) == 'table' then
---@diagnostic disable-next-line: param-type-mismatch
for _, config_context in ipairs(config.context) do
parse_context(config_context)
end
else
parse_context(config.context)
end
end
local embeddings = utils.ordered_map()
for _, context_data in ipairs(contexts) do
local context_value = M.config.contexts[context_data.name]
for _, embedding in ipairs(context_value.resolve(context_data.input, state.source or {})) do
if embedding then
embeddings:set(embedding.filename, embedding)
end
end
end
return embeddings:values(), prompt
end
local function resolve_agent(prompt, config)
local agents = vim.tbl_keys(state.copilot:list_agents())
local selected_agent = config.agent
prompt = prompt:gsub('@' .. WORD, function(match)
if vim.tbl_contains(agents, match) then
selected_agent = match
return ''
end
return '@' .. match
end)
return selected_agent, prompt
end
local function resolve_model(prompt, config)
local models = vim.tbl_keys(state.copilot:list_models())
local selected_model = config.model
prompt = prompt:gsub('%$' .. WORD, function(match)
if vim.tbl_contains(models, match) then
selected_model = match
return ''
end
return '$' .. match
end)
return selected_model, prompt
end
---@param start_of_chat boolean?
local function finish(start_of_chat)
if not start_of_chat then
state.chat:append('\n\n')
end
state.chat:append(M.config.question_header .. M.config.separator .. '\n\n')
-- Reinsert sticky prompts from last prompt
if state.last_prompt then
local has_sticky = false
local lines = vim.split(state.last_prompt, '\n')
for _, line in ipairs(lines) do
if vim.startswith(line, '> ') then
state.chat:append(line .. '\n')
has_sticky = true
end
end
if has_sticky then
state.chat:append('\n')
end
end
state.chat:finish()
end
---@param err string|table|nil
---@param append_newline boolean?
local function show_error(err, append_newline)
err = err or 'Unknown error'
if type(err) == 'string' then
local message = err:match('^[^:]+:[^:]+:(.+)') or err
message = message:gsub('^%s*', '')
err = message
else
err = utils.make_string(err)
end
if append_newline then
state.chat:append('\n')
end
state.chat:append(M.config.error_header .. '\n```error\n' .. err .. '\n```')
finish()
end
--- Map a key to a function.
---@param name string
---@param bufnr number
---@param fn function
local function map_key(name, bufnr, fn)
local key = M.config.mappings[name]
if not key then
return
end
if key.normal and key.normal ~= '' then
vim.keymap.set(
'n',
key.normal,
fn,
{ buffer = bufnr, nowait = true, desc = PLUGIN_NAME .. ' ' .. name:gsub('_', ' ') }
)
end
if key.insert and key.insert ~= '' then
vim.keymap.set('i', key.insert, function()
-- If in insert mode and menu visible, use original key
if vim.fn.pumvisible() == 1 then
local used_key = key.insert == M.config.mappings.complete.insert and '<C-y>' or key.insert
if used_key then
vim.api.nvim_feedkeys(
vim.api.nvim_replace_termcodes(used_key, true, false, true),
'n',
false
)
end
else
fn()
end
end, { buffer = bufnr, desc = PLUGIN_NAME .. ' ' .. name:gsub('_', ' ') })
end
end
--- Get the info for a key.
---@param name string
---@param surround string|nil
---@return string
local function key_to_info(name, surround)
local key = M.config.mappings[name]
if not key then
return ''
end
if not surround then
surround = ''
end
local out = ''
if key.normal and key.normal ~= '' then
out = out .. surround .. key.normal .. surround
end
if key.insert and key.insert ~= '' and key.insert ~= key.normal then
if out ~= '' then
out = out .. ' or '
end
out = out .. surround .. key.insert .. surround .. ' in insert mode'
end
if out == '' then
return out
end
out = out .. ' to ' .. name:gsub('_', ' ')
if key.detail and key.detail ~= '' then
out = out .. '. ' .. key.detail
end
return out
end
local function trigger_complete()
local info = M.complete_info()
local bufnr = vim.api.nvim_get_current_buf()
local line = vim.api.nvim_get_current_line()
local cursor = vim.api.nvim_win_get_cursor(0)
local row = cursor[1]
local col = cursor[2]
if col == 0 or #line == 0 then
return
end
local prefix, cmp_start = unpack(vim.fn.matchstrpos(line:sub(1, col), info.pattern))
if not prefix then
return
end
if vim.startswith(prefix, '#') and vim.endswith(prefix, ':') then
local found_context = M.config.contexts[prefix:sub(2, -2)]
if found_context and found_context.input then
found_context.input(function(value)
if not value then
return
end
local value_str = tostring(value)
vim.api.nvim_buf_set_text(bufnr, row - 1, col, row - 1, col, { value_str })
vim.api.nvim_win_set_cursor(0, { row, col + #value_str })
end, state.source or {})
end
return
end
M.complete_items(function(items)
if vim.fn.mode() ~= 'i' then
return
end
vim.fn.complete(
cmp_start + 1,
vim.tbl_filter(function(item)
return vim.startswith(item.word:lower(), prefix:lower())
end, items)
)
end)
end
--- Get the completion info for the chat window, for use with custom completion providers
---@return table
function M.complete_info()
return {
triggers = { '@', '/', '#', '$' },
pattern = [[\%(@\|/\|#\|\$\)\S*]],
}
end
--- Get the completion items for the chat window, for use with custom completion providers
---@param callback function(table)
function M.complete_items(callback)
async.run(function()
local models = state.copilot:list_models()
local agents = state.copilot:list_agents()
local prompts_to_use = M.prompts()
local items = {}
for name, prompt in pairs(prompts_to_use) do
local kind = ''
local info = ''
if prompt.prompt then
kind = 'user'
info = prompt.prompt
elseif prompt.system_prompt then
kind = 'system'
info = prompt.system_prompt
end
items[#items + 1] = {
word = '/' .. name,
kind = kind,
info = info,
menu = prompt.description or '',
icase = 1,
dup = 0,
empty = 0,
}
end
for name, description in pairs(models) do
items[#items + 1] = {
word = '$' .. name,
kind = 'model',
menu = description,
icase = 1,
dup = 0,
empty = 0,
}
end
for name, description in pairs(agents) do
items[#items + 1] = {
word = '@' .. name,
kind = 'agent',
menu = description,
icase = 1,
dup = 0,
empty = 0,
}
end
for name, value in pairs(M.config.contexts) do
items[#items + 1] = {
word = '#' .. name,
kind = 'context',
menu = value.description or '',
icase = 1,
dup = 0,
empty = 0,
}
end
table.sort(items, function(a, b)
if a.kind == b.kind then
return a.word < b.word
end
return a.kind < b.kind
end)
async.util.scheduler()
callback(items)
end)
end
--- Get the prompts to use.
---@return table<string, CopilotChat.config.prompt>
function M.prompts()
local prompts_to_use = {}
for name, prompt in pairs(prompts) do
prompts_to_use[name] = {
system_prompt = prompt,
}
end
for name, prompt in pairs(M.config.prompts) do
local val = prompt
if type(prompt) == 'string' then
val = {
prompt = prompt,
}
end
prompts_to_use[name] = val
end
return prompts_to_use
end
--- Open the chat window.
---@param config CopilotChat.config.shared?
function M.open(config)
-- If we are already in chat window, do nothing
if state.chat:active() then
return
end
config = vim.tbl_deep_extend('force', M.config, config or {})
if config.headless then
return
end
utils.return_to_normal_mode()
state.chat:open(config)
state.chat:follow()
state.chat:focus()
end
--- Close the chat window.
function M.close()
state.chat:close(state.source and state.source.bufnr or nil)
end
--- Toggle the chat window.
---@param config CopilotChat.config.shared?
function M.toggle(config)
if state.chat:visible() then
M.close()
else
M.open(config)
end
end
--- Get the last response.
--- @returns string
function M.response()
return state.last_response
end
--- Select default Copilot GPT model.
function M.select_model()
async.run(function()
local models = vim.tbl_keys(state.copilot:list_models())
models = vim.tbl_map(function(model)
if model == M.config.model then
return model .. ' (selected)'
end
return model
end, models)
async.util.scheduler()
vim.ui.select(models, {
prompt = 'Select a model> ',
}, function(choice)
if choice then
M.config.model = choice:gsub(' %(selected%)', '')
end
end)
end)
end
--- Select default Copilot agent.
function M.select_agent()
async.run(function()
local agents = vim.tbl_keys(state.copilot:list_agents())
agents = vim.tbl_map(function(agent)
if agent == M.config.agent then
return agent .. ' (selected)'
end
return agent
end, agents)
async.util.scheduler()
vim.ui.select(agents, {
prompt = 'Select an agent> ',
}, function(choice)
if choice then
M.config.agent = choice:gsub(' %(selected%)', '')
end
end)
end)
end
--- Ask a question to the Copilot model.
---@param prompt string?
---@param config CopilotChat.config.shared?
function M.ask(prompt, config)
M.open(config)
prompt = vim.trim(prompt or '')
if prompt == '' then
return
end
vim.diagnostic.reset(vim.api.nvim_create_namespace('copilot_diagnostics'))
config = vim.tbl_deep_extend('force', state.chat.config, config or {})
config = vim.tbl_deep_extend('force', M.config, config or {})
if not config.headless then
if config.clear_chat_on_new_prompt then
M.stop(true)
elseif state.copilot:stop() then
finish()
end
state.last_prompt = prompt
state.chat:clear_prompt()
state.chat:append('\n\n' .. prompt)
state.chat:append('\n\n' .. config.answer_header .. config.separator .. '\n\n')
end
-- Resolve prompt references
local prompt, config = resolve_prompts(prompt, config)
local system_prompt = config.system_prompt
-- Remove sticky prefix
prompt = vim.trim(table.concat(
vim.tbl_map(function(l)
return l:gsub('^>%s+', '')
end, vim.split(prompt, '\n')),
'\n'
))
-- Retrieve the selection
local selection = get_selection(config)
local ok, err = pcall(async.run, function()
local embeddings, prompt = resolve_embeddings(prompt, config)
local selected_agent, prompt = resolve_agent(prompt, config)
local selected_model, prompt = resolve_model(prompt, config)
local has_output = false
local query_ok, filtered_embeddings =
pcall(context.filter_embeddings, state.copilot, prompt, embeddings)
if not query_ok then
async.util.scheduler()
log.error(filtered_embeddings)
if not config.headless then
show_error(filtered_embeddings, has_output)
end
return
end
local ask_ok, response, token_count, token_max_count =
pcall(state.copilot.ask, state.copilot, prompt, {
selection = selection,
embeddings = filtered_embeddings,
system_prompt = system_prompt,
model = selected_model,
agent = selected_agent,
temperature = config.temperature,
no_history = config.headless,
on_progress = vim.schedule_wrap(function(token)
if not config.headless then
state.chat:append(token)
end
has_output = true
end),
})
async.util.scheduler()
if not ask_ok then
log.error(response)
if not config.headless then
show_error(response, has_output)
end
return
end
if not response then
return
end
if not config.headless then
state.last_response = response
state.chat.token_count = token_count
state.chat.token_max_count = token_max_count
end
if not config.headless then
finish()
end
if config.callback then
config.callback(response, state.source)
end
end)
if not ok then
log.error(err)
if not config.headless then
show_error(err)
end
end
end
--- Stop current copilot output and optionally reset the chat ten show the help message.
---@param reset boolean?
function M.stop(reset)
if reset then
state.copilot:reset()
state.chat:clear()
state.last_prompt = nil
state.last_response = nil
else
state.copilot:stop()
end
finish(reset)
end
--- Reset the chat window and show the help message.
function M.reset()
M.stop(true)
end
--- Save the chat history to a file.
---@param name string?
---@param history_path string?
function M.save(name, history_path)
if not name or vim.trim(name) == '' then
name = 'default'
else
name = vim.trim(name)
end
history_path = history_path or M.config.history_path
if history_path then
state.copilot:save(name, history_path)
end
end
--- Load the chat history from a file.
---@param name string?
---@param history_path string?
function M.load(name, history_path)
if not name or vim.trim(name) == '' then
name = 'default'
else
name = vim.trim(name)
end
history_path = history_path or M.config.history_path
if not history_path then
return
end
state.copilot:reset()
state.chat:clear()
local history = state.copilot:load(name, history_path)
for i, message in ipairs(history) do
if message.role == 'user' then
if i > 1 then
state.chat:append('\n\n')
end
state.chat:append(M.config.question_header .. M.config.separator .. '\n\n')
state.chat:append(message.content)
elseif message.role == 'assistant' then
state.chat:append('\n\n' .. M.config.answer_header .. M.config.separator .. '\n\n')
state.chat:append(message.content)
end
end
finish(#history == 0)
end
--- Set the log level
---@param level string
function M.log_level(level)
M.config.log_level = level
M.config.debug = level == 'debug'
local logfile = string.format('%s/%s.log', vim.fn.stdpath('state'), PLUGIN_NAME)
log.new({
plugin = PLUGIN_NAME,
level = level,
outfile = logfile,
}, true)
log.logfile = logfile
end
--- Set up the plugin
---@param config CopilotChat.config?
function M.setup(config)
-- Handle changed configuration
if config then
if config.mappings then
for name, key in pairs(config.mappings) do
if type(key) == 'string' then
utils.deprecate(
'config.mappings.' .. name,
'config.mappings.' .. name .. '.normal and config.mappings.' .. name .. '.insert'
)
config.mappings[name] = {
normal = key,
}
end
if name == 'show_system_prompt' then
utils.deprecate('config.mappings.' .. name, 'config.mappings.show_info')
end
if name == 'show_user_context' or name == 'show_user_selection' then
utils.deprecate('config.mappings.' .. name, 'config.mappings.show_context')
end
end
end
if config['yank_diff_register'] then
utils.deprecate('config.yank_diff_register', 'config.mappings.yank_diff.register')
config.mappings.yank_diff.register = config['yank_diff_register']
end
end
-- Handle removed commands
vim.api.nvim_create_user_command('CopilotChatFixDiagnostic', function()
utils.deprecate('CopilotChatFixDiagnostic', 'CopilotChatFix')
M.ask('/Fix')
end, { force = true })
vim.api.nvim_create_user_command('CopilotChatCommitStaged', function()
utils.deprecate('CopilotChatCommitStaged', 'CopilotChatCommit')
M.ask('/Commit')
end, { force = true })
M.config = vim.tbl_deep_extend('force', default_config, config or {})
if state.copilot then
state.copilot:stop()
end
state.copilot = Copilot(M.config.proxy, M.config.allow_insecure)
if M.config.debug then
M.log_level('debug')
else
M.log_level(M.config.log_level)
end
vim.api.nvim_set_hl(0, 'CopilotChatSpinner', { link = 'DiagnosticInfo', default = true })
vim.api.nvim_set_hl(0, 'CopilotChatHelp', { link = 'DiagnosticInfo', default = true })
vim.api.nvim_set_hl(0, 'CopilotChatSelection', { link = 'Visual', default = true })
vim.api.nvim_set_hl(
0,
'CopilotChatHeader',
{ link = '@markup.heading.2.markdown', default = true }
)
vim.api.nvim_set_hl(
0,
'CopilotChatSeparator',
{ link = '@punctuation.special.markdown', default = true }
)
local overlay_help = key_to_info('close')
local diff_help = key_to_info('accept_diff')
if overlay_help ~= '' and diff_help ~= '' then
diff_help = diff_help .. '\n' .. overlay_help
end
if state.overlay then
state.overlay:delete()
end
state.overlay = Overlay('copilot-overlay', overlay_help, function(bufnr)
map_key('close', bufnr, function()
state.overlay:restore(state.chat.winnr, state.chat.bufnr)
end)
end)
if not state.debug then
state.debug = Debug()
end
if state.diff then
state.diff:delete()
end
state.diff = Diff(diff_help, function(bufnr)
map_key('close', bufnr, function()
state.diff:restore(state.chat.winnr, state.chat.bufnr)
end)
map_key('accept_diff', bufnr, function()
apply_diff(state.diff:get_diff(), state.chat.config)
end)
end)
if state.chat then
state.chat:close(state.source and state.source.bufnr or nil)
state.chat:delete()
end
state.chat = Chat(
M.config.question_header,
M.config.answer_header,
M.config.separator,
key_to_info('show_help'),
function(bufnr)
map_key('show_help', bufnr, function()
local chat_help = '**`Special tokens`**\n'
chat_help = chat_help .. '`@<agent>` to select an agent\n'
chat_help = chat_help .. '`#<context>` to select a context\n'
chat_help = chat_help .. '`#<context>:<input>` to select input for context\n'
chat_help = chat_help .. '`/<prompt>` to select a prompt\n'
chat_help = chat_help .. '`$<model>` to select a model\n'
chat_help = chat_help .. '`> <text>` to make a sticky prompt (copied to next prompt)\n'
chat_help = chat_help .. '\n**`Mappings`**\n'