David-Kunz / gen.nvim

Neovim plugin to generate text using LLMs with customizable prompts
The Unlicense
1.15k stars 92 forks source link

Add before & after cursor as context #120

Open felixkreuk opened 3 weeks ago

felixkreuk commented 3 weeks ago

First, thanks a lot for this nifty plugin! :)

The use case would be to generate a code snippet at a specific line. In this scenario, it may be redundant to give the whole file as context, but a few lines before and after the current cursor line might help.

Edit: other helpful contexts can be passing the current function/class/scope and cursor location, etc.

Apologies if this is already implemented and I missed it. Thanks again!

David-Kunz commented 3 days ago

Hi @felixkreuk ,

Thank you for this feature suggestion. This is already possible as of today, for example to insert the lines before and after the cursor, you can do the following:

require('gen').prompts['Code_Completion'] = { 
  prompt = function()
    local buf = vim.api.nvim_get_current_buf()
    local row, col = unpack(vim.api.nvim_win_get_cursor(0))

    local before = vim.api.nvim_buf_get_text(0, 0, 0, row-1, col+1, {})
    local after = vim.api.nvim_buf_get_text(0, row-1, col+1, -1, -1, {})
    local prompt = '<|fim_prefix|>' .. table.concat(before, "\n") .. '<|fim_suffix|>' .. table.concat(after, "\n") .. '<|fim_middle|>only output the middle part, not the prefix/suffix, nothing else, just the missing code including the $filetype code fence ```$filetype\n<resulting code>\n``` for example ```$filetype\nconsole.log("hello")\n```'
    return prompt
  end,
  model = "qwen2.5-coder:7b-instruct",
  extract = "```$filetype\n(.-)```"
}
vim.keymap.set('i', '<c-]>', '<esc>:Gen Code_Completion<CR>')

Would that work for you?

Thanks and best regards, David