-
-
Notifications
You must be signed in to change notification settings - Fork 96
/
Copy pathinit.lua
2007 lines (1726 loc) · 58.6 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
-- Gp (GPT prompt) lua plugin for Neovim
-- https://github.com/Robitx/gp.nvim/
--------------------------------------------------------------------------------
-- Module structure
--------------------------------------------------------------------------------
local config = require("gp.config")
local M = {
_Name = "Gp", -- plugin name
_state = {}, -- table of state variables
agents = {}, -- table of agents
cmd = {}, -- default command functions
config = {}, -- config variables
hooks = {}, -- user defined command functions
defaults = require("gp.defaults"), -- some useful defaults
deprecator = require("gp.deprecator"), -- handle deprecated options
dispatcher = require("gp.dispatcher"), -- handle communication with LLM providers
helpers = require("gp.helper"), -- helper functions
imager = require("gp.imager"), -- image generation module
logger = require("gp.logger"), -- logger module
render = require("gp.render"), -- render module
spinner = require("gp.spinner"), -- spinner module
tasker = require("gp.tasker"), -- tasker module
vault = require("gp.vault"), -- handles secrets
whisper = require("gp.whisper"), -- whisper module
}
--------------------------------------------------------------------------------
-- Module helper functions and variables
--------------------------------------------------------------------------------
local agent_completion = function()
local buf = vim.api.nvim_get_current_buf()
local file_name = vim.api.nvim_buf_get_name(buf)
if M.not_chat(buf, file_name) == nil then
return M._chat_agents
end
return M._command_agents
end
-- setup function
M._setup_called = false
---@param opts GpConfig? # table with options
M.setup = function(opts)
M._setup_called = true
math.randomseed(os.time())
-- make sure opts is a table
opts = opts or {}
if type(opts) ~= "table" then
M.logger.error(string.format("setup() expects table, but got %s:\n%s", type(opts), vim.inspect(opts)))
opts = {}
end
-- reset M.config
M.config = vim.deepcopy(config)
local curl_params = opts.curl_params or M.config.curl_params
local cmd_prefix = opts.cmd_prefix or M.config.cmd_prefix
local state_dir = opts.state_dir or M.config.state_dir
local openai_api_key = opts.openai_api_key or M.config.openai_api_key
M.logger.setup(opts.log_file or M.config.log_file, opts.log_sensitive)
M.vault.setup({ state_dir = state_dir, curl_params = curl_params })
M.vault.add_secret("openai_api_key", openai_api_key)
M.config.openai_api_key = nil
opts.openai_api_key = nil
M.dispatcher.setup({ providers = opts.providers, curl_params = curl_params })
M.config.providers = nil
opts.providers = nil
local image_opts = opts.image or {}
image_opts.state_dir = state_dir
image_opts.cmd_prefix = cmd_prefix
image_opts.secret = image_opts.secret or openai_api_key
M.imager.setup(image_opts)
M.config.image = nil
opts.image = nil
local whisper_opts = opts.whisper or {}
whisper_opts.style_popup_border = opts.style_popup_border or M.config.style_popup_border
whisper_opts.curl_params = curl_params
whisper_opts.cmd_prefix = cmd_prefix
M.whisper.setup(whisper_opts)
M.config.whisper = nil
opts.whisper = nil
-- merge nested tables
local mergeTables = { "hooks", "agents" }
for _, tbl in ipairs(mergeTables) do
M[tbl] = M[tbl] or {}
---@diagnostic disable-next-line
for k, v in pairs(M.config[tbl]) do
if tbl == "hooks" then
M[tbl][k] = v
elseif tbl == "agents" then
---@diagnostic disable-next-line
M[tbl][v.name] = v
end
end
M.config[tbl] = nil
opts[tbl] = opts[tbl] or {}
for k, v in pairs(opts[tbl]) do
if tbl == "hooks" then
M[tbl][k] = v
elseif tbl == "agents" then
M[tbl][v.name] = v
end
end
opts[tbl] = nil
end
for k, v in pairs(opts) do
if M.deprecator.is_valid(k, v) then
M.config[k] = v
end
end
M.deprecator.report()
-- make sure _dirs exists
for k, v in pairs(M.config) do
if k:match("_dir$") and type(v) == "string" then
M.config[k] = M.helpers.prepare_dir(v, k)
end
end
-- remove invalid agents
for name, agent in pairs(M.agents) do
if type(agent) ~= "table" or agent.disable then
M.agents[name] = nil
elseif not agent.model or not agent.system_prompt then
M.logger.warning(
"Agent "
.. name
.. " is missing model or system_prompt\n"
.. "If you want to disable an agent, use: { name = '"
.. name
.. "', disable = true },"
)
M.agents[name] = nil
end
end
-- prepare agent completions
M._chat_agents = {}
M._command_agents = {}
for name, agent in pairs(M.agents) do
M.agents[name].provider = M.agents[name].provider or "openai"
if M.dispatcher.providers[M.agents[name].provider] then
if agent.command then
table.insert(M._command_agents, name)
end
if agent.chat then
table.insert(M._chat_agents, name)
end
else
M.agents[name] = nil
end
end
table.sort(M._chat_agents)
table.sort(M._command_agents)
M.refresh_state()
if M.config.default_command_agent then
M.refresh_state({ command_agent = M.config.default_command_agent })
end
if M.config.default_chat_agent then
M.refresh_state({ chat_agent = M.config.default_chat_agent })
end
-- register user commands
for hook, _ in pairs(M.hooks) do
M.helpers.create_user_command(M.config.cmd_prefix .. hook, function(params)
if M.hooks[hook] ~= nil then
M.refresh_state()
M.logger.debug("running hook: " .. hook)
return M.hooks[hook](M, params)
end
M.logger.error("The hook '" .. hook .. "' does not exist.")
end)
end
local completions = {
ChatNew = { "popup", "split", "vsplit", "tabnew" },
ChatPaste = { "popup", "split", "vsplit", "tabnew" },
ChatToggle = { "popup", "split", "vsplit", "tabnew" },
ChatLast = { "popup", "split", "vsplit", "tabnew" },
Context = { "popup", "split", "vsplit", "tabnew" },
Agent = agent_completion,
}
-- register default commands
for cmd, _ in pairs(M.cmd) do
if M.hooks[cmd] == nil then
M.helpers.create_user_command(M.config.cmd_prefix .. cmd, function(params)
M.logger.debug("running command: " .. cmd)
M.refresh_state()
M.cmd[cmd](params)
end, completions[cmd])
end
end
M.buf_handler()
if vim.fn.executable("curl") == 0 then
M.logger.error("curl is not installed, run :checkhealth gp")
end
M.logger.debug("setup finished")
end
---@param update table | nil # table with options
M.refresh_state = function(update)
local state_file = M.config.state_dir .. "/state.json"
update = update or {}
local old_state = vim.deepcopy(M._state)
local disk_state = {}
if vim.fn.filereadable(state_file) ~= 0 then
disk_state = M.helpers.file_to_table(state_file) or {}
end
if not disk_state.updated then
local last = M.config.chat_dir .. "/last.md"
if vim.fn.filereadable(last) == 1 then
os.remove(last)
end
end
if not M._state.updated or (disk_state.updated and M._state.updated < disk_state.updated) then
M._state = vim.deepcopy(disk_state)
end
M._state.updated = os.time()
for k, v in pairs(update) do
M._state[k] = v
end
if not M._state.chat_agent or not M.agents[M._state.chat_agent] then
M._state.chat_agent = M._chat_agents[1]
end
if not M._state.command_agent or not M.agents[M._state.command_agent] then
M._state.command_agent = M._command_agents[1]
end
if M._state.last_chat and vim.fn.filereadable(M._state.last_chat) == 0 then
M._state.last_chat = nil
end
for k, _ in pairs(M._state) do
if M._state[k] ~= old_state[k] or M._state[k] ~= disk_state[k] then
M.logger.debug(
string.format(
"state[%s]: disk=%s old=%s new=%s",
k,
vim.inspect(disk_state[k]),
vim.inspect(old_state[k]),
vim.inspect(M._state[k])
)
)
end
end
M.helpers.table_to_file(M._state, state_file)
M.prepare_commands()
local buf = vim.api.nvim_get_current_buf()
local file_name = vim.api.nvim_buf_get_name(buf)
M.display_chat_agent(buf, file_name)
end
M.Target = {
rewrite = 0, -- for replacing the selection, range or the current line
append = 1, -- for appending after the selection, range or the current line
prepend = 2, -- for prepending before the selection, range or the current line
popup = 3, -- for writing into the popup window
-- for writing into a new buffer
---@param filetype nil | string # nil = same as the original buffer
---@return table # a table with type=4 and filetype=filetype
enew = function(filetype)
return { type = 4, filetype = filetype }
end,
--- for creating a new horizontal split
---@param filetype nil | string # nil = same as the original buffer
---@return table # a table with type=5 and filetype=filetype
new = function(filetype)
return { type = 5, filetype = filetype }
end,
--- for creating a new vertical split
---@param filetype nil | string # nil = same as the original buffer
---@return table # a table with type=6 and filetype=filetype
vnew = function(filetype)
return { type = 6, filetype = filetype }
end,
--- for creating a new tab
---@param filetype nil | string # nil = same as the original buffer
---@return table # a table with type=7 and filetype=filetype
tabnew = function(filetype)
return { type = 7, filetype = filetype }
end,
}
-- creates prompt commands for each target
M.prepare_commands = function()
for name, target in pairs(M.Target) do
-- uppercase first letter
local command = name:gsub("^%l", string.upper)
local cmd = function(params, whisper)
local agent = M.get_command_agent()
-- popup is like ephemeral one off chat
if target == M.Target.popup then
agent = M.get_chat_agent()
end
-- template is chosen dynamically based on mode in which the command is called
local template = M.config.template_command
if params.range > 0 then
template = M.config.template_selection
end
-- rewrite needs custom template
if target == M.Target.rewrite then
template = M.config.template_rewrite
end
if target == M.Target.append then
template = M.config.template_append
end
if target == M.Target.prepend then
template = M.config.template_prepend
end
if agent then
M.Prompt(params, target, agent, template, agent.cmd_prefix, whisper)
end
end
M.cmd[command] = function(params)
cmd(params)
end
if not M.whisper.disabled then
M.cmd["Whisper" .. command] = function(params)
M.whisper.Whisper(function(text)
vim.schedule(function()
cmd(params, text)
end)
end)
end
end
end
end
-- stop receiving gpt responses for all processes and clean the handles
---@param signal number | nil # signal to send to the process
M.cmd.Stop = function(signal)
M.tasker.stop(signal)
end
--------------------------------------------------------------------------------
-- Chat logic
--------------------------------------------------------------------------------
M._toggle = {}
M._toggle_kind = {
unknown = 0, -- unknown toggle
chat = 1, -- chat toggle
popup = 2, -- popup toggle
context = 3, -- context toggle
}
---@param kind number # kind of toggle
---@return boolean # true if toggle was closed
M._toggle_close = function(kind)
if
M._toggle[kind]
and M._toggle[kind].win
and M._toggle[kind].buf
and M._toggle[kind].close
and vim.api.nvim_win_is_valid(M._toggle[kind].win)
and vim.api.nvim_buf_is_valid(M._toggle[kind].buf)
and vim.api.nvim_win_get_buf(M._toggle[kind].win) == M._toggle[kind].buf
then
if #vim.api.nvim_list_wins() == 1 then
M.logger.warning("Can't close the last window.")
else
M._toggle[kind].close()
M._toggle[kind] = nil
end
return true
end
M._toggle[kind] = nil
return false
end
---@param kind number # kind of toggle
---@param toggle table # table containing `win`, `buf`, and `close` information
M._toggle_add = function(kind, toggle)
M._toggle[kind] = toggle
end
---@param kind string # string representation of the toggle kind
---@return number # numeric kind of the toggle
M._toggle_resolve = function(kind)
kind = kind:lower()
if kind == "chat" then
return M._toggle_kind.chat
elseif kind == "popup" then
return M._toggle_kind.popup
elseif kind == "context" then
return M._toggle_kind.context
end
M.logger.warning("Unknown toggle kind: " .. kind)
return M._toggle_kind.unknown
end
---@param buf number | nil # buffer number
M.prep_md = function(buf)
-- disable swapping for this buffer and set filetype to markdown
vim.api.nvim_command("setlocal noswapfile")
-- better text wrapping
vim.api.nvim_command("setlocal wrap linebreak")
-- auto save on TextChanged, InsertLeave
vim.api.nvim_command("autocmd TextChanged,InsertLeave <buffer=" .. buf .. "> silent! write")
-- register shortcuts local to this buffer
buf = buf or vim.api.nvim_get_current_buf()
-- ensure normal mode
vim.api.nvim_command("stopinsert")
M.helpers.feedkeys("<esc>", "xn")
end
---@param buf number # buffer number
---@param file_name string # file name
---@return string | nil # reason for not being a chat or nil if it is a chat
M.not_chat = function(buf, file_name)
file_name = vim.fn.resolve(file_name)
local chat_dir = vim.fn.resolve(M.config.chat_dir)
if not M.helpers.starts_with(file_name, chat_dir) then
return "resolved file (" .. file_name .. ") not in chat dir (" .. chat_dir .. ")"
end
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
if #lines < 5 then
return "file too short"
end
if not lines[1]:match("^# ") then
return "missing topic header"
end
local header_found = nil
for i = 1, 10 do
if i < #lines and lines[i]:match("^- file: ") then
header_found = true
break
end
end
if not header_found then
return "missing file header"
end
return nil
end
M.display_chat_agent = function(buf, file_name)
if M.not_chat(buf, file_name) then
return
end
if buf ~= vim.api.nvim_get_current_buf() then
return
end
local ns_id = vim.api.nvim_create_namespace("GpChatExt_" .. file_name)
vim.api.nvim_buf_clear_namespace(buf, ns_id, 0, -1)
vim.api.nvim_buf_set_extmark(buf, ns_id, 0, 0, {
strict = false,
right_gravity = true,
virt_text_pos = "right_align",
virt_text = {
{ "Current Agent: [" .. M._state.chat_agent .. "]", "DiagnosticHint" },
},
hl_mode = "combine",
})
end
M._prepared_bufs = {}
M.prep_chat = function(buf, file_name)
if M.not_chat(buf, file_name) then
return
end
if buf ~= vim.api.nvim_get_current_buf() then
return
end
M.refresh_state({ last_chat = file_name })
if M._prepared_bufs[buf] then
M.logger.debug("buffer already prepared: " .. buf)
return
end
M._prepared_bufs[buf] = true
M.prep_md(buf)
if M.config.chat_prompt_buf_type then
vim.api.nvim_set_option_value("buftype", "prompt", { buf = buf })
vim.fn.prompt_setprompt(buf, "")
vim.fn.prompt_setcallback(buf, function()
M.cmd.ChatRespond({ args = "" })
end)
end
-- setup chat specific commands
local range_commands = {
{
command = "ChatRespond",
modes = M.config.chat_shortcut_respond.modes,
shortcut = M.config.chat_shortcut_respond.shortcut,
comment = "GPT prompt Chat Respond",
},
{
command = "ChatNew",
modes = M.config.chat_shortcut_new.modes,
shortcut = M.config.chat_shortcut_new.shortcut,
comment = "GPT prompt Chat New",
},
}
for _, rc in ipairs(range_commands) do
local cmd = M.config.cmd_prefix .. rc.command .. "<cr>"
for _, mode in ipairs(rc.modes) do
if mode == "n" or mode == "i" then
M.helpers.set_keymap({ buf }, mode, rc.shortcut, function()
vim.api.nvim_command(M.config.cmd_prefix .. rc.command)
-- go to normal mode
vim.api.nvim_command("stopinsert")
M.helpers.feedkeys("<esc>", "xn")
end, rc.comment)
else
M.helpers.set_keymap({ buf }, mode, rc.shortcut, ":<C-u>'<,'>" .. cmd, rc.comment)
end
end
end
local ds = M.config.chat_shortcut_delete
M.helpers.set_keymap({ buf }, ds.modes, ds.shortcut, M.cmd.ChatDelete, "GPT prompt Chat Delete")
local ss = M.config.chat_shortcut_stop
M.helpers.set_keymap({ buf }, ss.modes, ss.shortcut, M.cmd.Stop, "GPT prompt Chat Stop")
-- conceal parameters in model header so it's not distracting
if M.config.chat_conceal_model_params then
vim.opt_local.conceallevel = 2
vim.opt_local.concealcursor = ""
vim.fn.matchadd("Conceal", [[^- model: .*model.:.[^"]*\zs".*\ze]], 10, -1, { conceal = "…" })
vim.fn.matchadd("Conceal", [[^- model: \zs.*model.:.\ze.*]], 10, -1, { conceal = "…" })
vim.fn.matchadd("Conceal", [[^- role: .\{64,64\}\zs.*\ze]], 10, -1, { conceal = "…" })
vim.fn.matchadd("Conceal", [[^- role: .[^\\]*\zs\\.*\ze]], 10, -1, { conceal = "…" })
end
end
M.buf_handler = function()
local gid = M.helpers.create_augroup("GpBufHandler", { clear = true })
M.helpers.autocmd({ "BufEnter" }, nil, function(event)
local buf = event.buf
if not vim.api.nvim_buf_is_valid(buf) then
return
end
local file_name = vim.api.nvim_buf_get_name(buf)
M.prep_chat(buf, file_name)
M.display_chat_agent(buf, file_name)
M.prep_context(buf, file_name)
end, gid)
M.helpers.autocmd({ "WinEnter" }, nil, function(event)
local buf = event.buf
if not vim.api.nvim_buf_is_valid(buf) then
return
end
local file_name = vim.api.nvim_buf_get_name(buf)
M.display_chat_agent(buf, file_name)
end, gid)
end
M.BufTarget = {
current = 0, -- current window
popup = 1, -- popup window
split = 2, -- split window
vsplit = 3, -- vsplit window
tabnew = 4, -- new tab
}
---@param params table | string # table with args or string args
---@return number # buf target
M.resolve_buf_target = function(params)
local args = ""
if type(params) == "table" then
args = params.args or ""
else
args = params
end
args = args:match("^%s*(.-)%s*$")
if args == "popup" then
return M.BufTarget.popup
elseif args == "split" then
return M.BufTarget.split
elseif args == "vsplit" then
return M.BufTarget.vsplit
elseif args == "tabnew" then
return M.BufTarget.tabnew
else
return M.BufTarget.current
end
end
---@param file_name string
---@param target number | nil # buf target
---@param kind number | nil # nil or a toggle kind, must be toggle kind when toggle is true
---@param toggle boolean # whether to toggle
---@return number # buffer number
M.open_buf = function(file_name, target, kind, toggle)
target = target or M.BufTarget.current
-- close previous popup if it exists
M._toggle_close(M._toggle_kind.popup)
if toggle then
---@cast kind number
M._toggle_close(kind)
end
local close, buf, win
if target == M.BufTarget.popup then
local old_buf = M.helpers.get_buffer(file_name)
buf, win, close, _ = M.render.popup(old_buf, M._Name .. " Popup", function(w, h)
local top = M.config.style_popup_margin_top or 2
local bottom = M.config.style_popup_margin_bottom or 8
local left = M.config.style_popup_margin_left or 1
local right = M.config.style_popup_margin_right or 1
local max_width = M.config.style_popup_max_width or 160
local ww = math.min(w - (left + right), max_width)
local wh = h - (top + bottom)
return ww, wh, top, (w - ww) / 2
end, { on_leave = false, escape = false, persist = true }, {
border = M.config.style_popup_border or "single",
zindex = M.config.zindex,
})
if not toggle then
M._toggle_add(M._toggle_kind.popup, { win = win, buf = buf, close = close })
end
if old_buf == nil then
-- read file into buffer and force write it
vim.api.nvim_command("silent 0read " .. file_name)
vim.api.nvim_command("silent file " .. file_name)
-- set the filetype to markdown
vim.api.nvim_set_option_value("filetype", "markdown", { buf = buf })
else
-- move cursor to the beginning of the file and scroll to the end
M.helpers.feedkeys("ggG", "xn")
end
-- delete whitespace lines at the end of the file
local last_content_line = M.helpers.last_content_line(buf)
vim.api.nvim_buf_set_lines(buf, last_content_line, -1, false, {})
-- insert a new line at the end of the file
vim.api.nvim_buf_set_lines(buf, -1, -1, false, { "" })
vim.api.nvim_command("silent write! " .. file_name)
elseif target == M.BufTarget.split then
vim.api.nvim_command("split " .. file_name)
elseif target == M.BufTarget.vsplit then
vim.api.nvim_command("vsplit " .. file_name)
elseif target == M.BufTarget.tabnew then
vim.api.nvim_command("tabnew " .. file_name)
else
-- is it already open in a buffer?
for _, b in ipairs(vim.api.nvim_list_bufs()) do
if vim.api.nvim_buf_get_name(b) == file_name then
for _, w in ipairs(vim.api.nvim_list_wins()) do
if vim.api.nvim_win_get_buf(w) == b then
vim.api.nvim_set_current_win(w)
return b
end
end
end
end
-- open in new buffer
vim.api.nvim_command("edit " .. file_name)
end
buf = vim.api.nvim_get_current_buf()
win = vim.api.nvim_get_current_win()
close = close or function() end
if not toggle then
return buf
end
vim.api.nvim_set_option_value("buflisted", false, { buf = buf })
if target == M.BufTarget.split or target == M.BufTarget.vsplit then
close = function()
if vim.api.nvim_win_is_valid(win) then
vim.api.nvim_win_close(win, true)
end
end
end
if target == M.BufTarget.tabnew then
close = function()
if vim.api.nvim_win_is_valid(win) then
local tab = vim.api.nvim_win_get_tabpage(win)
vim.api.nvim_set_current_tabpage(tab)
vim.api.nvim_command("tabclose")
end
end
end
M._toggle_add(kind, { win = win, buf = buf, close = close })
return buf
end
---@param params table # vim command parameters such as range, args, etc.
---@param toggle boolean # whether chat is toggled
---@param system_prompt string | nil # system prompt to use
---@param agent table | nil # obtained from get_command_agent or get_chat_agent
---@return number # buffer number
M.new_chat = function(params, toggle, system_prompt, agent)
M._toggle_close(M._toggle_kind.popup)
local filename = M.config.chat_dir .. "/" .. M.logger.now() .. ".md"
-- encode as json if model is a table
local model = ""
local provider = ""
if agent and agent.model and agent.provider then
model = agent.model
provider = agent.provider
if type(model) == "table" then
model = "- model: " .. vim.json.encode(model) .. "\n"
else
model = "- model: " .. model .. "\n"
end
provider = "- provider: " .. provider:gsub("\n", "\\n") .. "\n"
end
-- display system prompt as single line with escaped newlines
if system_prompt then
system_prompt = "- role: " .. system_prompt:gsub("\n", "\\n") .. "\n"
else
system_prompt = ""
end
local template = M.render.template(M.config.chat_template or require("gp.defaults").chat_template, {
["{{filename}}"] = string.match(filename, "([^/]+)$"),
["{{optional_headers}}"] = model .. provider .. system_prompt,
["{{user_prefix}}"] = M.config.chat_user_prefix,
["{{respond_shortcut}}"] = M.config.chat_shortcut_respond.shortcut,
["{{cmd_prefix}}"] = M.config.cmd_prefix,
["{{stop_shortcut}}"] = M.config.chat_shortcut_stop.shortcut,
["{{delete_shortcut}}"] = M.config.chat_shortcut_delete.shortcut,
["{{new_shortcut}}"] = M.config.chat_shortcut_new.shortcut,
})
-- escape underscores (for markdown)
template = template:gsub("_", "\\_")
local cbuf = vim.api.nvim_get_current_buf()
-- strip leading and trailing newlines
template = template:gsub("^%s*(.-)%s*$", "%1") .. "\n"
-- create chat file
vim.fn.writefile(vim.split(template, "\n"), filename)
local target = M.resolve_buf_target(params)
local buf = M.open_buf(filename, target, M._toggle_kind.chat, toggle)
if params.range == 2 then
M.render.append_selection(params, cbuf, buf, M.config.template_selection)
end
M.helpers.feedkeys("G", "xn")
return buf
end
---@param params table
---@param system_prompt string | nil
---@param agent table | nil # obtained from get_command_agent or get_chat_agent
---@return number # buffer number
M.cmd.ChatNew = function(params, system_prompt, agent)
if M.deprecator.has_old_chat_signature(agent) then
return -1
end
-- if chat toggle is open, close it and start a new one
if M._toggle_close(M._toggle_kind.chat) then
params.args = params.args or ""
if params.args == "" then
params.args = M.config.toggle_target
end
return M.new_chat(params, true, system_prompt, agent)
end
return M.new_chat(params, false, system_prompt, agent)
end
---@param params table
---@param system_prompt string | nil
---@param agent table | nil # obtained from get_command_agent or get_chat_agent
M.cmd.ChatToggle = function(params, system_prompt, agent)
if M._toggle_close(M._toggle_kind.popup) then
return
end
if M._toggle_close(M._toggle_kind.chat) and params.range ~= 2 then
return
end
-- create new chat file otherwise
params.args = params.args or ""
if params.args == "" then
params.args = M.config.toggle_target
end
-- if the range is 2, we want to create a new chat file with the selection
if params.range ~= 2 then
local last = M._state.last_chat
if last and vim.fn.filereadable(last) == 1 then
last = vim.fn.resolve(last)
M.open_buf(last, M.resolve_buf_target(params), M._toggle_kind.chat, true)
return
end
end
M.new_chat(params, true, system_prompt, agent)
end
---@param params table
---@return number | nil # buffer number or nil if no last chat
M.cmd.ChatLast = function(params)
local toggle = false
-- if the range is 2, we want to create a new chat file with the selection
if M._toggle_close(M._toggle_kind.chat) then
params.args = params.args or ""
if params.args == "" then
params.args = M.config.toggle_target
end
toggle = true
end
local last = M._state.last_chat
if last and vim.fn.filereadable(last) == 1 then
last = vim.fn.resolve(last)
-- get current buffer, for pasting selection if necessary
local cbuf = vim.api.nvim_get_current_buf()
local buf = M.helpers.get_buffer(last)
local win_found = false
if buf then
for _, w in ipairs(vim.api.nvim_list_wins()) do
if vim.api.nvim_win_get_buf(w) == buf then
vim.api.nvim_set_current_win(w)
vim.api.nvim_set_current_buf(buf)
win_found = true
break
end
end
end
buf = win_found and buf or M.open_buf(last, M.resolve_buf_target(params), toggle and M._toggle_kind.chat or nil, toggle)
-- if there is a selection, paste it
if params.range == 2 then
M.render.append_selection(params, cbuf, buf, M.config.template_selection)
M.helpers.feedkeys("G", "xn")
end
return buf
end
return nil
end
M.cmd.ChatPaste = function(params)
-- if there is no selection, do nothing
if params.range ~= 2 then
M.logger.warning("Please select some text to paste into the chat.")
return
end
-- get current buffer
local cbuf = vim.api.nvim_get_current_buf()
-- make new chat if last doesn't exist
local last = M._state.last_chat
if not last or vim.fn.filereadable(last) ~= 1 then
-- skip rest since new chat will handle snippet on it's own
M.cmd.ChatNew(params, nil, nil)
return
end
params.args = params.args or ""
if params.args == "" then
params.args = M.config.toggle_target
end
local target = M.resolve_buf_target(params)
last = vim.fn.resolve(last)
local buf = M.helpers.get_buffer(last)
local win_found = false
if buf then
for _, w in ipairs(vim.api.nvim_list_wins()) do
if vim.api.nvim_win_get_buf(w) == buf then
vim.api.nvim_set_current_win(w)
vim.api.nvim_set_current_buf(buf)
win_found = true
break
end
end
end
buf = win_found and buf or M.open_buf(last, target, M._toggle_kind.chat, true)
M.render.append_selection(params, cbuf, buf, M.config.template_selection)
M.helpers.feedkeys("G", "xn")
end
M.cmd.ChatDelete = function()
-- get buffer and file
local buf = vim.api.nvim_get_current_buf()
local file_name = vim.api.nvim_buf_get_name(buf)
-- check if file is in the chat dir
if not M.helpers.starts_with(file_name, vim.fn.resolve(M.config.chat_dir)) then
M.logger.warning("File " .. vim.inspect(file_name) .. " is not in chat dir")
return
end
-- delete without confirmation
if not M.config.chat_confirm_delete then
M.helpers.delete_file(file_name)
return
end
-- ask for confirmation
vim.ui.input({ prompt = "Delete " .. file_name .. "? [y/N] " }, function(input)
if input and input:lower() == "y" then
M.helpers.delete_file(file_name)
end
end)
end
M.chat_respond = function(params)
local buf = vim.api.nvim_get_current_buf()
local win = vim.api.nvim_get_current_win()
if M.tasker.is_busy(buf) then
return
end
-- go to normal mode
vim.cmd("stopinsert")
-- get all lines
local lines = vim.api.nvim_buf_get_lines(buf, 0, -1, false)
-- check if file looks like a chat file
local file_name = vim.api.nvim_buf_get_name(buf)
local reason = M.not_chat(buf, file_name)
if reason then
M.logger.warning("File " .. vim.inspect(file_name) .. " does not look like a chat file: " .. vim.inspect(reason))
return
end
-- headers are fields before first ---