在Lunarvim/Neovim中流畅地使用ChatGPT

效果展示

与 ChatGPT 对话

通过命令行模式输入NeoAI可以在终端右侧唤出对话框，体验模式和浏览器一样，并且速度和使用浏览器一样快。

点击Esc键可隐藏对话框。需要注意的是，每次重新输入NeoAI都相当于打开来一次新会话。

那么如何在隐藏对话框后不开启新会话且重新唤出对话框呢？

解释代码

通过视图模式选中要传入的代码，然后在命令行模式输入NeoAIContext相当于复制并发送了被选中的代码到 ChatGPT，使得 ChatGPT 能基于你提供的代码信息进行更准确地回答。

如果直接在命令行模式输入NeoAIContext相当于复制并发送整个缓冲区。

写文档

命令行模式输入NeoAIInject 要书写的文档主题，ChatGPT 会生成对应文档并插入到当前打开的文件中。

配置使用

添加插件

对于 Lunarvim 用户，只需将如下代码添加到 lvim.plugins 中即可：

Copy
{
"Bryley/neoai.nvim",
dependencies = {
"MunifTanjim/nui.nvim",
},
cmd = {
"NeoAI",
"NeoAIOpen",
"NeoAIClose",
"NeoAIToggle",
"NeoAIContext",
"NeoAIContextOpen",
"NeoAIContextClose",
"NeoAIInject",
"NeoAIInjectCode",
"NeoAIInjectContext",
"NeoAIInjectContextCode",
},
keys = {
{ "<leader>as", desc = "summarize text" },
{ "<leader>ag", desc = "generate git message" },
},
config = function()
require('neoai').setup {
-- Below are the default options, feel free to override what you would like changed
ui = {
output_popup_text = "NeoAI",
input_popup_text = "Prompt",
width = 30, -- As percentage eg. 30%
output_popup_height = 80, -- As percentage eg. 80%
submit = "<Enter>", -- Key binding to submit the prompt
},
models = {
{
name = "openai",
model = "gpt-3.5-turbo",
params = nil,
},
},
register_output = {
["g"] = function(output)
return output
end,
["c"] = require("neoai.utils").extract_code_snippets,
},
inject = {
cutoff_width = 75,
},
prompts = {
context_prompt = function(context)
return "Hey, I'd like to provide some context for future "
.. "messages. Here is the code/text that I want to refer "
.. "to in our upcoming conversations:\n\n"
.. context
end,
},
mappings = {
["select_up"] = "<C-k>",
["select_down"] = "<C-j>",
},
open_api_key_env = "OPENAI_API_KEY",
shortcuts = {
{
name = "textify",
key = "<leader>as",
desc = "fix text with AI",
use_context = true,
prompt = [[
Please rewrite the text to make it more readable, clear,
concise, and fix any grammatical, punctuation, or spelling
errors
]],
modes = { "v" },
strip_function = nil,
},
{
name = "gitcommit",
key = "<leader>ag",
desc = "generate git commit message",
use_context = false,
prompt = function()
return [[
Using the following git diff generate a consise and
clear git commit message, with a short title summary
that is 75 characters or less:
]] .. vim.fn.system("git diff --cached")
end,
modes = { "n" },
strip_function = nil,
},
},
}
end
},

添加 OPENAI_API_KEY 环境变量

打开～/.zshrc（如果你使用的是 bash 的话，则打开～/.bashrc)
Copy
sudo vim ~/.zshrc

在末尾添加如下内容（注意换成你自己的 OPENAI token）
Copy
export OPENAI_API_KEY=sk-kSynjjGgqIdsgVIK7iyz$$$$$$$$$$$$KFYkQwJxM8

保存退出（命令行模式输入wq)

使修改生效
Copy
source ~/.zshrc