@@ -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