@@ -144,6 +144,25 @@ local function run_llm_command(argv)
144144 return output
145145 end
146146
147+local function generate(prompt)
148+ local command, command_error = command_for_prompt(prompt)
149+
150+ if not command then
151+ error(command_error, 0)
152+ end
153+
154+ vim.notify('ai-complete: Generating...', vim.log.levels.INFO)
155+ vim.cmd('redraw')
156+
157+ local output, output_error = run_llm_command(command)
158+
159+ if output == nil then
160+ error(output_error, 0)
161+ end
162+
163+ return output
164+end
165+
147166 local function notify_error(message)
148167 vim.notify('ai-complete: ' .. message, vim.log.levels.ERROR)
149168 end
@@ -329,21 +348,7 @@ function M.complete(user_prompt, has_range)
329348 local selected_text = vim.fn.getreg('z')
330349 local selected_type = vim.fn.getregtype('z')
331350
332- local llm_prompt = prompt_for_llm(user_prompt, selected_text)
333- local command, command_error = command_for_prompt(llm_prompt)
334-
335- if not command then
336- error(command_error, 0)
337- end
338-
339- vim.notify('ai-complete: Generating...', vim.log.levels.INFO)
340- vim.cmd('redraw')
341-
342- local output, output_error = run_llm_command(command)
343-
344- if output == nil then
345- error(output_error, 0)
346- end
351+ local output = generate(prompt_for_llm(user_prompt, selected_text))
347352
348353 -- Preserve characterwise, linewise, or blockwise paste behavior.
349354 vim.fn.setreg('z', output, selected_type)
@@ -361,4 +366,34 @@ function M.complete(user_prompt, has_range)
361366 vim.cmd('redraw')
362367 end
363368
369+function M.complete_at_cursor()
370+ local buf = vim.api.nvim_get_current_buf()
371+ local cursor = vim.api.nvim_win_get_cursor(0)
372+ local row, col = cursor[1] - 1, cursor[2]
373+
374+ local ok, err = pcall(function()
375+ local prompt = table.concat({
376+ 'filename: ' .. vim.fn.expand('%:t'),
377+ 'path: ' .. vim.fn.expand('%:p'),
378+ '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.',
379+ 'Insertion is immediately before line ' .. cursor[1] .. ', byte column ' .. (col + 1) .. ' (1-based).',
380+ 'Current buffer (including unsaved changes):',
381+ table.concat(vim.api.nvim_buf_get_lines(buf, 0, -1, false), '\n'),
382+ }, '\n')
383+ local output = generate(prompt)
384+
385+ -- Close the previous undo block so rejecting this completion preserves earlier edits.
386+ vim.bo[buf].undolevels = vim.bo[buf].undolevels
387+ vim.api.nvim_buf_set_text(buf, row, col, row, col, vim.split(output, '\n', { plain = true }))
388+ end)
389+
390+ if not ok then
391+ notify_error(tostring(err))
392+ return
393+ end
394+
395+ vim.notify('ai-complete: done.', vim.log.levels.INFO)
396+ vim.cmd('redraw')
397+end
398+
364399 return M