-
Notifications
You must be signed in to change notification settings - Fork 13
Expand file tree
/
Copy pathcode.lua
More file actions
108 lines (101 loc) · 2.58 KB
/
code.lua
File metadata and controls
108 lines (101 loc) · 2.58 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
local M = {}
local gpt_provide = require("kide.gpt.provide")
---@type gpt.Client
local client = nil
function M.completions(param, callback)
local messages = {
{
content = "帮我生成一个快速排序",
role = "user",
},
{
content = "```python\n",
prefix = true,
role = "assistant",
},
}
messages[1].content = param.message
messages[2].content = "```" .. param.filetype .. "\n"
client = gpt_provide.new_client("code")
client:request(messages, callback)
end
M.code_completions = function(opts)
local codebuf = vim.api.nvim_get_current_buf()
local codewin = vim.api.nvim_get_current_win()
local filetype = vim.bo[codebuf].filetype
local closed = false
local message
if opts.inputcode then
message = "```" .. filetype .. "\n" .. table.concat(opts.inputcode, "\n") .. "```\n" .. opts.message
vim.api.nvim_win_set_cursor(codewin, { vim.fn.getpos("'>")[2] + 1, 0 })
else
message = opts.message
end
vim.api.nvim_create_autocmd("BufWipeout", {
buffer = codebuf,
callback = function()
closed = true
if client then
client:close()
end
end,
})
vim.keymap.set("n", "<C-c>", function()
closed = true
if client then
client:close()
end
vim.keymap.del("n", "<C-c>", { buffer = codebuf })
end, { buffer = codebuf, noremap = true, silent = true })
local callback = function(opt)
local data = opt.data
if closed then
vim.fn.jobstop(opt.job)
return
end
if opt.done then
return
end
local put_data = {}
if vim.api.nvim_buf_is_valid(codebuf) then
if data:match("\n") then
put_data = vim.split(data, "\n")
else
put_data = { data }
end
vim.api.nvim_put(put_data, "c", true, true)
end
end
M.completions({
filetype = filetype,
message = message,
}, callback)
end
M.setup = function()
local command = vim.api.nvim_buf_create_user_command
local autocmd = vim.api.nvim_create_autocmd
local function augroup(name)
return vim.api.nvim_create_augroup("kide" .. name, { clear = true })
end
autocmd("FileType", {
group = augroup("gpt_code_gen"),
pattern = "*",
callback = function(event)
command(event.buf, "GptCode", function(opts)
local code
if opts.range > 0 then
code = require("kide.tools").get_visual_selection()
end
M.code_completions({
inputcode = code,
message = opts.args,
})
end, {
desc = "Gpt Code",
nargs = "+",
range = true,
})
end,
})
end
return M