xonecas.io
7415
Va

vim-ai-complete / files

vim-ai-complete / lua / ai_complete / init.lua

10.9 KB
1local M = {}
2
3-- Constants and module state
4
5local PROMPT_PLACEHOLDER = '{prompt}'
6local REPLACEMENT_INSTRUCTION =
7  'Generate an exact replacement for the selected text using the user prompt and surrounding file context. Return only the replacement text exactly as it should appear in the file. Do not add commentary, formatting wrappers, or surrounding code fences.'
8local COMPLETION_INSTRUCTION =
9  'Complete the text at the cursor based on the surrounding context. Decide what and how much to insert, and read additional context as needed. Return only the text to insert, without repeating existing text, commentary, formatting wrappers, or surrounding code fences.'
10
11---@class AiCompletePromptState
12---@field changedtick integer
13---@field closed boolean
14---@field opts { range: integer, line1: integer, line2: integer }
15---@field prompt_buf integer
16---@field prompt_win integer
17---@field source_buf integer
18---@field source_win integer
19
20---@type AiCompletePromptState?
21local active_prompt
22
23local config = {
24  command = {
25    'pi',
26    '-t',
27    'read,find,ls,grep',
28    '--thinking',
29    'high',
30    '-p',
31    PROMPT_PLACEHOLDER,
32  },
33}
34
35M.config = config
36
37function M.setup(opts)
38  opts = opts or {}
39
40  if opts.command ~= nil then
41    config.command = opts.command
42  end
43end
44
45-- Shared feedback, file context, and LLM execution
46
47local function notify_error(message)
48  vim.notify('ai-complete: ' .. message, vim.log.levels.ERROR)
49end
50
51local function notify_done()
52  vim.notify('ai-complete: done.', vim.log.levels.INFO)
53  vim.cmd('redraw')
54end
55
56local function file_context()
57  return 'filename: ' .. vim.fn.expand('%:t') .. '\npath: ' .. vim.fn.expand('%:p')
58end
59
60local function validate_command(command)
61  if type(command) ~= 'table' or #command == 0 then
62    return nil, 'LLM command must be a non-empty argv list'
63  end
64
65  local argv = {}
66
67  for i, arg in ipairs(command) do
68    if type(arg) ~= 'string' then
69      return nil, 'LLM command argument ' .. i .. ' must be a string'
70    end
71
72    argv[i] = arg
73  end
74
75  return argv
76end
77
78local function command_for_prompt(prompt)
79  local configured_command = config.command
80
81  if type(configured_command) == 'function' then
82    local ok, command = pcall(function()
83      return configured_command(prompt)
84    end)
85
86    if not ok then
87      return nil, 'LLM command failed to build: ' .. tostring(command)
88    end
89
90    return validate_command(command)
91  end
92
93  if type(configured_command) ~= 'table' then
94    return nil, 'LLM command must be an argv list or function'
95  end
96
97  local argv = {}
98  local inserted_prompt = false
99
100  for i, arg in ipairs(configured_command) do
101    if type(arg) ~= 'string' then
102      return nil, 'LLM command argument ' .. i .. ' must be a string'
103    end
104
105    local replaced, count = arg:gsub(PROMPT_PLACEHOLDER, function()
106      return prompt
107    end)
108
109    if count > 0 then
110      inserted_prompt = true
111    end
112
113    argv[i] = replaced
114  end
115
116  if #argv == 0 then
117    return nil, 'LLM command must be a non-empty argv list'
118  end
119
120  -- If the template omits {prompt}, append it as the final argv item.
121  if not inserted_prompt then
122    table.insert(argv, prompt)
123  end
124
125  return argv
126end
127
128local function command_with_cwd(argv)
129  -- Keep execution in Neovim's cwd without shell-joining user-provided args.
130  local command = {
131    'sh',
132    '-c',
133    'cd "$1" && shift && exec "$@"',
134    'sh',
135    vim.fn.getcwd(),
136  }
137
138  return vim.list_extend(command, argv)
139end
140
141local function command_failure(code, output)
142  local details = vim.trim(output or '')
143  return 'LLM command failed (exit ' .. code .. ')' .. (details ~= '' and ': ' .. details or '')
144end
145
146local function run_llm_command(argv)
147  local command = command_with_cwd(argv)
148
149  if type(vim.system) == 'function' then
150    local ok, result = pcall(function()
151      return vim.system(command, { text = true }):wait()
152    end)
153
154    if not ok then
155      return nil, 'LLM command failed: ' .. tostring(result)
156    end
157
158    if result.code ~= 0 then
159      return nil, command_failure(result.code, result.stderr)
160    end
161
162    return result.stdout or ''
163  end
164
165  -- Neovim < 0.10 does not have vim.system(); this fallback may include stderr.
166  local ok, output = pcall(vim.fn.system, command)
167
168  if not ok then
169    return nil, 'LLM command failed: ' .. tostring(output)
170  end
171
172  if vim.v.shell_error ~= 0 then
173    return nil, command_failure(vim.v.shell_error, output)
174  end
175
176  return output
177end
178
179local function generate(prompt)
180  local command, command_error = command_for_prompt(prompt)
181
182  if not command then
183    error(command_error, 0)
184  end
185
186  vim.notify('ai-complete: Generating...', vim.log.levels.INFO)
187  vim.cmd('redraw')
188
189  local output, output_error = run_llm_command(command)
190
191  if output == nil then
192    error(output_error, 0)
193  end
194
195  return output
196end
197
198-- Feature: replace a visual selection
199
200local function prompt_for_selection(user_prompt, selected_text)
201  return table.concat({
202    file_context(),
203    'prompt: ' .. user_prompt,
204    'selection:',
205    selected_text,
206    REPLACEMENT_INSTRUCTION,
207  }, '\n')
208end
209
210function M.complete(user_prompt, has_range)
211  if has_range == 0 then
212    notify_error('select text visually first')
213    return
214  end
215
216  -- Restore scratch register z even if yanking, generation, or replacement fails.
217  local old_z = vim.fn.getreg('z', 1, true)
218  local old_z_type = vim.fn.getregtype('z')
219
220  local ok, err = pcall(function()
221    -- `gv` restores the last Visual selection before yanking it into register z.
222    vim.cmd([[silent normal! gv"zy]])
223
224    local selected_text = vim.fn.getreg('z')
225    local selected_type = vim.fn.getregtype('z')
226
227    local output = generate(prompt_for_selection(user_prompt, selected_text))
228
229    -- Preserve characterwise, linewise, or blockwise paste behavior.
230    vim.fn.setreg('z', output, selected_type)
231    vim.cmd([[silent normal! gv"zp]])
232  end)
233
234  vim.fn.setreg('z', old_z, old_z_type)
235
236  if not ok then
237    notify_error(tostring(err))
238    return
239  end
240
241  notify_done()
242end
243
244local function has_visual_range(opts)
245  if opts.range ~= 2 then
246    return false
247  end
248
249  local start_mark = vim.fn.getpos("'<")
250  local end_mark = vim.fn.getpos("'>")
251
252  return start_mark[2] > 0 and end_mark[2] > 0 and opts.line1 == start_mark[2] and opts.line2 == end_mark[2]
253end
254
255local function close_prompt(state, restore_focus)
256  if state.closed then
257    return
258  end
259
260  state.closed = true
261
262  if active_prompt == state then
263    active_prompt = nil
264  end
265
266  if vim.api.nvim_get_current_win() == state.prompt_win then
267    pcall(function()
268      vim.cmd('stopinsert')
269    end)
270  end
271
272  if vim.api.nvim_win_is_valid(state.prompt_win) then
273    pcall(vim.api.nvim_win_close, state.prompt_win, true)
274  end
275
276  if vim.api.nvim_buf_is_valid(state.prompt_buf) then
277    pcall(vim.api.nvim_buf_delete, state.prompt_buf, { force = true })
278  end
279
280  if restore_focus and vim.api.nvim_win_is_valid(state.source_win) then
281    pcall(vim.api.nvim_set_current_win, state.source_win)
282  end
283end
284
285local function source_is_valid(state)
286  return vim.api.nvim_win_is_valid(state.source_win)
287    and vim.api.nvim_buf_is_valid(state.source_buf)
288    and vim.api.nvim_win_get_buf(state.source_win) == state.source_buf
289    and vim.api.nvim_buf_get_changedtick(state.source_buf) == state.changedtick
290    and has_visual_range(state.opts)
291end
292
293function M.prompt(opts)
294  if not has_visual_range(opts) then
295    notify_error('select text visually first')
296    return
297  end
298
299  if active_prompt then
300    close_prompt(active_prompt, false)
301  end
302
303  local source_win = vim.api.nvim_get_current_win()
304  local source_buf = vim.api.nvim_get_current_buf()
305  local selection_end = vim.fn.getpos("'>")
306  local source_width = vim.api.nvim_win_get_width(source_win)
307  local source_height = vim.api.nvim_win_get_height(source_win)
308  local available_width = math.max(1, source_width - 2)
309  local available_height = math.max(1, source_height - 2)
310  local prompt_width = math.min(80, math.max(20, math.floor(source_width * 0.7)), available_width)
311  local prompt_height = math.min(5, available_height)
312  local prompt_buf = vim.api.nvim_create_buf(false, true)
313
314  vim.bo[prompt_buf].bufhidden = 'wipe'
315  vim.bo[prompt_buf].filetype = 'ai-complete-prompt'
316
317  local prompt_win = vim.api.nvim_open_win(prompt_buf, true, {
318    relative = 'win',
319    win = source_win,
320    bufpos = { selection_end[2] - 1, math.max(0, selection_end[3] - 1) },
321    row = 1,
322    col = 0,
323    anchor = 'NW',
324    width = prompt_width,
325    height = prompt_height,
326    border = 'single',
327    style = 'minimal',
328  })
329
330  ---@type AiCompletePromptState
331  local state = {
332    changedtick = vim.api.nvim_buf_get_changedtick(source_buf),
333    closed = false,
334    opts = opts,
335    prompt_buf = prompt_buf,
336    prompt_win = prompt_win,
337    source_buf = source_buf,
338    source_win = source_win,
339  }
340
341  active_prompt = state
342
343  local function cancel(restore_focus)
344    close_prompt(state, restore_focus)
345  end
346
347  local function submit()
348    if state.closed then
349      return
350    end
351
352    local prompt = table.concat(vim.api.nvim_buf_get_lines(prompt_buf, 0, -1, false), '\n')
353    close_prompt(state, true)
354
355    -- Let the submit mapping finish so Neovim can leave Insert mode and redraw
356    -- before the blocking LLM command starts.
357    vim.schedule(function()
358      if not source_is_valid(state) then
359        notify_error('the selected text changed while entering the prompt')
360        return
361      end
362
363      M.complete(prompt, opts.range)
364    end)
365  end
366
367  vim.keymap.set({ 'i', 'n' }, '<S-CR>', submit, { buffer = prompt_buf, nowait = true })
368  vim.keymap.set({ 'i', 'n' }, '<Esc>', function()
369    cancel(true)
370  end, { buffer = prompt_buf, nowait = true })
371  vim.keymap.set({ 'i', 'n' }, '<C-c>', function()
372    cancel(true)
373  end, { buffer = prompt_buf, nowait = true })
374
375  vim.api.nvim_create_autocmd('WinLeave', {
376    buffer = prompt_buf,
377    once = true,
378    callback = function()
379      cancel(false)
380    end,
381  })
382
383  vim.cmd('startinsert')
384end
385
386function M.dispatch(opts)
387  if not has_visual_range(opts) then
388    notify_error('select text visually first')
389    return
390  end
391
392  if opts.args == '' then
393    M.prompt(opts)
394    return
395  end
396
397  M.complete(opts.args, opts.range)
398end
399
400-- Feature: complete at the cursor
401
402function M.complete_at_cursor()
403  local buf = vim.api.nvim_get_current_buf()
404  local cursor = vim.api.nvim_win_get_cursor(0)
405  local row, col = cursor[1] - 1, cursor[2]
406
407  local ok, err = pcall(function()
408    local prompt = table.concat({
409      file_context(),
410      COMPLETION_INSTRUCTION,
411      'Insertion is immediately before line ' .. cursor[1] .. ', byte column ' .. (col + 1) .. ' (1-based).',
412      'Current buffer (including unsaved changes):',
413      table.concat(vim.api.nvim_buf_get_lines(buf, 0, -1, false), '\n'),
414    }, '\n')
415    local output = generate(prompt)
416
417    -- Close the previous undo block so rejecting this completion preserves earlier edits.
418    vim.bo[buf].undolevels = vim.bo[buf].undolevels
419    vim.api.nvim_buf_set_text(buf, row, col, row, col, vim.split(output, '\n', { plain = true }))
420  end)
421
422  if not ok then
423    notify_error(tostring(err))
424    return
425  end
426
427  notify_done()
428end
429
430return M