xonecas.io
7415
Va

vim-ai-complete / commit 67d65b6

refactor: Allow user provided cli commands for LLM

- Still defaults to pi.

xonecas2026-06-13 67d65b63d0051a370daec178460b74addc2f7780 parent 18ebe44

4 files changed

.luarc.json+12−0
@@ -0,0 +1,12 @@
1+{
2+ "$schema": "https://raw.githubusercontent.com/LuaLS/vscode-lua/master/setting/schema.json",
3+ "runtime.version": "LuaJIT",
4+ "diagnostics.globals": [
5+ "vim"
6+ ],
7+ "workspace.checkThirdParty": false,
8+ "workspace.library": [
9+ "$VIMRUNTIME/lua",
10+ "$VIMRUNTIME/lua/vim/lsp"
11+ ]
12+}
README.md+22−6
@@ -1,22 +1,38 @@
11 # vim-ai-complete
22
3-A simple Neovim plugin that mimics Cursor's selection prompt and Zed's editor assist feature using the pi coding agent's non-interactive mode.
3+A simple Neovim plugin that mimics Cursor's selection prompt and Zed's editor assist feature using a configurable LLM CLI (`pi` by default).
44
5-## Pi as your LLM
5+## LLM command
66
7-Currently, the plugin expects `pi` to be installed and ready to use. The arguments this extension sends are the prompt and the read-only tool list, and it sets the thinking level to minimal for speed.
7+By default, the plugin uses `pi` with the original read-only tools and minimal thinking level:
8+
9+```lua
10+{ "pi", "-t", "read,find,ls,grep", "--thinking", "minimal", "-p", "{prompt}" }
11+```
12+
13+The generated prompt replaces `{prompt}`. On Neovim 0.10+, stdout becomes the replacement text; older versions fall back to Neovim's legacy `system()` output, which may include stderr.
14+
15+To use another CLI, call `setup()` from your Neovim config:
16+
17+```lua
18+require("ai_complete").setup({
19+ command = { "my-llm", "--prompt", "{prompt}" },
20+})
21+```
22+
23+If `{prompt}` is omitted, the prompt is appended as the final argument. For advanced cases, `command` may be a function that receives the prompt and returns the full argv list.
824
925 ## How to use
1026
1127 Select a visual block, line, or selection, and then type `:Ai <your prompt here>`. The selection will be replaced with the model's output.
12-You can give any kind of prompt, but the agent has no edit tools, so it can only reply with the new text, and it is instructed to do so.
28+You can give any kind of prompt. The plugin uses the configured command's output as the replacement, and the default prompt instructs it to return only that replacement.
1329 There is no visual feedback on submit, but if an error occurs, you will see it.
1430
15-Just select, prompt, and send. Then hope for the best. Each prompt is its own individual session; there is no continuation, though you can resume from pi itself.
31+Just select, prompt, and send. Then hope for the best. Each prompt is its own individual session; there is no continuation unless your configured CLI provides one.
1632
1733 ## How to install
1834
19-This plugin uses the standard Neovim plugin layout, so it should work with any plugin manager. Make sure the external `pi` executable is installed and available on Neovim's `$PATH`.
35+This plugin uses the standard Neovim plugin layout, so it should work with any plugin manager. Make sure `pi` is installed and available on Neovim's `$PATH`, or configure another LLM command.
2036
2137 ### lazy.nvim / LazyVim
2238
lua/ai_complete/init.lua+155−55
@@ -1,98 +1,198 @@
1--- Create a table that will hold everything this module exposes.
2--- In Lua plugins, returning a table like this lets other files call M.complete().
31 local M = {}
42
5--- Build the prompt that will be sent to the `pi` command-line tool.
6--- We include both editor context and the text the user selected so the tool knows
7--- exactly what file it is working on and what text it should transform.
8-local function prompt_for_pi(user_prompt, selected_text)
9- -- table.concat joins each line below with a newline, producing one readable
10- -- prompt instead of manually adding "\n" to every string.
3+local PROMPT_PLACEHOLDER = '{prompt}'
4+
5+local config = {
6+ command = {
7+ 'pi',
8+ '-t',
9+ 'read,find,ls,grep',
10+ '--thinking',
11+ 'minimal',
12+ '-p',
13+ PROMPT_PLACEHOLDER,
14+ },
15+}
16+
17+M.config = config
18+
19+function M.setup(opts)
20+ opts = opts or {}
21+
22+ if opts.command ~= nil then
23+ config.command = opts.command
24+ end
25+end
26+
27+local function validate_command(command)
28+ if type(command) ~= 'table' or #command == 0 then
29+ return nil, 'LLM command must be a non-empty argv list'
30+ end
31+
32+ local argv = {}
33+
34+ for i, arg in ipairs(command) do
35+ if type(arg) ~= 'string' then
36+ return nil, 'LLM command argument ' .. i .. ' must be a string'
37+ end
38+
39+ argv[i] = arg
40+ end
41+
42+ return argv
43+end
44+
45+local function command_for_prompt(prompt)
46+ local configured_command = config.command
47+
48+ if type(configured_command) == 'function' then
49+ local ok, command = pcall(function()
50+ return configured_command(prompt)
51+ end)
52+
53+ if not ok then
54+ return nil, 'LLM command failed to build: ' .. tostring(command)
55+ end
56+
57+ return validate_command(command)
58+ end
59+
60+ if type(configured_command) ~= 'table' then
61+ return nil, 'LLM command must be an argv list or function'
62+ end
63+
64+ local argv = {}
65+ local inserted_prompt = false
66+
67+ for i, arg in ipairs(configured_command) do
68+ if type(arg) ~= 'string' then
69+ return nil, 'LLM command argument ' .. i .. ' must be a string'
70+ end
71+
72+ local replaced, count = arg:gsub(PROMPT_PLACEHOLDER, function()
73+ return prompt
74+ end)
75+
76+ if count > 0 then
77+ inserted_prompt = true
78+ end
79+
80+ argv[i] = replaced
81+ end
82+
83+ if #argv == 0 then
84+ return nil, 'LLM command must be a non-empty argv list'
85+ end
86+
87+ -- If the template omits {prompt}, append it as the final argv item.
88+ if not inserted_prompt then
89+ table.insert(argv, prompt)
90+ end
91+
92+ return argv
93+end
94+
95+local function command_with_cwd(argv)
96+ -- Keep execution in Neovim's cwd without shell-joining user-provided args.
97+ local command = {
98+ 'sh',
99+ '-c',
100+ 'cd "$1" && shift && exec "$@"',
101+ 'sh',
102+ vim.fn.getcwd(),
103+ }
104+
105+ return vim.list_extend(command, argv)
106+end
107+
108+local function run_llm_command(argv)
109+ local command = command_with_cwd(argv)
110+
111+ if type(vim.system) == 'function' then
112+ local ok, result = pcall(function()
113+ return vim.system(command, { text = true }):wait()
114+ end)
115+
116+ if not ok then
117+ return nil, 'LLM command failed: ' .. tostring(result)
118+ end
119+
120+ if result.code ~= 0 then
121+ return nil, 'LLM command failed'
122+ end
123+
124+ return result.stdout or ''
125+ end
126+
127+ -- Neovim < 0.10 does not have vim.system(); this fallback may include stderr.
128+ local ok, output = pcall(vim.fn.system, command)
129+
130+ if not ok then
131+ return nil, 'LLM command failed: ' .. tostring(output)
132+ end
133+
134+ if vim.v.shell_error ~= 0 then
135+ return nil, 'LLM command failed'
136+ end
137+
138+ return output
139+end
140+
141+local function prompt_for_llm(user_prompt, selected_text)
11142 return table.concat({
12- -- Current file name, without directories. Example: "init.lua".
13143 'filename: ' .. vim.fn.expand('%:t'),
14- -- Full path to the current file, so the tool has precise context.
15144 'path: ' .. vim.fn.expand('%:p'),
16- -- The user's instruction, such as "add comments" or "refactor this".
17145 'prompt: ' .. user_prompt,
18- -- A label that separates metadata above from the selected text below.
19146 'selection:',
20- -- The actual text selected in Visual mode.
21147 selected_text,
22- -- The "system" prompt
23- 'Generate an exact replacement for the selected text using the user prompt and surrounding file context. Return only the replacement text.'
148+ 'Generate an exact replacement for the selected text using the user prompt and surrounding file context. Return only the replacement text.',
24149 }, '\n')
25150 end
26151
27--- Complete or rewrite the current visual selection using the external `pi` tool.
28--- `user_prompt` is the instruction typed by the user.
29--- `has_range` tells us whether Vim passed a visual range to this command.
30152 function M.complete(user_prompt, has_range)
31- -- This command only makes sense when text is selected. If there is no range,
32- -- show an error and stop before changing anything.
33153 if has_range == 0 then
34154 vim.notify('ai-complete: select text visually first', vim.log.levels.ERROR)
35155 return
36156 end
37157
38- -- We use register "z" as a temporary clipboard for the selected text and for
39- -- the replacement. Before touching it, save its contents and type so we can
40- -- restore the user's register exactly as it was.
158+ -- Use register z as scratch space, then restore it before returning.
41159 local old_z = vim.fn.getreg('z')
42160 local old_z_type = vim.fn.getregtype('z')
43161
44- -- Re-select the previous Visual selection (`gv`), then yank it into register z
45- -- (`"zy`). `silent normal!` runs the Normal-mode keys without extra messages or
46- -- user mappings, making the command predictable.
162+ -- `gv` restores the last Visual selection before yanking it into register z.
47163 vim.cmd([[silent normal! gv"zy]])
48164
49- -- Read the selected text and selection type from register z. The type matters:
50- -- it tells Vim whether the selection was characterwise, linewise, or blockwise.
51165 local selected_text = vim.fn.getreg('z')
52166 local selected_type = vim.fn.getregtype('z')
53167
54- -- Let the user know Neovim is about to block while pi generates a response.
168+ local llm_prompt = prompt_for_llm(user_prompt, selected_text)
169+ local command, command_error = command_for_prompt(llm_prompt)
170+
171+ if not command then
172+ vim.fn.setreg('z', old_z, old_z_type)
173+ vim.notify('ai-complete: ' .. command_error, vim.log.levels.ERROR)
174+ return
175+ end
176+
55177 vim.notify('ai-complete: generating...', vim.log.levels.INFO)
56178 vim.cmd('redraw')
57179
58- -- Call the external `pi` program with a prompt built from the user instruction
59- -- and the selected text from Vim's current working directory. The command's
60- -- stdout becomes `output`.
61- local output = vim.fn.system({
62- 'sh',
63- '-c',
64- 'cd "$1" && shift && exec "$@"',
65- 'sh',
66- vim.fn.getcwd(),
67- 'pi',
68- '-t',
69- 'read,find,ls,grep',
70- '--thinking',
71- 'minimal',
72- '-p',
73- prompt_for_pi(user_prompt, selected_text),
74- })
180+ local output, output_error = run_llm_command(command)
75181
76- -- If the shell command failed, restore register z, report the error, and leave
77- -- the buffer unchanged.
78- if vim.v.shell_error ~= 0 then
182+ if output == nil then
79183 vim.fn.setreg('z', old_z, old_z_type)
80- vim.notify('ai-complete: pi failed', vim.log.levels.ERROR)
184+ vim.notify('ai-complete: ' .. output_error, vim.log.levels.ERROR)
81185 return
82186 end
83187
84- -- Put the generated output into register z using the original selection type,
85- -- then re-select the same text and paste over it from register z.
188+ -- Preserve characterwise, linewise, or blockwise paste behavior.
86189 vim.fn.setreg('z', output, selected_type)
87190 vim.cmd([[silent normal! gv"zp]])
88191
89- -- Finally, restore register z so this plugin does not clobber the user's data.
90192 vim.fn.setreg('z', old_z, old_z_type)
91193
92- -- Let the user know we are done.
93194 vim.notify('ai-complete: done.', vim.log.levels.INFO)
94195 vim.cmd('redraw')
95196 end
96197
97--- Return the module table so Neovim can require() this file and call M.complete().
98198 return M
plugin/ai_complete.lua+1−7
@@ -1,21 +1,15 @@
1--- Guard against loading this plugin more than once in a Neovim session.
21 if vim.g.loaded_ai_complete == 1 then
32 return
43 end
54
6--- Mark the plugin as loaded so re-sourcing the runtime files is a no-op.
75 vim.g.loaded_ai_complete = 1
86
9--- Define :Ai as the public entry point for invoking ai_complete.
10--- Forward any command arguments and range information to the Lua module.
117 vim.api.nvim_create_user_command('Ai', function(opts)
128 require('ai_complete').complete(opts.args, opts.range)
139 end, {
14- -- Accept zero or more arguments after :Ai.
1510 nargs = '*',
16- -- Allow :Ai to be called with a line range.
1711 range = true,
1812 })
1913
20--- Neovim user commands must start with uppercase, so :ai is a tiny alias.
14+-- User commands must start uppercase; support :ai as an abbreviation.
2115 vim.cmd([[cabbrev ai Ai]])