-[](https://copilotc-nvim.github.io/CopilotChat.nvim/)
-[](https://results.pre-commit.ci/latest/github/CopilotC-Nvim/CopilotChat.nvim/main)
-[](https://discord.gg/vy6hJsTWaZ)
-[](https://dotfyle.com/plugins/CopilotC-Nvim/CopilotChat.nvim)
-[](#contributors)
+# Copilot Chat for Neovim
-> [!NOTE]
-> Plugin was rewritten to Lua from Python. Please check the [migration guide from version 1 to version 2](/MIGRATION.md) for more information.
+[](https://github.com/CopilotC-Nvim/CopilotChat.nvim/releases/latest)
+[](https://github.com/CopilotC-Nvim/CopilotChat.nvim/actions/workflows/ci.yml)
+[](#contributors)
+[](/doc/CopilotChat.txt)
+[](https://discord.gg/vy6hJsTWaZ)
+[](https://dotfyle.com/plugins/CopilotC-Nvim/CopilotChat.nvim)
-## Prerequisites
+
-Ensure you have the following installed:
+https://github.com/user-attachments/assets/8cad5643-63b2-4641-a5c4-68bc313f20e6
-- **Neovim stable (0.9.5) or nightly**.
+
-Optional:
+# Requirements
-- tiktoken_core: `sudo luarocks install --lua-version 5.1 tiktoken_core`. Alternatively, download a pre-built binary from [lua-tiktoken releases](https://github.com/gptlang/lua-tiktoken/releases)
-- You can check your Lua PATH in Neovim by doing `:lua print(package.cpath)`. Save the binary as `tiktoken_core.so` in any of the given paths.
+- [Neovim 0.9.5+](https://neovim.io/) - Older versions are not supported, and for best compatibility 0.10.0+ is preferred
+- [curl](https://curl.se/) - 8.0.0+ is recommended for best compatibility. Should be installed by default on most systems and also shipped with Neovim
+- [Copilot chat in the IDE](https://github.com/settings/copilot) setting enabled in GitHub settings
+- _(Optional)_ [tiktoken_core](https://github.com/gptlang/lua-tiktoken) - Used for more accurate token counting
+ - For Arch Linux users, you can install [`luajit-tiktoken-bin`](https://aur.archlinux.org/packages/luajit-tiktoken-bin) or [`lua51-tiktoken-bin`](https://aur.archlinux.org/packages/lua51-tiktoken-bin) from aur
+ - Alternatively, install via luarocks: `sudo luarocks install --lua-version 5.1 tiktoken_core`
+ - Alternatively, download a pre-built binary from [lua-tiktoken releases](https://github.com/gptlang/lua-tiktoken/releases). You can check your Lua PATH in Neovim by doing `:lua print(package.cpath)`. Save the binary as `tiktoken_core.so` in any of the given paths.
+- _(Optional)_ [git](https://git-scm.com/) - Used for fetching git diffs for `git` context
+ - For Arch Linux users, you can install [`git`](https://archlinux.org/packages/extra/x86_64/git) from the official repositories
+ - For other systems, use your package manager to install `git`. For windows use the installer provided from git site
+- _(Optional)_ [lynx](https://lynx.invisible-island.net/) - Used for improved fetching of URLs for `url` context
+ - For Arch Linux users, you can install [`lynx`](https://archlinux.org/packages/extra/x86_64/lynx) from the official repositories
+ - For other systems, use your package manager to install `lynx`. For windows use the installer provided from lynx site
-> For Arch Linux user, you can install [`luajit-tiktoken-bin`](https://aur.archlinux.org/packages/luajit-tiktoken-bin) or [`lua51-tiktoken-bin`](https://aur.archlinux.org/packages/lua51-tiktoken-bin) from aur!
+> [!WARNING]
+> If you are on neovim < 0.11.0, you also might want to add `noinsert` and `popup` to your `completeopt` to make the chat completion behave well.
-## Installation
+# Installation
-### Lazy.nvim
+### [Lazy.nvim](https://github.com/folke/lazy.nvim)
```lua
return {
{
"CopilotC-Nvim/CopilotChat.nvim",
- branch = "canary",
dependencies = {
- { "zbirenbaum/copilot.lua" }, -- or github/copilot.vim
+ { "github/copilot.vim" }, -- or zbirenbaum/copilot.lua
{ "nvim-lua/plenary.nvim" }, -- for curl, log wrapper
},
build = "make tiktoken", -- Only on MacOS or Linux
@@ -44,17 +55,17 @@ return {
}
```
-See @jellydn for [configuration](https://github.com/jellydn/lazy-nvim-ide/blob/main/lua/plugins/extras/copilot-chat-v2.lua)
+See [@jellydn](https://github.com/jellydn) for [configuration](https://github.com/jellydn/lazy-nvim-ide/blob/main/lua/plugins/extras/copilot-chat-v2.lua)
-### Vim-Plug
+### [Vim-Plug](https://github.com/junegunn/vim-plug)
Similar to the lazy setup, you can use the following configuration:
```vim
call plug#begin()
-Plug 'zbirenbaum/copilot.lua'
+Plug 'github/copilot.vim'
Plug 'nvim-lua/plenary.nvim'
-Plug 'CopilotC-Nvim/CopilotChat.nvim', { 'branch': 'canary' }
+Plug 'CopilotC-Nvim/CopilotChat.nvim', { 'branch': 'main' }
call plug#end()
lua << EOF
@@ -72,10 +83,10 @@ EOF
mkdir -p ~/.config/nvim/pack/copilotchat/start
cd ~/.config/nvim/pack/copilotchat/start
-git clone https://github.com/zbirenbaum/copilot.lua
+git clone https://github.com/github/copilot.vim
git clone https://github.com/nvim-lua/plenary.nvim
-git clone -b canary https://github.com/CopilotC-Nvim/CopilotChat.nvim
+git clone -b main https://github.com/CopilotC-Nvim/CopilotChat.nvim
```
2. Add to your configuration (e.g. `~/.config/nvim/init.lua`)
@@ -86,15 +97,11 @@ require("CopilotChat").setup {
}
```
-See @deathbeam for [configuration](https://github.com/deathbeam/dotfiles/blob/master/nvim/.config/nvim/lua/config/copilot.lua#L14)
-
-### Post-Installation
+See [@deathbeam](https://github.com/deathbeam) for [configuration](https://github.com/deathbeam/dotfiles/blob/master/nvim/.config/nvim/lua/config/copilot.lua)
-Verify "[Copilot chat in the IDE](https://github.com/settings/copilot)" is enabled.
+# Usage
-## Usage
-
-### Commands
+## Commands
- `:CopilotChat ?` - Open chat window with optional input
- `:CopilotChatOpen` - Open chat window
@@ -107,13 +114,49 @@ Verify "[Copilot chat in the IDE](https://github.com/settings/copilot)" is enabl
- `:CopilotChatDebugInfo` - Show debug information
- `:CopilotChatModels` - View and select available models. This is reset when a new instance is made. Please set your model in `init.lua` for persistence.
- `:CopilotChatAgents` - View and select available agents. This is reset when a new instance is made. Please set your agent in `init.lua` for persistence.
+- `:CopilotChat` - Ask a question with a specific prompt. For example, `:CopilotChatExplain` will ask a question with the `Explain` prompt. See [Prompts](#prompts) for more information.
+
+## Chat Mappings
+
+- `` - Trigger completion menu for special tokens or accept current completion (see help)
+- `q`/`` - Close the chat window
+- `` - Reset and clear the chat window
+- ``/`` - Submit the current prompt
+- `gr` - Toggle sticky prompt for the line under cursor
+- `` - Accept nearest diff (works best with `COPILOT_GENERATE` prompt)
+- `gj` - Jump to section of nearest diff. If in different buffer, jumps there; creates buffer if needed (works best with `COPILOT_GENERATE` prompt)
+- `gq` - Add all diffs from chat to quickfix list
+- `gy` - Yank nearest diff to register (defaults to `"`)
+- `gd` - Show diff between source and nearest diff
+- `gi` - Show info about current chat (model, agent, system prompt)
+- `gc` - Show current chat context
+- `gh` - Show help message
+
+The mappings can be customized by setting the `mappings` table in your configuration. Each mapping can have:
+
+- `normal`: Key for normal mode
+- `insert`: Key for insert mode
+- `detail`: Description of what the mapping does
+
+For example, to change the submit prompt mapping:
+
+```lua
+{
+ mappings = {
+ submit_prompt = {
+ normal = 's',
+ insert = ''
+ }
+ }
+}
+```
-### Prompts
+## Prompts
You can ask Copilot to do various tasks with prompts. You can reference prompts with `/PromptName` in chat or call with command `:CopilotChat`.
Default prompts are:
-- `Explain` - Write an explanation for the selected code and diagnostics as paragraphs of text
+- `Explain` - Write an explanation for the selected code as paragraphs of text
- `Review` - Review the selected code
- `Fix` - There is a problem in this code. Rewrite the code to show it with the bug fixed
- `Optimize` - Optimize the selected code to improve performance and readability
@@ -121,7 +164,22 @@ Default prompts are:
- `Tests` - Please generate tests for my code
- `Commit` - Write commit message for the change with commitizen convention
-### System Prompts
+You can define custom prompts like this (only `prompt` is required):
+
+```lua
+{
+ prompts = {
+ MyCustomPrompt = {
+ prompt = 'Explain how it works.',
+ system_prompt = 'You are very good at explaining stuff',
+ mapping = 'ccmc',
+ description = 'My custom prompt description',
+ }
+ }
+}
+```
+
+## System Prompts
System prompts specify the behavior of the AI model. You can reference system prompts with `/PROMPT_NAME` in chat.
Default system prompts are:
@@ -131,7 +189,19 @@ Default system prompts are:
- `COPILOT_REVIEW` - On top of the base instructions adds code review behavior with instructions on how to generate diagnostics
- `COPILOT_GENERATE` - On top of the base instructions adds code generation behavior, with predefined formatting and generation rules
-### Sticky Prompts
+You can define custom system prompts like this (works same as `prompts` so you can combine prompt and system prompt definitions):
+
+```lua
+{
+ prompts = {
+ Yarrr = {
+ system_prompt = 'You are fascinated by pirates, so please respond in pirate speak.',
+ }
+ }
+}
+```
+
+## Sticky Prompts
You can set sticky prompt in chat by prefixing the text with `> ` using markdown blockquote syntax.
The sticky prompt will be copied at start of every new prompt in chat window. You can freely edit the sticky prompt, only rule is `> ` prefix at beginning of line.
@@ -150,10 +220,10 @@ List all files in the workspace
What is 1 + 11
```
-### Models
+## Models
You can list available models with `:CopilotChatModels` command. Model determines the AI model used for the chat.
-You can set the model in the prompt by using `$` followed by the model name.
+You can set the model in the prompt by using `$` followed by the model name or default model via config using `model` key.
Default models are:
- `gpt-4o` - This is the default Copilot Chat model. It is a versatile, multimodal model that excels in both text and image processing and is designed to provide fast, reliable responses. It also has superior performance in non-English languages. Gpt-4o is hosted on Azure.
@@ -164,29 +234,98 @@ Default models are:
For more information about models, see [here](https://docs.github.com/en/copilot/using-github-copilot/asking-github-copilot-questions-in-your-ide#ai-models-for-copilot-chat)
You can use more models from [here](https://github.com/marketplace/models) by using `@models` agent from [here](https://github.com/marketplace/models-github) (example: `@models Using Mistral-small, what is 1 + 11`)
-### Agents
+## Agents
Agents are used to determine the AI agent used for the chat. You can list available agents with `:CopilotChatAgents` command.
-You can set the agent in the prompt by using `@` followed by the agent name.
+You can set the agent in the prompt by using `@` followed by the agent name or default agent via config using `agent` key.
Default "noop" agent is `copilot`.
For more information about extension agents, see [here](https://docs.github.com/en/copilot/using-github-copilot/using-extensions-to-integrate-external-tools-with-copilot-chat)
You can install more agents from [here](https://github.com/marketplace?type=apps&copilot_app=true)
-### Contexts
+## Contexts
Contexts are used to determine the context of the chat.
-You can set the context in the prompt by using `#` followed by the context name.
+You can add context to the prompt by using `#` followed by the context name or default context via config using `context` (can be single or array) key.
+Any amount of context can be added to the prompt.
If context supports input, you can set the input in the prompt by using `:` followed by the input (or pressing `complete` key after `:`).
Default contexts are:
-- `buffer` - Includes specified buffer in chat context (default current). Supports input.
-- `buffers` - Includes all buffers in chat context (default listed). Supports input.
+- `buffer` - Includes specified buffer in chat context. Supports input (default current).
+- `buffers` - Includes all buffers in chat context. Supports input (default listed).
- `file` - Includes content of provided file in chat context. Supports input.
-- `files` - Includes all non-hidden filenames in the current workspace in chat context. Supports input.
-- `git` - Includes current git diff in chat context (default unstaged). Supports input.
+- `files` - Includes all non-hidden files in the current workspace in chat context. Supports input (default list).
+ - `files:list` - Only lists file names.
+ - `files:full` - Includes file content for each file found. Can be slow on large workspaces, use with care.
+- `git` - Requires `git`. Includes current git diff in chat context. Supports input (default unstaged).
+ - `git:unstaged` - Includes unstaged changes in chat context.
+ - `git:staged` - Includes staged changes in chat context.
+- `url` - Includes content of provided URL in chat context. Supports input.
+- `register` - Includes contents of register in chat context. Supports input (default +, e.g clipboard).
-### API
+You can define custom contexts like this:
+
+```lua
+{
+ contexts = {
+ birthday = {
+ input = function(callback)
+ vim.ui.select({ 'user', 'napoleon' }, {
+ prompt = 'Select birthday> ',
+ }, callback)
+ end,
+ resolve = function(input)
+ input = input or 'user'
+ local birthday = input
+ if input == 'user' then
+ birthday = birthday .. ' birthday is April 1, 1990'
+ elseif input == 'napoleon' then
+ birthday = birthday .. ' birthday is August 15, 1769'
+ end
+
+ return {
+ {
+ content = birthday,
+ filename = input .. '_birthday',
+ filetype = 'text',
+ }
+ }
+ end
+ }
+ }
+}
+```
+
+```markdown
+> #birthday:user
+
+What is my birthday
+```
+
+## Selections
+
+Selections are used to determine the source of the chat (so basically what to chat about).
+Selections are configurable either by default or by prompt.
+Default selection is `visual` or `buffer` (if no visual selection).
+Selection includes content, start and end position, buffer info and diagnostic info (if available).
+Supported selections that live in `local select = require("CopilotChat.select")` are:
+
+- `select.visual` - Current visual selection.
+- `select.buffer` - Current buffer content.
+- `select.line` - Current line content.
+- `select.unnamed` - Unnamed register content. This register contains last deleted, changed or yanked content.
+
+You can chain multiple selections like this:
+
+```lua
+{
+ selection = function(source)
+ return select.visual(source) or select.buffer(source)
+ end
+}
+```
+
+## API
```lua
local chat = require("CopilotChat")
@@ -227,6 +366,11 @@ chat.ask("Explain how it works.", {
selection = require("CopilotChat.select").buffer,
})
+-- Ask a question and provide custom contexts
+chat.ask("Explain how it works.", {
+ context = { 'buffers', 'files', 'register:+' },
+})
+
-- Ask a question and do something with the response
chat.ask("Show me something interesting", {
callback = function(response)
@@ -240,6 +384,10 @@ local prompts = chat.prompts()
-- Get last copilot response (also can be used for integrations and custom keymaps)
local response = chat.response()
+-- Retrieve current chat config
+local config = chat.config
+print(config.model)
+
-- Pick a prompt using vim.ui.select
local actions = require("CopilotChat.actions")
@@ -252,47 +400,69 @@ actions.pick(actions.prompt_actions({
chat.log_level("debug")
```
-## Configuration
+# Configuration
-### Default configuration
+## Default configuration
Also see [here](/lua/CopilotChat/config.lua):
```lua
{
- debug = false, -- Enable debug logging (same as 'log_level = 'debug')
- log_level = 'info', -- Log level to use, 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
- proxy = nil, -- [protocol://]host[:port] Use this proxy
- allow_insecure = false, -- Allow insecure server connections
+
+ -- Shared config starts here (can be passed to functions at runtime and configured via setup function)
system_prompt = prompts.COPILOT_INSTRUCTIONS, -- System prompt to use (can be specified manually in prompt via /).
model = 'gpt-4o', -- Default model to use, see ':CopilotChatModels' for available models (can be specified manually in prompt via $).
agent = 'copilot', -- Default agent to use, see ':CopilotChatAgents' for available agents (can be specified manually in prompt via @).
- context = nil, -- Default context to use (can be specified manually in prompt via #).
+ context = nil, -- Default context or array of contexts to use (can be specified manually in prompt via #).
temperature = 0.1, -- GPT result temperature
- question_header = '## User ', -- Header to use for user questions
- answer_header = '## Copilot ', -- Header to use for AI answers
- error_header = '## Error ', -- Header to use for errors
- separator = '───', -- Separator to use in chat
+ headless = false, -- Do not write to chat buffer and use history(useful for using callback for custom processing)
+ callback = nil, -- Callback to use when ask response is received
+
+ -- default selection
+ selection = function(source)
+ return select.visual(source) or select.buffer(source)
+ end,
+
+ -- default window options
+ window = {
+ layout = 'vertical', -- 'vertical', 'horizontal', 'float', 'replace'
+ width = 0.5, -- fractional width of parent, or absolute width in columns when > 1
+ height = 0.5, -- fractional height of parent, or absolute height in rows when > 1
+ -- Options below only apply to floating windows
+ relative = 'editor', -- 'editor', 'win', 'cursor', 'mouse'
+ border = 'single', -- 'none', single', 'double', 'rounded', 'solid', 'shadow'
+ row = nil, -- row position of the window, default is centered
+ col = nil, -- column position of the window, default is centered
+ title = 'Copilot Chat', -- title of chat window
+ footer = nil, -- footer of chat window
+ zindex = 1, -- determines if window is on top or below other floating windows
+ },
- chat_autocomplete = true, -- Enable chat autocompletion (when disabled, requires manual `mappings.complete` trigger)
- show_folds = true, -- Shows folds for sections in chat
show_help = true, -- Shows help message as virtual lines when waiting for user input
+ show_folds = true, -- Shows folds for sections in chat
+ highlight_selection = true, -- Highlight selection
+ highlight_headers = true, -- Highlight headers in chat, disable if using markdown renderers (like render-markdown.nvim)
auto_follow_cursor = true, -- Auto-follow cursor in chat
auto_insert_mode = false, -- Automatically enter insert mode when opening window and on new prompt
insert_at_end = false, -- Move cursor to end of buffer when inserting text
clear_chat_on_new_prompt = false, -- Clears chat on every new prompt
- highlight_selection = true, -- Highlight selection in the source buffer when in the chat window
- highlight_headers = true, -- Highlight headers in chat, disable if using markdown renderers (like render-markdown.nvim)
+ -- Static config starts here (can be configured only via setup function)
+
+ debug = false, -- Enable debug logging (same as 'log_level = 'debug')
+ log_level = 'info', -- Log level to use, 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
+ proxy = nil, -- [protocol://]host[:port] Use this proxy
+ allow_insecure = false, -- Allow insecure server connections
+
+ chat_autocomplete = true, -- Enable chat autocompletion (when disabled, requires manual `mappings.complete` trigger)
history_path = vim.fn.stdpath('data') .. '/copilotchat_history', -- Default path to stored history
- callback = nil, -- Callback to use when ask response is received
- -- default selection
- selection = function(source)
- return select.visual(source) or select.buffer(source)
- end,
+ question_header = '# User ', -- Header to use for user questions
+ answer_header = '# Copilot ', -- Header to use for AI answers
+ error_header = '# Error ', -- Header to use for errors
+ separator = '───', -- Separator to use in chat
-- default contexts
contexts = {
@@ -311,12 +481,18 @@ Also see [here](/lua/CopilotChat/config.lua):
git = {
-- see config.lua for implementation
},
+ url = {
+ -- see config.lua for implementation
+ },
+ register = {
+ -- see config.lua for implementation
+ },
},
-- default prompts
prompts = {
Explain = {
- prompt = '> /COPILOT_EXPLAIN\n\nWrite an explanation for the selected code and diagnostics as paragraphs of text.',
+ prompt = '> /COPILOT_EXPLAIN\n\nWrite an explanation for the selected code as paragraphs of text.',
},
Review = {
prompt = '> /COPILOT_REVIEW\n\nReview the selected code.',
@@ -339,37 +515,22 @@ Also see [here](/lua/CopilotChat/config.lua):
},
},
- -- default window options
- window = {
- layout = 'vertical', -- 'vertical', 'horizontal', 'float', 'replace'
- width = 0.5, -- fractional width of parent, or absolute width in columns when > 1
- height = 0.5, -- fractional height of parent, or absolute height in rows when > 1
- -- Options below only apply to floating windows
- relative = 'editor', -- 'editor', 'win', 'cursor', 'mouse'
- border = 'single', -- 'none', single', 'double', 'rounded', 'solid', 'shadow'
- row = nil, -- row position of the window, default is centered
- col = nil, -- column position of the window, default is centered
- title = 'Copilot Chat', -- title of chat window
- footer = nil, -- footer of chat window
- zindex = 1, -- determines if window is on top or below other floating windows
- },
-
-- default mappings
mappings = {
complete = {
- insert ='',
+ insert = '',
},
close = {
normal = 'q',
- insert = ''
+ insert = '',
},
reset = {
- normal ='',
- insert = ''
+ normal = '',
+ insert = '',
},
submit_prompt = {
normal = '',
- insert = ''
+ insert = '',
},
toggle_sticky = {
detail = 'Makes line under cursor sticky or deletes sticky line.',
@@ -377,86 +538,35 @@ Also see [here](/lua/CopilotChat/config.lua):
},
accept_diff = {
normal = '',
- insert = ''
+ insert = '',
+ },
+ jump_to_diff = {
+ normal = 'gj',
+ },
+ quickfix_diffs = {
+ normal = 'gq',
},
yank_diff = {
normal = 'gy',
register = '"',
},
show_diff = {
- normal = 'gd'
+ normal = 'gd',
},
- show_system_prompt = {
- normal = 'gp'
+ show_info = {
+ normal = 'gi',
},
- show_user_selection = {
- normal = 'gs'
+ show_context = {
+ normal = 'gc',
},
- },
-}
-```
-
-For further reference, you can view @jellydn's [configuration](https://github.com/jellydn/lazy-nvim-ide/blob/main/lua/plugins/extras/copilot-chat-v2.lua).
-
-### Defining a prompt with command and keymap
-
-This will define prompt that you can reference with `/MyCustomPrompt` in chat, call with `:CopilotChatMyCustomPrompt` or use the keymap `ccmc`.
-It will use visual selection as default selection. If you are using `lazy.nvim` and are already lazy loading based on `Commands` make sure to include the prompt
-commands and keymaps in `cmd` and `keys` respectively.
-
-```lua
-{
- prompts = {
- MyCustomPrompt = {
- prompt = 'Explain how it works.',
- mapping = 'ccmc',
- description = 'My custom prompt description',
- selection = require('CopilotChat.select').visual,
+ show_help = {
+ normal = 'gh',
},
},
}
```
-### Referencing system or user prompts
-
-You can reference system or user prompts in your configuration or in chat with `/PROMPT_NAME` slash notation.
-For collection of default `COPILOT_` (system) and `USER_` (user) prompts, see [here](/lua/CopilotChat/prompts.lua).
-
-```lua
-{
- prompts = {
- MyCustomPrompt = {
- prompt = '/COPILOT_EXPLAIN Explain how it works.',
- },
- MyCustomPrompt2 = {
- prompt = '/MyCustomPrompt Include some additional context.',
- },
- },
-}
-```
-
-### Custom system prompts
-
-You can define custom system prompts by using `system_prompt` property when passing config around.
-
-```lua
-{
- system_prompt = 'Your name is Github Copilot and you are a AI assistant for developers.',
- prompts = {
- Johnny = {
- system_prompt = 'Your name is Johny Microsoft and you are not an AI assistant for developers.',
- prompt = 'Explain how it works.',
- },
- Yarrr = {
- system_prompt = 'You are fascinated by pirates, so please respond in pirate speak.'
- },
- },
-}
-```
-
-To use any of your custom prompts, simply do `:CopilotChat`. E.g. `:CopilotChatJohnny` or `:CopilotChatYarrr What is a sorting algo?`. Tab autocomplete will help you out.
-
-### Customizing buffers
+## Customizing buffers
You can set local options for the buffers that are created by this plugin: `copilot-diff`, `copilot-system-prompt`, `copilot-user-selection`, `copilot-chat`.
@@ -474,7 +584,7 @@ vim.api.nvim_create_autocmd('BufEnter', {
})
```
-## Tips
+# Tips
Quick chat with your buffer
@@ -497,7 +607,7 @@ To chat with Copilot using the entire content of the buffer, you can add the fol
}
```
-[](https://gyazo.com/9b8cbf1d78a19f326282a6520bc9aab0)
+[](https://gyazo.com/9b8cbf1d78a19f326282a6520bc9aab0)
@@ -544,7 +654,7 @@ Requires [telescope.nvim](https://github.com/nvim-telescope/telescope.nvim) plug
},
```
-
+
@@ -567,7 +677,7 @@ Requires [fzf-lua](https://github.com/ibhagwan/fzf-lua) plugin to be installed.
},
```
-
+
@@ -582,23 +692,25 @@ require('render-markdown').setup({
file_types = { 'markdown', 'copilot-chat' },
})
--- You might also want to disable default header highlighting for copilot chat when doing this
+-- You might also want to disable default header highlighting for copilot chat when doing this and set error header style and separator
require('CopilotChat').setup({
highlight_headers = false,
+ separator = '---',
+ error_header = '> [!ERROR] Error',
-- rest of your config
})
```
-
+
-## Roadmap (Wishlist)
+# Roadmap
-- Use indexed vector database with current workspace for better context selection
+- Improved caching for context (persistence through restarts/smarter caching)
- General QOL improvements
-## Development
+# Development
### Installing Pre-commit Tool
@@ -610,7 +722,7 @@ make install-pre-commit
This will install the pre-commit tool and the pre-commit hooks.
-## Contributors ✨
+# Contributors
If you want to contribute to this project, please read the [CONTRIBUTING.md](/CONTRIBUTING.md) file.
@@ -672,6 +784,7 @@ Thanks goes to these wonderful people ([emoji key](https://allcontributors.org/d
diff --git a/doc/CopilotChat.txt b/doc/CopilotChat.txt
index e8529db7..be4de4f7 100644
--- a/doc/CopilotChat.txt
+++ b/doc/CopilotChat.txt
@@ -1,49 +1,54 @@
-*CopilotChat.txt* For NVIM v0.8.0 Last change: 2024 November 18
+*CopilotChat.txt* For NVIM v0.8.0 Last change: 2024 December 02
==============================================================================
Table of Contents *CopilotChat-table-of-contents*
-1. Copilot Chat for Neovim |CopilotChat-copilot-chat-for-neovim|
- - Prerequisites |CopilotChat-prerequisites|
- - Installation |CopilotChat-installation|
- - Usage |CopilotChat-usage|
- - Configuration |CopilotChat-configuration|
- - Tips |CopilotChat-tips|
- - Roadmap (Wishlist) |CopilotChat-roadmap-(wishlist)|
- - Development |CopilotChat-development|
- - Contributors ✨ |CopilotChat-contributors-✨|
-2. Links |CopilotChat-links|
+1. Requirements |CopilotChat-requirements|
+2. Installation |CopilotChat-installation|
+3. Usage |CopilotChat-usage|
+ - Commands |CopilotChat-commands|
+ - Chat Mappings |CopilotChat-chat-mappings|
+ - Prompts |CopilotChat-prompts|
+ - System Prompts |CopilotChat-system-prompts|
+ - Sticky Prompts |CopilotChat-sticky-prompts|
+ - Models |CopilotChat-models|
+ - Agents |CopilotChat-agents|
+ - Contexts |CopilotChat-contexts|
+ - Selections |CopilotChat-selections|
+ - API |CopilotChat-api|
+4. Configuration |CopilotChat-configuration|
+ - Default configuration |CopilotChat-default-configuration|
+ - Customizing buffers |CopilotChat-customizing-buffers|
+5. Tips |CopilotChat-tips|
+6. Roadmap |CopilotChat-roadmap|
+7. Development |CopilotChat-development|
+8. Contributors |CopilotChat-contributors|
+9. Links |CopilotChat-links|
-==============================================================================
-1. Copilot Chat for Neovim *CopilotChat-copilot-chat-for-neovim*
-
-
-
-
- |CopilotChat-|
-
-
- [!NOTE] Plugin was rewritten to Lua from Python. Please check the migration
- guide from version 1 to version 2 for more information.
-
-PREREQUISITES *CopilotChat-prerequisites*
-
-Ensure you have the following installed:
-
-- **Neovim stable (0.9.5) or nightly**.
-Optional:
-
-- tiktoken_core: `sudo luarocks install --lua-version 5.1 tiktoken_core`. Alternatively, download a pre-built binary from lua-tiktoken releases
-- You can check your Lua PATH in Neovim by doing `:lua print(package.cpath)`. Save the binary as `tiktoken_core.so` in any of the given paths.
-
-
- For Arch Linux user, you can install `luajit-tiktoken-bin`
- or
- `lua51-tiktoken-bin`
- from aur!
+==============================================================================
+1. Requirements *CopilotChat-requirements*
+
+- Neovim 0.9.5+ - Older versions are not supported, and for best compatibility 0.10.0+ is preferred
+- curl - 8.0.0+ is recommended for best compatibility. Should be installed by default on most systems and also shipped with Neovim
+- Copilot chat in the IDE setting enabled in GitHub settings
+- _(Optional)_ tiktoken_core - Used for more accurate token counting
+ - For Arch Linux users, you can install `luajit-tiktoken-bin` or `lua51-tiktoken-bin` from aur
+ - Alternatively, install via luarocks: `sudo luarocks install --lua-version 5.1 tiktoken_core`
+ - Alternatively, download a pre-built binary from lua-tiktoken releases . You can check your Lua PATH in Neovim by doing `:lua print(package.cpath)`. Save the binary as `tiktoken_core.so` in any of the given paths.
+- _(Optional)_ git - Used for fetching git diffs for `git` context
+ - For Arch Linux users, you can install `git` from the official repositories
+ - For other systems, use your package manager to install `git`. For windows use the installer provided from git site
+- _(Optional)_ lynx - Used for improved fetching of URLs for `url` context
+ - For Arch Linux users, you can install `lynx` from the official repositories
+ - For other systems, use your package manager to install `lynx`. For windows use the installer provided from lynx site
+
+
+ [!WARNING] If you are on neovim < 0.11.0, you also might want to add `noinsert`
+ and `popup` to your `completeopt` to make the chat completion behave well.
-INSTALLATION *CopilotChat-installation*
+==============================================================================
+2. Installation *CopilotChat-installation*
LAZY.NVIM ~
@@ -52,9 +57,8 @@ LAZY.NVIM ~
return {
{
"CopilotC-Nvim/CopilotChat.nvim",
- branch = "canary",
dependencies = {
- { "zbirenbaum/copilot.lua" }, -- or github/copilot.vim
+ { "github/copilot.vim" }, -- or zbirenbaum/copilot.lua
{ "nvim-lua/plenary.nvim" }, -- for curl, log wrapper
},
build = "make tiktoken", -- Only on MacOS or Linux
@@ -66,7 +70,7 @@ LAZY.NVIM ~
}
<
-See @jellydn for configuration
+See @jellydn for configuration
@@ -76,9 +80,9 @@ Similar to the lazy setup, you can use the following configuration:
>vim
call plug#begin()
- Plug 'zbirenbaum/copilot.lua'
+ Plug 'github/copilot.vim'
Plug 'nvim-lua/plenary.nvim'
- Plug 'CopilotC-Nvim/CopilotChat.nvim', { 'branch': 'canary' }
+ Plug 'CopilotC-Nvim/CopilotChat.nvim', { 'branch': 'main' }
call plug#end()
lua << EOF
@@ -97,10 +101,10 @@ MANUAL ~
mkdir -p ~/.config/nvim/pack/copilotchat/start
cd ~/.config/nvim/pack/copilotchat/start
- git clone https://github.com/zbirenbaum/copilot.lua
+ git clone https://github.com/github/copilot.vim
git clone https://github.com/nvim-lua/plenary.nvim
- git clone -b canary https://github.com/CopilotC-Nvim/CopilotChat.nvim
+ git clone -b main https://github.com/CopilotC-Nvim/CopilotChat.nvim
<
1. Add to your configuration (e.g. `~/.config/nvim/init.lua`)
@@ -111,20 +115,15 @@ MANUAL ~
}
<
-See @deathbeam for configuration
-
-
+See @deathbeam for configuration
+
-POST-INSTALLATION ~
-Verify "Copilot chat in the IDE " is
-enabled.
-
-
-USAGE *CopilotChat-usage*
+==============================================================================
+3. Usage *CopilotChat-usage*
-COMMANDS ~
+COMMANDS *CopilotChat-commands*
- `:CopilotChat ?` - Open chat window with optional input
- `:CopilotChatOpen` - Open chat window
@@ -137,15 +136,53 @@ COMMANDS ~
- `:CopilotChatDebugInfo` - Show debug information
- `:CopilotChatModels` - View and select available models. This is reset when a new instance is made. Please set your model in `init.lua` for persistence.
- `:CopilotChatAgents` - View and select available agents. This is reset when a new instance is made. Please set your agent in `init.lua` for persistence.
+- `:CopilotChat` - Ask a question with a specific prompt. For example, `:CopilotChatExplain` will ask a question with the `Explain` prompt. See |CopilotChat-prompts| for more information.
+
+
+CHAT MAPPINGS *CopilotChat-chat-mappings*
+
+- `` - Trigger completion menu for special tokens or accept current completion (see help)
+- `q`/`` - Close the chat window
+- `` - Reset and clear the chat window
+- ``/`` - Submit the current prompt
+- `gr` - Toggle sticky prompt for the line under cursor
+- `` - Accept nearest diff (works best with `COPILOT_GENERATE` prompt)
+- `gj` - Jump to section of nearest diff. If in different buffer, jumps there; creates buffer if needed (works best with `COPILOT_GENERATE` prompt)
+- `gq` - Add all diffs from chat to quickfix list
+- `gy` - Yank nearest diff to register (defaults to `"`)
+- `gd` - Show diff between source and nearest diff
+- `gi` - Show info about current chat (model, agent, system prompt)
+- `gc` - Show current chat context
+- `gh` - Show help message
+The mappings can be customized by setting the `mappings` table in your
+configuration. Each mapping can have:
-PROMPTS ~
+- `normal`: Key for normal mode
+- `insert`: Key for insert mode
+- `detail`: Description of what the mapping does
+
+For example, to change the submit prompt mapping:
+
+>lua
+ {
+ mappings = {
+ submit_prompt = {
+ normal = 's',
+ insert = ''
+ }
+ }
+ }
+<
+
+
+PROMPTS *CopilotChat-prompts*
You can ask Copilot to do various tasks with prompts. You can reference prompts
with `/PromptName` in chat or call with command `:CopilotChat`.
Default prompts are:
-- `Explain` - Write an explanation for the selected code and diagnostics as paragraphs of text
+- `Explain` - Write an explanation for the selected code as paragraphs of text
- `Review` - Review the selected code
- `Fix` - There is a problem in this code. Rewrite the code to show it with the bug fixed
- `Optimize` - Optimize the selected code to improve performance and readability
@@ -153,8 +190,23 @@ Default prompts are:
- `Tests` - Please generate tests for my code
- `Commit` - Write commit message for the change with commitizen convention
+You can define custom prompts like this (only `prompt` is required):
+
+>lua
+ {
+ prompts = {
+ MyCustomPrompt = {
+ prompt = 'Explain how it works.',
+ system_prompt = 'You are very good at explaining stuff',
+ mapping = 'ccmc',
+ description = 'My custom prompt description',
+ }
+ }
+ }
+<
+
-SYSTEM PROMPTS ~
+SYSTEM PROMPTS *CopilotChat-system-prompts*
System prompts specify the behavior of the AI model. You can reference system
prompts with `/PROMPT_NAME` in chat. Default system prompts are:
@@ -164,8 +216,21 @@ prompts with `/PROMPT_NAME` in chat. Default system prompts are:
- `COPILOT_REVIEW` - On top of the base instructions adds code review behavior with instructions on how to generate diagnostics
- `COPILOT_GENERATE` - On top of the base instructions adds code generation behavior, with predefined formatting and generation rules
+You can define custom system prompts like this (works same as `prompts` so you
+can combine prompt and system prompt definitions):
+
+>lua
+ {
+ prompts = {
+ Yarrr = {
+ system_prompt = 'You are fascinated by pirates, so please respond in pirate speak.',
+ }
+ }
+ }
+<
+
-STICKY PROMPTS ~
+STICKY PROMPTS *CopilotChat-sticky-prompts*
You can set sticky prompt in chat by prefixing the text with `>` using markdown
blockquote syntax. The sticky prompt will be copied at start of every new
@@ -186,11 +251,12 @@ and agent selection (see below). Example usage:
<
-MODELS ~
+MODELS *CopilotChat-models*
You can list available models with `:CopilotChatModels` command. Model
determines the AI model used for the chat. You can set the model in the prompt
-by using `$` followed by the model name. Default models are:
+by using `$` followed by the model name or default model via config using
+`model` key. Default models are:
- `gpt-4o` - This is the default Copilot Chat model. It is a versatile, multimodal model that excels in both text and image processing and is designed to provide fast, reliable responses. It also has superior performance in non-English languages. Gpt-4o is hosted on Azure.
- `claude-3.5-sonnet` - This model excels at coding tasks across the entire software development lifecycle, from initial design to bug fixes, maintenance to optimizations. GitHub Copilot uses Claude 3.5 Sonnet hosted on Amazon Web Services.
@@ -204,12 +270,12 @@ using `@models` agent from here
(example: `@models Using Mistral-small, what is 1 + 11`)
-AGENTS ~
+AGENTS *CopilotChat-agents*
Agents are used to determine the AI agent used for the chat. You can list
available agents with `:CopilotChatAgents` command. You can set the agent in
-the prompt by using `@` followed by the agent name. Default "noop" agent is
-`copilot`.
+the prompt by using `@` followed by the agent name or default agent via config
+using `agent` key. Default "noop" agent is `copilot`.
For more information about extension agents, see here
@@ -217,21 +283,93 @@ You can install more agents from here
-CONTEXTS ~
+CONTEXTS *CopilotChat-contexts*
-Contexts are used to determine the context of the chat. You can set the context
-in the prompt by using `#` followed by the context name. If context supports
-input, you can set the input in the prompt by using `:` followed by the input
-(or pressing `complete` key after `:`). Default contexts are:
+Contexts are used to determine the context of the chat. You can add context to
+the prompt by using `#` followed by the context name or default context via
+config using `context` (can be single or array) key. Any amount of context can
+be added to the prompt. If context supports input, you can set the input in the
+prompt by using `:` followed by the input (or pressing `complete` key after
+`:`). Default contexts are:
-- `buffer` - Includes specified buffer in chat context (default current). Supports input.
-- `buffers` - Includes all buffers in chat context (default listed). Supports input.
+- `buffer` - Includes specified buffer in chat context. Supports input (default current).
+- `buffers` - Includes all buffers in chat context. Supports input (default listed).
- `file` - Includes content of provided file in chat context. Supports input.
-- `files` - Includes all non-hidden filenames in the current workspace in chat context. Supports input.
-- `git` - Includes current git diff in chat context (default unstaged). Supports input.
+- `files` - Includes all non-hidden files in the current workspace in chat context. Supports input (default list).
+ - `files:list` - Only lists file names.
+ - `files:full` - Includes file content for each file found. Can be slow on large workspaces, use with care.
+- `git` - Requires `git`. Includes current git diff in chat context. Supports input (default unstaged).
+ - `git:unstaged` - Includes unstaged changes in chat context.
+ - `git:staged` - Includes staged changes in chat context.
+- `url` - Includes content of provided URL in chat context. Supports input.
+- `register` - Includes contents of register in chat context. Supports input (default +, e.g clipboard).
+You can define custom contexts like this:
-API ~
+>lua
+ {
+ contexts = {
+ birthday = {
+ input = function(callback)
+ vim.ui.select({ 'user', 'napoleon' }, {
+ prompt = 'Select birthday> ',
+ }, callback)
+ end,
+ resolve = function(input)
+ input = input or 'user'
+ local birthday = input
+ if input == 'user' then
+ birthday = birthday .. ' birthday is April 1, 1990'
+ elseif input == 'napoleon' then
+ birthday = birthday .. ' birthday is August 15, 1769'
+ end
+
+ return {
+ {
+ content = birthday,
+ filename = input .. '_birthday',
+ filetype = 'text',
+ }
+ }
+ end
+ }
+ }
+ }
+<
+
+>markdown
+ > #birthday:user
+
+ What is my birthday
+<
+
+
+SELECTIONS *CopilotChat-selections*
+
+Selections are used to determine the source of the chat (so basically what to
+chat about). Selections are configurable either by default or by prompt.
+Default selection is `visual` or `buffer` (if no visual selection). Selection
+includes content, start and end position, buffer info and diagnostic info (if
+available). Supported selections that live in `local select =
+require("CopilotChat.select")` are:
+
+- `select.visual` - Current visual selection.
+- `select.buffer` - Current buffer content.
+- `select.line` - Current line content.
+- `select.unnamed` - Unnamed register content. This register contains last deleted, changed or yanked content.
+
+You can chain multiple selections like this:
+
+>lua
+ {
+ selection = function(source)
+ return select.visual(source) or select.buffer(source)
+ end
+ }
+<
+
+
+API *CopilotChat-api*
>lua
local chat = require("CopilotChat")
@@ -272,6 +410,11 @@ API ~
selection = require("CopilotChat.select").buffer,
})
+ -- Ask a question and provide custom contexts
+ chat.ask("Explain how it works.", {
+ context = { 'buffers', 'files', 'register:+' },
+ })
+
-- Ask a question and do something with the response
chat.ask("Show me something interesting", {
callback = function(response)
@@ -285,6 +428,10 @@ API ~
-- Get last copilot response (also can be used for integrations and custom keymaps)
local response = chat.response()
+ -- Retrieve current chat config
+ local config = chat.config
+ print(config.model)
+
-- Pick a prompt using vim.ui.select
local actions = require("CopilotChat.actions")
@@ -298,48 +445,71 @@ API ~
<
-CONFIGURATION *CopilotChat-configuration*
+==============================================================================
+4. Configuration *CopilotChat-configuration*
-DEFAULT CONFIGURATION ~
+DEFAULT CONFIGURATION *CopilotChat-default-configuration*
Also see here :
>lua
{
- debug = false, -- Enable debug logging (same as 'log_level = 'debug')
- log_level = 'info', -- Log level to use, 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
- proxy = nil, -- [protocol://]host[:port] Use this proxy
- allow_insecure = false, -- Allow insecure server connections
+
+ -- Shared config starts here (can be passed to functions at runtime and configured via setup function)
system_prompt = prompts.COPILOT_INSTRUCTIONS, -- System prompt to use (can be specified manually in prompt via /).
model = 'gpt-4o', -- Default model to use, see ':CopilotChatModels' for available models (can be specified manually in prompt via $).
agent = 'copilot', -- Default agent to use, see ':CopilotChatAgents' for available agents (can be specified manually in prompt via @).
- context = nil, -- Default context to use (can be specified manually in prompt via #).
+ context = nil, -- Default context or array of contexts to use (can be specified manually in prompt via #).
temperature = 0.1, -- GPT result temperature
- question_header = '## User ', -- Header to use for user questions
- answer_header = '## Copilot ', -- Header to use for AI answers
- error_header = '## Error ', -- Header to use for errors
- separator = '───', -- Separator to use in chat
+ headless = false, -- Do not write to chat buffer and use history(useful for using callback for custom processing)
+ callback = nil, -- Callback to use when ask response is received
+
+ -- default selection
+ selection = function(source)
+ return select.visual(source) or select.buffer(source)
+ end,
+
+ -- default window options
+ window = {
+ layout = 'vertical', -- 'vertical', 'horizontal', 'float', 'replace'
+ width = 0.5, -- fractional width of parent, or absolute width in columns when > 1
+ height = 0.5, -- fractional height of parent, or absolute height in rows when > 1
+ -- Options below only apply to floating windows
+ relative = 'editor', -- 'editor', 'win', 'cursor', 'mouse'
+ border = 'single', -- 'none', single', 'double', 'rounded', 'solid', 'shadow'
+ row = nil, -- row position of the window, default is centered
+ col = nil, -- column position of the window, default is centered
+ title = 'Copilot Chat', -- title of chat window
+ footer = nil, -- footer of chat window
+ zindex = 1, -- determines if window is on top or below other floating windows
+ },
- chat_autocomplete = true, -- Enable chat autocompletion (when disabled, requires manual `mappings.complete` trigger)
- show_folds = true, -- Shows folds for sections in chat
show_help = true, -- Shows help message as virtual lines when waiting for user input
+ show_folds = true, -- Shows folds for sections in chat
+ highlight_selection = true, -- Highlight selection
+ highlight_headers = true, -- Highlight headers in chat, disable if using markdown renderers (like render-markdown.nvim)
auto_follow_cursor = true, -- Auto-follow cursor in chat
auto_insert_mode = false, -- Automatically enter insert mode when opening window and on new prompt
insert_at_end = false, -- Move cursor to end of buffer when inserting text
clear_chat_on_new_prompt = false, -- Clears chat on every new prompt
- highlight_selection = true, -- Highlight selection in the source buffer when in the chat window
- highlight_headers = true, -- Highlight headers in chat, disable if using markdown renderers (like render-markdown.nvim)
+ -- Static config starts here (can be configured only via setup function)
+
+ debug = false, -- Enable debug logging (same as 'log_level = 'debug')
+ log_level = 'info', -- Log level to use, 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
+ proxy = nil, -- [protocol://]host[:port] Use this proxy
+ allow_insecure = false, -- Allow insecure server connections
+
+ chat_autocomplete = true, -- Enable chat autocompletion (when disabled, requires manual `mappings.complete` trigger)
history_path = vim.fn.stdpath('data') .. '/copilotchat_history', -- Default path to stored history
- callback = nil, -- Callback to use when ask response is received
- -- default selection
- selection = function(source)
- return select.visual(source) or select.buffer(source)
- end,
+ question_header = '# User ', -- Header to use for user questions
+ answer_header = '# Copilot ', -- Header to use for AI answers
+ error_header = '# Error ', -- Header to use for errors
+ separator = '───', -- Separator to use in chat
-- default contexts
contexts = {
@@ -358,12 +528,18 @@ Also see here :
git = {
-- see config.lua for implementation
},
+ url = {
+ -- see config.lua for implementation
+ },
+ register = {
+ -- see config.lua for implementation
+ },
},
-- default prompts
prompts = {
Explain = {
- prompt = '> /COPILOT_EXPLAIN\n\nWrite an explanation for the selected code and diagnostics as paragraphs of text.',
+ prompt = '> /COPILOT_EXPLAIN\n\nWrite an explanation for the selected code as paragraphs of text.',
},
Review = {
prompt = '> /COPILOT_REVIEW\n\nReview the selected code.',
@@ -386,37 +562,22 @@ Also see here :
},
},
- -- default window options
- window = {
- layout = 'vertical', -- 'vertical', 'horizontal', 'float', 'replace'
- width = 0.5, -- fractional width of parent, or absolute width in columns when > 1
- height = 0.5, -- fractional height of parent, or absolute height in rows when > 1
- -- Options below only apply to floating windows
- relative = 'editor', -- 'editor', 'win', 'cursor', 'mouse'
- border = 'single', -- 'none', single', 'double', 'rounded', 'solid', 'shadow'
- row = nil, -- row position of the window, default is centered
- col = nil, -- column position of the window, default is centered
- title = 'Copilot Chat', -- title of chat window
- footer = nil, -- footer of chat window
- zindex = 1, -- determines if window is on top or below other floating windows
- },
-
-- default mappings
mappings = {
complete = {
- insert ='',
+ insert = '',
},
close = {
normal = 'q',
- insert = ''
+ insert = '',
},
reset = {
- normal ='',
- insert = ''
+ normal = '',
+ insert = '',
},
submit_prompt = {
normal = '',
- insert = ''
+ insert = '',
},
toggle_sticky = {
detail = 'Makes line under cursor sticky or deletes sticky line.',
@@ -424,97 +585,36 @@ Also see here :
},
accept_diff = {
normal = '',
- insert = ''
+ insert = '',
+ },
+ jump_to_diff = {
+ normal = 'gj',
+ },
+ quickfix_diffs = {
+ normal = 'gq',
},
yank_diff = {
normal = 'gy',
register = '"',
},
show_diff = {
- normal = 'gd'
- },
- show_system_prompt = {
- normal = 'gp'
- },
- show_user_selection = {
- normal = 'gs'
- },
- },
- }
-<
-
-For further reference, you can view @jellydn’s configuration
-.
-
-
-DEFINING A PROMPT WITH COMMAND AND KEYMAP ~
-
-This will define prompt that you can reference with `/MyCustomPrompt` in chat,
-call with `:CopilotChatMyCustomPrompt` or use the keymap `ccmc`. It
-will use visual selection as default selection. If you are using `lazy.nvim`
-and are already lazy loading based on `Commands` make sure to include the
-prompt commands and keymaps in `cmd` and `keys` respectively.
-
->lua
- {
- prompts = {
- MyCustomPrompt = {
- prompt = 'Explain how it works.',
- mapping = 'ccmc',
- description = 'My custom prompt description',
- selection = require('CopilotChat.select').visual,
- },
- },
- }
-<
-
-
-REFERENCING SYSTEM OR USER PROMPTS ~
-
-You can reference system or user prompts in your configuration or in chat with
-`/PROMPT_NAME` slash notation. For collection of default `COPILOT_` (system)
-and `USER_` (user) prompts, see here .
-
->lua
- {
- prompts = {
- MyCustomPrompt = {
- prompt = '/COPILOT_EXPLAIN Explain how it works.',
+ normal = 'gd',
},
- MyCustomPrompt2 = {
- prompt = '/MyCustomPrompt Include some additional context.',
+ show_info = {
+ normal = 'gi',
},
- },
- }
-<
-
-
-CUSTOM SYSTEM PROMPTS ~
-
-You can define custom system prompts by using `system_prompt` property when
-passing config around.
-
->lua
- {
- system_prompt = 'Your name is Github Copilot and you are a AI assistant for developers.',
- prompts = {
- Johnny = {
- system_prompt = 'Your name is Johny Microsoft and you are not an AI assistant for developers.',
- prompt = 'Explain how it works.',
+ show_context = {
+ normal = 'gc',
},
- Yarrr = {
- system_prompt = 'You are fascinated by pirates, so please respond in pirate speak.'
+ show_help = {
+ normal = 'gh',
},
},
}
<
-To use any of your custom prompts, simply do `:CopilotChat`. E.g.
-`:CopilotChatJohnny` or `:CopilotChatYarrr What is a sorting algo?`. Tab
-autocomplete will help you out.
-
-CUSTOMIZING BUFFERS ~
+CUSTOMIZING BUFFERS *CopilotChat-customizing-buffers*
You can set local options for the buffers that are created by this plugin:
`copilot-diff`, `copilot-system-prompt`, `copilot-user-selection`,
@@ -535,7 +635,8 @@ You can set local options for the buffers that are created by this plugin:
<
-TIPS *CopilotChat-tips*
+==============================================================================
+5. Tips *CopilotChat-tips*
Quick chat with your buffer ~
@@ -629,21 +730,25 @@ installed.
file_types = { 'markdown', 'copilot-chat' },
})
- -- You might also want to disable default header highlighting for copilot chat when doing this
+ -- You might also want to disable default header highlighting for copilot chat when doing this and set error header style and separator
require('CopilotChat').setup({
highlight_headers = false,
+ separator = '---',
+ error_header = '> [!ERROR] Error',
-- rest of your config
})
<
-ROADMAP (WISHLIST) *CopilotChat-roadmap-(wishlist)*
+==============================================================================
+6. Roadmap *CopilotChat-roadmap*
-- Use indexed vector database with current workspace for better context selection
+- Improved caching for context (persistence through restarts/smarter caching)
- General QOL improvements
-DEVELOPMENT *CopilotChat-development*
+==============================================================================
+7. Development *CopilotChat-development*
INSTALLING PRE-COMMIT TOOL ~
@@ -658,7 +763,8 @@ pre-commit tool:
This will install the pre-commit tool and the pre-commit hooks.
-CONTRIBUTORS ✨ *CopilotChat-contributors-✨*
+==============================================================================
+8. Contributors *CopilotChat-contributors*
If you want to contribute to this project, please read the CONTRIBUTING.md
file.
@@ -666,7 +772,7 @@ If you want to contribute to this project, please read the CONTRIBUTING.md
Thanks goes to these wonderful people (emoji key
):
-gptlang💻 📖Dung Duc Huynh (Kaka)💻 📖Ahmed Haracic💻Trí Thiện Nguyễn💻He Zhizhou💻Guruprakash Rajakkannu💻kristofka💻PostCyberPunk📖Katsuhiko Nishimra💻Erno Hopearuoho💻Shaun Garwood💻neutrinoA4💻 📖Jack Muratore💻Adriel Velazquez💻 📖Tomas Slusny💻 📖Nisal📖Tobias Gårdhus📖Petr Dlouhý📖Dylan Madisetti💻Aaron Weisberg💻 📖Jose Tlacuilo💻 📖Kevin Traver💻 📖dTry💻Arata Furukawa💻Ling💻Ivan Frolov💻Folke Lemaitre💻 📖GitMurf💻Dmitrii Lipin💻jinzhongjia📖guill💻Sjon-Paul Brown💻Renzo Mondragón💻 📖fjchen7💻Radosław Woźniak💻JakubPecenka💻thomastthai📖Tomáš Janoušek💻Toddneal Stallworth📖Sergey Alexandrov💻This project follows the all-contributors
+gptlang💻 📖Dung Duc Huynh (Kaka)💻 📖Ahmed Haracic💻Trí Thiện Nguyễn💻He Zhizhou💻Guruprakash Rajakkannu💻kristofka💻PostCyberPunk📖Katsuhiko Nishimra💻Erno Hopearuoho💻Shaun Garwood💻neutrinoA4💻 📖Jack Muratore💻Adriel Velazquez💻 📖Tomas Slusny💻 📖Nisal📖Tobias Gårdhus📖Petr Dlouhý📖Dylan Madisetti💻Aaron Weisberg💻 📖Jose Tlacuilo💻 📖Kevin Traver💻 📖dTry💻Arata Furukawa💻Ling💻Ivan Frolov💻Folke Lemaitre💻 📖GitMurf💻Dmitrii Lipin💻jinzhongjia📖guill💻Sjon-Paul Brown💻Renzo Mondragón💻 📖fjchen7💻Radosław Woźniak💻JakubPecenka💻thomastthai📖Tomáš Janoušek💻Toddneal Stallworth📖Sergey Alexandrov💻Léopold Mebazaa💻This project follows the all-contributors
specification.
Contributions of any kind are welcome!
@@ -676,22 +782,16 @@ STARGAZERS OVER TIME ~
==============================================================================
-2. Links *CopilotChat-links*
-
-1. *Documentation*: https://img.shields.io/badge/documentation-yes-brightgreen.svg
-2. *pre-commit.ci*: https://results.pre-commit.ci/badge/github/CopilotC-Nvim/CopilotChat.nvim/main.svg
-3. *Discord*: https://img.shields.io/discord/1200633211236122665.svg
-4. *Dotfyle*: https://dotfyle.com/plugins/CopilotC-Nvim/CopilotChat.nvim/shield?style=flat
-5. *All Contributors*: https://img.shields.io/github/all-contributors/CopilotC-Nvim/CopilotChat.nvim?color=ee8449&style=flat&link=%23contributors-
-6. *@jellydn*:
-7. *@deathbeam*:
-8. *@jellydn*:
-9. *Chat with buffer*: https://i.gyazo.com/9b8cbf1d78a19f326282a6520bc9aab0.gif
-10. *inline-chat*: https://github.com/CopilotC-Nvim/CopilotChat.nvim/assets/5115805/608e3c9b-8569-408d-a5d1-2213325fc93c
-11. *image*: https://github.com/CopilotC-Nvim/CopilotChat.nvim/assets/5115805/14360883-7535-4ee3-aca1-79f6c39f626b
-12. *image*: https://github.com/CopilotC-Nvim/CopilotChat.nvim/assets/5115805/743455bb-9517-48a8-a7a1-81215dc3b747
-13. *image*: https://github.com/user-attachments/assets/d8dc16f8-3f61-43fa-bfb9-83f240ae30e8
-14. *Stargazers over time*: https://starchart.cc/CopilotC-Nvim/CopilotChat.nvim.svg
+9. Links *CopilotChat-links*
+
+1. *@jellydn*:
+2. *@deathbeam*:
+3. *chat-with-buffer*: https://i.gyazo.com/9b8cbf1d78a19f326282a6520bc9aab0.gif
+4. *inline-chat*: https://github.com/CopilotC-Nvim/CopilotChat.nvim/assets/5115805/608e3c9b-8569-408d-a5d1-2213325fc93c
+5. *telescope-integration*: https://github.com/CopilotC-Nvim/CopilotChat.nvim/assets/5115805/14360883-7535-4ee3-aca1-79f6c39f626b
+6. *fzf-lua-integration*: https://github.com/CopilotC-Nvim/CopilotChat.nvim/assets/5115805/743455bb-9517-48a8-a7a1-81215dc3b747
+7. *render-markdown-integration*: https://github.com/user-attachments/assets/d8dc16f8-3f61-43fa-bfb9-83f240ae30e8
+8. *Stargazers over time*: https://starchart.cc/CopilotC-Nvim/CopilotChat.nvim.svg
Generated by panvimdoc
diff --git a/lua/CopilotChat/actions.lua b/lua/CopilotChat/actions.lua
index 4ae5dfeb..fa93976f 100644
--- a/lua/CopilotChat/actions.lua
+++ b/lua/CopilotChat/actions.lua
@@ -13,12 +13,14 @@ function M.help_actions()
end
--- User prompt actions
----@param config CopilotChat.config?: The chat configuration
+---@param config CopilotChat.config.shared?: The chat configuration
---@return CopilotChat.integrations.actions?: The prompt actions
function M.prompt_actions(config)
local actions = {}
- for name, prompt in pairs(chat.prompts(true)) do
- actions[name] = vim.tbl_extend('keep', prompt, config or {})
+ for name, prompt in pairs(chat.prompts()) do
+ if prompt.prompt then
+ actions[name] = vim.tbl_extend('keep', prompt, config or {})
+ end
end
return {
prompt = 'Copilot Chat Prompt Actions',
diff --git a/lua/CopilotChat/chat.lua b/lua/CopilotChat/chat.lua
deleted file mode 100644
index ba80787a..00000000
--- a/lua/CopilotChat/chat.lua
+++ /dev/null
@@ -1,309 +0,0 @@
----@class CopilotChat.Chat
----@field bufnr number
----@field winnr number
----@field valid fun(self: CopilotChat.Chat)
----@field visible fun(self: CopilotChat.Chat)
----@field active fun(self: CopilotChat.Chat)
----@field append fun(self: CopilotChat.Chat, str: string)
----@field last fun(self: CopilotChat.Chat)
----@field clear fun(self: CopilotChat.Chat)
----@field open fun(self: CopilotChat.Chat, config: CopilotChat.config)
----@field close fun(self: CopilotChat.Chat, bufnr: number?)
----@field focus fun(self: CopilotChat.Chat)
----@field follow fun(self: CopilotChat.Chat)
----@field finish fun(self: CopilotChat.Chat, msg: string?, offset: number?)
----@field delete fun(self: CopilotChat.Chat)
-
-local Overlay = require('CopilotChat.overlay')
-local Spinner = require('CopilotChat.spinner')
-local utils = require('CopilotChat.utils')
-local is_stable = utils.is_stable
-local class = utils.class
-
-function CopilotChatFoldExpr(lnum, separator)
- local to_match = separator .. '$'
- if string.match(vim.fn.getline(lnum), to_match) then
- return '1'
- elseif string.match(vim.fn.getline(lnum + 1), to_match) then
- return '0'
- end
- return '='
-end
-
-local Chat = class(function(self, help, on_buf_create)
- self.header_ns = vim.api.nvim_create_namespace('copilot-chat-headers')
- self.help = help
- self.on_buf_create = on_buf_create
- self.bufnr = nil
- self.winnr = nil
- self.spinner = nil
- self.separator = nil
- self.auto_insert = false
- self.auto_follow_cursor = true
- self.highlight_headers = true
- self.layout = nil
-
- vim.treesitter.language.register('markdown', 'copilot-chat')
-
- self.buf_create = function()
- local bufnr = vim.api.nvim_create_buf(false, true)
- vim.api.nvim_buf_set_name(bufnr, 'copilot-chat')
- vim.bo[bufnr].filetype = 'copilot-chat'
- vim.bo[bufnr].syntax = 'markdown'
- vim.bo[bufnr].textwidth = 0
- local ok, parser = pcall(vim.treesitter.get_parser, bufnr, 'markdown')
- if ok and parser then
- vim.treesitter.start(bufnr, 'markdown')
- end
-
- if not self.spinner then
- self.spinner = Spinner(bufnr)
- else
- self.spinner.bufnr = bufnr
- end
-
- return bufnr
- end
-end, Overlay)
-
-function Chat:visible()
- return self.winnr
- and vim.api.nvim_win_is_valid(self.winnr)
- and vim.api.nvim_win_get_buf(self.winnr) == self.bufnr
-end
-
-function Chat:render()
- if not self.highlight_headers or not self:visible() then
- return
- end
-
- vim.api.nvim_buf_clear_namespace(self.bufnr, self.header_ns, 0, -1)
- local lines = vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false)
- for l, line in ipairs(lines) do
- if line:match(self.separator .. '$') then
- local sep = vim.fn.strwidth(line) - vim.fn.strwidth(self.separator)
- -- separator line
- vim.api.nvim_buf_set_extmark(self.bufnr, self.header_ns, l - 1, sep, {
- virt_text_win_col = sep,
- virt_text = { { string.rep(self.separator, vim.go.columns), 'CopilotChatSeparator' } },
- priority = 100,
- strict = false,
- })
- -- header hl group
- vim.api.nvim_buf_set_extmark(self.bufnr, self.header_ns, l - 1, 0, {
- end_col = sep + 1,
- hl_group = 'CopilotChatHeader',
- priority = 100,
- strict = false,
- })
- end
- end
-end
-
-function Chat:active()
- return vim.api.nvim_get_current_win() == self.winnr
-end
-
-function Chat:last()
- self:validate()
- local line_count = vim.api.nvim_buf_line_count(self.bufnr)
- local last_line = line_count - 1
- if last_line < 0 then
- return 0, 0, line_count
- end
- local last_line_content = vim.api.nvim_buf_get_lines(self.bufnr, -2, -1, false)
- if not last_line_content or #last_line_content == 0 then
- return last_line, 0, line_count
- end
- local last_column = #last_line_content[1]
- return last_line, last_column, line_count
-end
-
-function Chat:append(str)
- self:validate()
-
- if self:active() then
- utils.return_to_normal_mode()
- end
-
- if self.spinner then
- self.spinner:start()
- end
-
- -- Decide if we should follow cursor after appending text.
- local should_follow_cursor = self.auto_follow_cursor
- if self.auto_follow_cursor and self:visible() then
- local current_pos = vim.api.nvim_win_get_cursor(self.winnr)
- local line_count = vim.api.nvim_buf_line_count(self.bufnr)
- -- Follow only if the cursor is currently at the last line.
- should_follow_cursor = current_pos[1] == line_count
- end
-
- local last_line, last_column, _ = self:last()
- vim.api.nvim_buf_set_text(
- self.bufnr,
- last_line,
- last_column,
- last_line,
- last_column,
- vim.split(str, '\n')
- )
- self:render()
-
- if should_follow_cursor then
- self:follow()
- end
-end
-
-function Chat:clear()
- self:validate()
- vim.api.nvim_buf_set_lines(self.bufnr, 0, -1, false, {})
- self:render()
-end
-
-function Chat:open(config)
- self:validate()
-
- local window = config.window
- local layout = window.layout
- local width = window.width > 1 and window.width or math.floor(vim.o.columns * window.width)
- local height = window.height > 1 and window.height or math.floor(vim.o.lines * window.height)
-
- if self.layout ~= layout then
- self:close()
- end
-
- if self:visible() then
- return
- end
-
- if layout == 'float' then
- local win_opts = {
- style = 'minimal',
- width = width,
- height = height,
- zindex = window.zindex,
- relative = window.relative,
- border = window.border,
- title = window.title,
- row = window.row or math.floor((vim.o.lines - height) / 2),
- col = window.col or math.floor((vim.o.columns - width) / 2),
- }
- if not is_stable() then
- win_opts.footer = window.footer
- end
- self.winnr = vim.api.nvim_open_win(self.bufnr, false, win_opts)
- elseif layout == 'vertical' then
- local orig = vim.api.nvim_get_current_win()
- local cmd = 'vsplit'
- if width ~= 0 then
- cmd = width .. cmd
- end
- vim.cmd(cmd)
- self.winnr = vim.api.nvim_get_current_win()
- vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
- vim.api.nvim_set_current_win(orig)
- elseif layout == 'horizontal' then
- local orig = vim.api.nvim_get_current_win()
- local cmd = 'split'
- if height ~= 0 then
- cmd = height .. cmd
- end
- vim.cmd(cmd)
- self.winnr = vim.api.nvim_get_current_win()
- vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
- vim.api.nvim_set_current_win(orig)
- elseif layout == 'replace' then
- self.winnr = vim.api.nvim_get_current_win()
- vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
- end
-
- self.layout = layout
- self.separator = config.separator
- self.auto_insert = config.auto_insert
- self.auto_follow_cursor = config.auto_follow_cursor
- self.highlight_headers = config.highlight_headers
-
- vim.wo[self.winnr].wrap = true
- vim.wo[self.winnr].linebreak = true
- vim.wo[self.winnr].cursorline = true
- vim.wo[self.winnr].conceallevel = 2
- vim.wo[self.winnr].foldlevel = 99
- if config.show_folds then
- vim.wo[self.winnr].foldcolumn = '1'
- vim.wo[self.winnr].foldmethod = 'expr'
- vim.wo[self.winnr].foldexpr = "v:lua.CopilotChatFoldExpr(v:lnum, '" .. config.separator .. "')"
- else
- vim.wo[self.winnr].foldcolumn = '0'
- end
- self:render()
-end
-
-function Chat:close(bufnr)
- if self.spinner then
- self.spinner:finish()
- end
-
- if self:visible() then
- if self:active() then
- utils.return_to_normal_mode()
- end
-
- if self.layout == 'replace' then
- self:restore(self.winnr, bufnr)
- else
- vim.api.nvim_win_close(self.winnr, true)
- end
-
- self.winnr = nil
- end
-end
-
-function Chat:focus()
- if self:visible() then
- vim.api.nvim_set_current_win(self.winnr)
- if self.auto_insert and self:active() then
- vim.cmd('startinsert')
- end
- end
-end
-
-function Chat:follow()
- if not self:visible() then
- return
- end
-
- local last_line, last_column, line_count = self:last()
- if line_count == 0 then
- return
- end
-
- vim.api.nvim_win_set_cursor(self.winnr, { last_line + 1, last_column })
-end
-
-function Chat:finish(msg, offset)
- if not self.spinner then
- return
- end
-
- if not offset then
- offset = 0
- end
-
- self.spinner:finish()
-
- if msg and msg ~= '' then
- if self.help and self.help ~= '' then
- msg = msg .. '\n' .. self.help
- end
- else
- msg = self.help
- end
-
- self:show_help(msg, -offset)
- if self.auto_insert and self:active() then
- vim.cmd('startinsert')
- end
-end
-
-return Chat
diff --git a/lua/CopilotChat/config.lua b/lua/CopilotChat/config.lua
index 79c250c5..b3993d63 100644
--- a/lua/CopilotChat/config.lua
+++ b/lua/CopilotChat/config.lua
@@ -1,42 +1,17 @@
local prompts = require('CopilotChat.prompts')
local context = require('CopilotChat.context')
local select = require('CopilotChat.select')
-
---- @class CopilotChat.config.source
---- @field bufnr number
---- @field winnr number
-
----@class CopilotChat.config.selection.diagnostic
----@field message string
----@field severity string
----@field start_row number
----@field start_col number
----@field end_row number
----@field end_col number
-
----@class CopilotChat.config.selection
----@field lines string
----@field diagnostics table?
----@field filename string?
----@field filetype string?
----@field start_row number?
----@field start_col number?
----@field end_row number?
----@field end_col number?
+local utils = require('CopilotChat.utils')
---@class CopilotChat.config.context
---@field description string?
----@field input fun(callback: fun(input: string?))?
----@field resolve fun(input: string?, source: CopilotChat.config.source):table
+---@field input fun(callback: fun(input: string?), source: CopilotChat.source)?
+---@field resolve fun(input: string?, source: CopilotChat.source):table
----@class CopilotChat.config.prompt
+---@class CopilotChat.config.prompt : CopilotChat.config.shared
---@field prompt string?
---@field description string?
----@field kind string?
---@field mapping string?
----@field system_prompt string?
----@field callback fun(response: string, source: CopilotChat.config.source)?
----@field selection nil|fun(source: CopilotChat.config.source):CopilotChat.config.selection?
---@class CopilotChat.config.window
---@field layout string?
@@ -55,6 +30,9 @@ local select = require('CopilotChat.select')
---@field insert string?
---@field detail string?
+---@class CopilotChat.config.mapping.register : CopilotChat.config.mapping
+---@field register string?
+
---@class CopilotChat.config.mappings
---@field complete CopilotChat.config.mapping?
---@field close CopilotChat.config.mapping?
@@ -62,89 +40,117 @@ local select = require('CopilotChat.select')
---@field submit_prompt CopilotChat.config.mapping?
---@field toggle_sticky CopilotChat.config.mapping?
---@field accept_diff CopilotChat.config.mapping?
----@field yank_diff CopilotChat.config.mapping?
+---@field jump_to_diff CopilotChat.config.mapping?
+---@field quickfix_diffs CopilotChat.config.mapping?
+---@field yank_diff CopilotChat.config.mapping.register?
---@field show_diff CopilotChat.config.mapping?
----@field show_system_prompt CopilotChat.config.mapping?
----@field show_user_selection CopilotChat.config.mapping?
+---@field show_info CopilotChat.config.mapping?
+---@field show_context CopilotChat.config.mapping?
---@field show_help CopilotChat.config.mapping?
---- CopilotChat default configuration
----@class CopilotChat.config
----@field debug boolean?
----@field log_level string?
----@field proxy string?
----@field allow_insecure boolean?
+---@class CopilotChat.config.shared
---@field system_prompt string?
---@field model string?
---@field agent string?
----@field context string?
+---@field context string|table|nil
---@field temperature number?
----@field question_header string?
----@field answer_header string?
----@field error_header string?
----@field separator string?
----@field chat_autocomplete boolean?
----@field show_folds boolean?
+---@field headless boolean?
+---@field callback fun(response: string, source: CopilotChat.source)?
+---@field selection nil|fun(source: CopilotChat.source):CopilotChat.select.selection?
+---@field window CopilotChat.config.window?
---@field show_help boolean?
+---@field show_folds boolean?
+---@field highlight_selection boolean?
+---@field highlight_headers boolean?
---@field auto_follow_cursor boolean?
---@field auto_insert_mode boolean?
+---@field insert_at_end boolean?
---@field clear_chat_on_new_prompt boolean?
----@field highlight_selection boolean?
----@field highlight_headers boolean?
+
+--- CopilotChat default configuration
+---@class CopilotChat.config : CopilotChat.config.shared
+---@field debug boolean?
+---@field log_level string?
+---@field proxy string?
+---@field allow_insecure boolean?
+---@field chat_autocomplete boolean?
---@field history_path string?
----@field callback fun(response: string, source: CopilotChat.config.source)?
----@field selection nil|fun(source: CopilotChat.config.source):CopilotChat.config.selection?
+---@field question_header string?
+---@field answer_header string?
+---@field error_header string?
+---@field separator string?
---@field contexts table?
---@field prompts table?
----@field window CopilotChat.config.window?
---@field mappings CopilotChat.config.mappings?
return {
- debug = false, -- Enable debug logging (same as 'log_level = 'debug')
- log_level = 'info', -- Log level to use, 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
- proxy = nil, -- [protocol://]host[:port] Use this proxy
- allow_insecure = false, -- Allow insecure server connections
+
+ -- Shared config starts here (can be passed to functions at runtime and configured via setup function)
system_prompt = prompts.COPILOT_INSTRUCTIONS, -- System prompt to use (can be specified manually in prompt via /).
model = 'gpt-4o', -- Default model to use, see ':CopilotChatModels' for available models (can be specified manually in prompt via $).
agent = 'copilot', -- Default agent to use, see ':CopilotChatAgents' for available agents (can be specified manually in prompt via @).
- context = nil, -- Default context to use (can be specified manually in prompt via #).
+ context = nil, -- Default context or array of contexts to use (can be specified manually in prompt via #).
temperature = 0.1, -- GPT result temperature
- question_header = '## User ', -- Header to use for user questions
- answer_header = '## Copilot ', -- Header to use for AI answers
- error_header = '## Error ', -- Header to use for errors
- separator = '───', -- Separator to use in chat
+ headless = false, -- Do not write to chat buffer and use history(useful for using callback for custom processing)
+ callback = nil, -- Callback to use when ask response is received
+
+ -- default selection
+ selection = function(source)
+ return select.visual(source) or select.buffer(source)
+ end,
+
+ -- default window options
+ window = {
+ layout = 'vertical', -- 'vertical', 'horizontal', 'float', 'replace'
+ width = 0.5, -- fractional width of parent, or absolute width in columns when > 1
+ height = 0.5, -- fractional height of parent, or absolute height in rows when > 1
+ -- Options below only apply to floating windows
+ relative = 'editor', -- 'editor', 'win', 'cursor', 'mouse'
+ border = 'single', -- 'none', single', 'double', 'rounded', 'solid', 'shadow'
+ row = nil, -- row position of the window, default is centered
+ col = nil, -- column position of the window, default is centered
+ title = 'Copilot Chat', -- title of chat window
+ footer = nil, -- footer of chat window
+ zindex = 1, -- determines if window is on top or below other floating windows
+ },
- chat_autocomplete = true, -- Enable chat autocompletion (when disabled, requires manual `mappings.complete` trigger)
- show_folds = true, -- Shows folds for sections in chat
show_help = true, -- Shows help message as virtual lines when waiting for user input
+ show_folds = true, -- Shows folds for sections in chat
+ highlight_selection = true, -- Highlight selection
+ highlight_headers = true, -- Highlight headers in chat, disable if using markdown renderers (like render-markdown.nvim)
auto_follow_cursor = true, -- Auto-follow cursor in chat
auto_insert_mode = false, -- Automatically enter insert mode when opening window and on new prompt
insert_at_end = false, -- Move cursor to end of buffer when inserting text
clear_chat_on_new_prompt = false, -- Clears chat on every new prompt
- highlight_selection = true, -- Highlight selection
- highlight_headers = true, -- Highlight headers in chat, disable if using markdown renderers (like render-markdown.nvim)
+ -- Static config starts here (can be configured only via setup function)
+
+ debug = false, -- Enable debug logging (same as 'log_level = 'debug')
+ log_level = 'info', -- Log level to use, 'trace', 'debug', 'info', 'warn', 'error', 'fatal'
+ proxy = nil, -- [protocol://]host[:port] Use this proxy
+ allow_insecure = false, -- Allow insecure server connections
+
+ chat_autocomplete = true, -- Enable chat autocompletion (when disabled, requires manual `mappings.complete` trigger)
history_path = vim.fn.stdpath('data') .. '/copilotchat_history', -- Default path to stored history
- callback = nil, -- Callback to use when ask response is received
- -- default selection
- selection = function(source)
- return select.visual(source) or select.buffer(source)
- end,
+ question_header = '## User ', -- Header to use for user questions
+ answer_header = '## Copilot ', -- Header to use for AI answers
+ error_header = '## Error ', -- Header to use for errors
+ separator = '───', -- Separator to use in chat
-- default contexts
contexts = {
buffer = {
- description = 'Includes specified buffer in chat context (default current). Supports input.',
+ description = 'Includes specified buffer in chat context. Supports input (default current).',
input = function(callback)
vim.ui.select(
vim.tbl_map(
function(buf)
- return { id = buf, name = vim.api.nvim_buf_get_name(buf) }
+ return { id = buf, name = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(buf), ':p:.') }
end,
vim.tbl_filter(function(buf)
- return vim.api.nvim_buf_is_loaded(buf) and vim.fn.buflisted(buf) == 1
+ return utils.buf_valid(buf) and vim.fn.buflisted(buf) == 1
end, vim.api.nvim_list_bufs())
),
{
@@ -159,13 +165,14 @@ return {
)
end,
resolve = function(input, source)
+ input = input and tonumber(input) or source.bufnr
return {
- context.outline(input and tonumber(input) or source.bufnr),
+ context.buffer(input),
}
end,
},
buffers = {
- description = 'Includes all buffers in chat context (default listed). Supports input.',
+ description = 'Includes all buffers in chat context. Supports input (default listed).',
input = function(callback)
vim.ui.select({ 'listed', 'visible' }, {
prompt = 'Select buffer scope> ',
@@ -173,22 +180,16 @@ return {
end,
resolve = function(input)
input = input or 'listed'
- return vim.tbl_map(
- context.outline,
- vim.tbl_filter(function(b)
- return vim.api.nvim_buf_is_loaded(b)
- and vim.fn.buflisted(b) == 1
- and (input == 'listed' or #vim.fn.win_findbuf(b) > 0)
- end, vim.api.nvim_list_bufs())
- )
+ return context.buffers(input)
end,
},
file = {
description = 'Includes content of provided file in chat context. Supports input.',
- input = function(callback)
+ input = function(callback, source)
+ local cwd = utils.win_cwd(source.winnr)
local files = vim.tbl_filter(function(file)
return vim.fn.isdirectory(file) == 0
- end, vim.fn.glob('**/*', false, true))
+ end, vim.fn.glob(cwd .. '/**/*', false, true))
vim.ui.select(files, {
prompt = 'Select a file> ',
@@ -201,27 +202,84 @@ return {
end,
},
files = {
- description = 'Includes all non-hidden filenames in the current workspace in chat context. Supports input.',
+ description = 'Includes all non-hidden files in the current workspace in chat context. Supports input (default list).',
input = function(callback)
- vim.ui.input({
- prompt = 'Enter a file pattern> ',
- default = '**/*',
- }, callback)
+ local choices = utils.kv_list({
+ list = 'Only lists file names',
+ full = 'Includes file content for each file found. Can be slow on large workspaces, use with care.',
+ })
+
+ vim.ui.select(choices, {
+ prompt = 'Select files content> ',
+ format_item = function(choice)
+ return choice.key .. ' - ' .. choice.value
+ end,
+ }, function(choice)
+ callback(choice and choice.key)
+ end)
end,
- resolve = function(input)
- return context.files(input)
+ resolve = function(input, source)
+ return context.files(source.winnr, input == 'full')
end,
},
git = {
- description = 'Includes current git diff in chat context (default unstaged). Supports input.',
+ description = 'Requires `git`. Includes current git diff in chat context. Supports input (default unstaged).',
input = function(callback)
vim.ui.select({ 'unstaged', 'staged' }, {
prompt = 'Select diff type> ',
}, callback)
end,
resolve = function(input, source)
+ input = input or 'unstaged'
+ return {
+ context.gitdiff(input, source.winnr),
+ }
+ end,
+ },
+ url = {
+ description = 'Includes content of provided URL in chat context. Supports input.',
+ input = function(callback)
+ vim.ui.input({
+ prompt = 'Enter URL> ',
+ default = 'https://',
+ }, callback)
+ end,
+ resolve = function(input)
+ return {
+ context.url(input),
+ }
+ end,
+ },
+ register = {
+ description = 'Includes contents of register in chat context. Supports input (default +, e.g clipboard).',
+ input = function(callback)
+ local choices = utils.kv_list({
+ ['+'] = 'synchronized with the system clipboard',
+ ['*'] = 'synchronized with the selection clipboard',
+ ['"'] = 'last deleted, changed, or yanked content',
+ ['0'] = 'last yank',
+ ['-'] = 'deleted or changed content smaller than one line',
+ ['.'] = 'last inserted text',
+ ['%'] = 'name of the current file',
+ [':'] = 'most recent executed command',
+ ['#'] = 'alternate buffer',
+ ['='] = 'result of an expression',
+ ['/'] = 'last search pattern',
+ })
+
+ vim.ui.select(choices, {
+ prompt = 'Select a register> ',
+ format_item = function(choice)
+ return choice.key .. ' - ' .. choice.value
+ end,
+ }, function(choice)
+ callback(choice and choice.key)
+ end)
+ end,
+ resolve = function(input)
+ input = input or '+'
return {
- context.gitdiff(input, source.bufnr),
+ context.register(input),
}
end,
},
@@ -230,7 +288,7 @@ return {
-- default prompts
prompts = {
Explain = {
- prompt = '> /COPILOT_EXPLAIN\n\nWrite an explanation for the selected code and diagnostics as paragraphs of text.',
+ prompt = '> /COPILOT_EXPLAIN\n\nWrite an explanation for the selected code as paragraphs of text.',
},
Review = {
prompt = '> /COPILOT_REVIEW\n\nReview the selected code.',
@@ -291,21 +349,6 @@ return {
},
},
- -- default window options
- window = {
- layout = 'vertical', -- 'vertical', 'horizontal', 'float', 'replace'
- width = 0.5, -- fractional width of parent, or absolute width in columns when > 1
- height = 0.5, -- fractional height of parent, or absolute height in rows when > 1
- -- Options below only apply to floating windows
- relative = 'editor', -- 'editor', 'win', 'cursor', 'mouse'
- border = 'single', -- 'none', single', 'double', 'rounded', 'solid', 'shadow'
- row = nil, -- row position of the window, default is centered
- col = nil, -- column position of the window, default is centered
- title = 'Copilot Chat', -- title of chat window
- footer = nil, -- footer of chat window
- zindex = 1, -- determines if window is on top or below other floating windows
- },
-
-- default mappings
mappings = {
complete = {
@@ -331,6 +374,12 @@ return {
normal = '',
insert = '',
},
+ jump_to_diff = {
+ normal = 'gj',
+ },
+ quickfix_diffs = {
+ normal = 'gq',
+ },
yank_diff = {
normal = 'gy',
register = '"',
@@ -338,11 +387,11 @@ return {
show_diff = {
normal = 'gd',
},
- show_system_prompt = {
- normal = 'gp',
+ show_info = {
+ normal = 'gi',
},
- show_user_selection = {
- normal = 'gs',
+ show_context = {
+ normal = 'gc',
},
show_help = {
normal = 'gh',
diff --git a/lua/CopilotChat/context.lua b/lua/CopilotChat/context.lua
index 3330939e..b1232f97 100644
--- a/lua/CopilotChat/context.lua
+++ b/lua/CopilotChat/context.lua
@@ -1,8 +1,30 @@
+---@class CopilotChat.context.symbol
+---@field name string?
+---@field signature string
+---@field type string
+---@field start_row number
+---@field start_col number
+---@field end_row number
+---@field end_col number
+
+---@class CopilotChat.context.embed
+---@field content string
+---@field filename string
+---@field filetype string
+---@field original string?
+---@field symbols table?
+---@field embedding table?
+
+local async = require('plenary.async')
local log = require('plenary.log')
+local notify = require('CopilotChat.notify')
+local utils = require('CopilotChat.utils')
+local file_cache = {}
+local url_cache = {}
local M = {}
-local outline_types = {
+local OUTLINE_TYPES = {
'local_function',
'function_item',
'arrow_function',
@@ -10,28 +32,30 @@ local outline_types = {
'function_declaration',
'method_definition',
'method_declaration',
+ 'proc_declaration',
+ 'template_declaration',
+ 'macro_declaration',
'constructor_declaration',
+ 'field_declaration',
'class_definition',
'class_declaration',
'interface_definition',
'interface_declaration',
+ 'record_declaration',
'type_alias_declaration',
'import_statement',
'import_from_statement',
+ 'atx_heading',
+ 'list_item',
}
-local comment_types = {
- 'comment',
- 'line_comment',
- 'block_comment',
- 'doc_comment',
-}
-
-local ignored_types = {
- 'export_statement',
+local NAME_TYPES = {
+ 'name',
+ 'identifier',
+ 'heading_content',
}
-local off_side_rule_languages = {
+local OFF_SIDE_RULE_LANGUAGES = {
'python',
'coffeescript',
'nim',
@@ -40,9 +64,14 @@ local off_side_rule_languages = {
'fsharp',
}
-local big_file_threshold = 500
-local selection_threshold = 200
+local TOP_SYMBOLS = 64
+local TOP_RELATED = 20
+local MULTI_FILE_THRESHOLD = 5
+--- Compute the cosine similarity between two vectors
+---@param a table
+---@param b table
+---@return number
local function spatial_distance_cosine(a, b)
local dot_product = 0
local magnitude_a = 0
@@ -57,270 +86,495 @@ local function spatial_distance_cosine(a, b)
return dot_product / (magnitude_a * magnitude_b)
end
+--- Rank data by relatedness to the query
+---@param query CopilotChat.context.embed
+---@param data table
+---@param top_n number
+---@return table
local function data_ranked_by_relatedness(query, data, top_n)
- local scores = {}
- for i, item in pairs(data) do
- scores[i] = { index = i, score = spatial_distance_cosine(item.embedding, query.embedding) }
- end
- table.sort(scores, function(a, b)
+ data = vim.tbl_map(function(item)
+ return vim.tbl_extend(
+ 'force',
+ item,
+ { score = spatial_distance_cosine(item.embedding, query.embedding) }
+ )
+ end, data)
+
+ table.sort(data, function(a, b)
return a.score > b.score
end)
- local result = {}
- for i = 1, math.min(top_n, #scores) do
- local srt = scores[i]
- table.insert(result, vim.tbl_extend('keep', data[srt.index], { score = srt.score }))
- end
- return result
+
+ return vim.list_slice(data, 1, top_n)
end
---- Get list of all files in workspace
----@param pattern string?
----@return table
-function M.files(pattern)
- local files = vim.tbl_filter(function(file)
- return vim.fn.isdirectory(file) == 0
- end, vim.fn.glob(pattern or '**/*', false, true))
-
- if #files == 0 then
- return {}
+--- Rank data by symbols
+---@param query string
+---@param data table
+---@param top_n number
+local function data_ranked_by_symbols(query, data, top_n)
+ local query_terms = {}
+ for term in query:lower():gmatch('%w+') do
+ query_terms[term] = true
end
- local out = {}
+ local results = {}
+ for _, entry in ipairs(data) do
+ local score = 0
+ local filename = entry.filename and entry.filename:lower() or ''
+
+ -- Filename matches (highest priority)
+ for term in pairs(query_terms) do
+ if filename:find(term, 1, true) then
+ score = score + 15
+ if vim.fn.fnamemodify(filename, ':t'):gsub('%..*$', '') == term then
+ score = score + 10
+ end
+ end
+ end
- -- Create embeddings in chunks
- local chunk_size = 100
- for i = 1, #files, chunk_size do
- local chunk = {}
- for j = i, math.min(i + chunk_size - 1, #files) do
- table.insert(chunk, files[j])
+ -- Symbol matches
+ if entry.symbols then
+ for _, symbol in ipairs(entry.symbols) do
+ for term in pairs(query_terms) do
+ -- Check symbol name (high priority)
+ if symbol.name and symbol.name:lower():find(term, 1, true) then
+ score = score + 5
+ if symbol.name:lower() == term then
+ score = score + 3
+ end
+ end
+
+ -- Check signature (medium priority)
+ -- This catches parameter names, return types, etc
+ if symbol.signature and symbol.signature:lower():find(term, 1, true) then
+ score = score + 2
+ end
+ end
+ end
end
- table.insert(out, {
- content = table.concat(chunk, '\n'),
- filename = 'file_map',
- filetype = 'text',
- })
+ table.insert(results, vim.tbl_extend('force', entry, { score = score }))
end
- return out
+ table.sort(results, function(a, b)
+ return a.score > b.score
+ end)
+
+ return vim.list_slice(results, 1, top_n)
end
---- Get the content of a file
----@param filename string
----@return CopilotChat.copilot.embed?
-function M.file(filename)
- local content = vim.fn.readfile(filename)
- if #content == 0 then
- return
+--- Get the full signature of a declaration
+---@param start_row number
+---@param start_col number
+---@param lines table
+---@return string
+local function get_full_signature(start_row, start_col, lines)
+ local start_line = lines[start_row + 1]
+ local signature = vim.trim(start_line:sub(start_col + 1))
+
+ -- Look ahead for opening brace on next line
+ if not signature:match('{') and (start_row + 2) <= #lines then
+ local next_line = vim.trim(lines[start_row + 2])
+ if next_line:match('^{') then
+ signature = signature .. ' {'
+ end
end
- return {
- content = table.concat(content, '\n'),
- filename = filename,
- filetype = vim.filetype.match({ filename = filename }),
- }
+ return signature
end
---- Build an outline for a buffer
---- FIXME: Handle multiline function argument definitions when building the outline
----@param bufnr number
----@return CopilotChat.copilot.embed?
-function M.outline(bufnr)
- local name = vim.api.nvim_buf_get_name(bufnr)
- local ft = vim.bo[bufnr].filetype
-
- -- If buffer is not too big, just return the content
- local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
- if #lines < big_file_threshold then
- return {
- content = table.concat(lines, '\n'),
- filename = name,
- filetype = ft,
- }
+--- Get the name of a node
+---@param node table
+---@param content string
+---@return string?
+local function get_node_name(node, content)
+ for _, name_type in ipairs(NAME_TYPES) do
+ local name_field = node:field(name_type)
+ if name_field and #name_field > 0 then
+ return vim.treesitter.get_node_text(name_field[1], content)
+ end
end
+ return nil
+end
+
+--- Build an outline and symbols from a string
+---@param content string
+---@param filename string
+---@param ft string
+---@return CopilotChat.context.embed
+local function build_outline(content, filename, ft)
+ local output = {
+ filename = filename,
+ filetype = ft,
+ content = content,
+ }
+
local lang = vim.treesitter.language.get_lang(ft)
local ok, parser = false, nil
if lang then
- ok, parser = pcall(vim.treesitter.get_parser, bufnr, lang)
+ ok, parser = pcall(vim.treesitter.get_string_parser, content, lang)
end
if not ok or not parser then
ft = string.gsub(ft, 'react', '')
- ok, parser = pcall(vim.treesitter.get_parser, bufnr, ft)
+ ok, parser = pcall(vim.treesitter.get_string_parser, content, ft)
if not ok or not parser then
- return
+ return output
end
end
local root = parser:parse()[1]:root()
+ local lines = vim.split(content, '\n')
+ local symbols = {}
local outline_lines = {}
- local comment_lines = {}
local depth = 0
- local function get_outline_lines(node)
+ local function parse_node(node)
local type = node:type()
- local parent = node:parent()
- local is_outline = vim.tbl_contains(outline_types, type)
- local is_comment = vim.tbl_contains(comment_types, type)
- local is_ignored = vim.tbl_contains(ignored_types, type)
- or parent and vim.tbl_contains(ignored_types, parent:type())
+ local is_outline = vim.tbl_contains(OUTLINE_TYPES, type)
local start_row, start_col, end_row, end_col = node:range()
- local skip_inner = false
if is_outline then
depth = depth + 1
-
- if #comment_lines > 0 then
- for _, line in ipairs(comment_lines) do
- table.insert(outline_lines, string.rep(' ', depth) .. line)
- end
- comment_lines = {}
- end
-
- local start_line = vim.api.nvim_buf_get_lines(bufnr, start_row, start_row + 1, false)[1]
- local signature_start =
- vim.api.nvim_buf_get_text(bufnr, start_row, start_col, start_row, #start_line, {})[1]
- table.insert(outline_lines, string.rep(' ', depth) .. vim.trim(signature_start))
-
- -- If the function definition spans multiple lines, add an ellipsis
- if start_row ~= end_row then
- table.insert(outline_lines, string.rep(' ', depth + 1) .. '...')
- else
- skip_inner = true
- end
- elseif is_comment then
- skip_inner = true
- local comment = vim.split(vim.treesitter.get_node_text(node, bufnr, {}), '\n')
- for _, line in ipairs(comment) do
- table.insert(comment_lines, vim.trim(line))
- end
- elseif not is_ignored then
- comment_lines = {}
+ local name = get_node_name(node, content)
+ local signature_start = get_full_signature(start_row, start_col, lines)
+ table.insert(outline_lines, string.rep(' ', depth) .. signature_start)
+
+ -- Store symbol information
+ table.insert(symbols, {
+ name = name,
+ signature = signature_start,
+ type = type,
+ start_row = start_row + 1,
+ start_col = start_col + 1,
+ end_row = end_row,
+ end_col = end_col,
+ })
end
- if not skip_inner then
- for child in node:iter_children() do
- get_outline_lines(child)
- end
+ for child in node:iter_children() do
+ parse_node(child)
end
if is_outline then
- if not skip_inner and not vim.tbl_contains(off_side_rule_languages, ft) then
- local signature_end =
- vim.trim(vim.api.nvim_buf_get_text(bufnr, end_row, 0, end_row, end_col, {})[1])
+ if not vim.tbl_contains(OFF_SIDE_RULE_LANGUAGES, ft) then
+ local end_line = lines[end_row + 1]
+ local signature_end = vim.trim(end_line:sub(1, end_col))
table.insert(outline_lines, string.rep(' ', depth) .. signature_end)
end
depth = depth - 1
end
end
- get_outline_lines(root)
- local content = table.concat(outline_lines, '\n')
- if content == '' then
- return
+ parse_node(root)
+
+ if #outline_lines > 0 then
+ output.original = content
+ output.content = table.concat(outline_lines, '\n')
+ output.symbols = symbols
end
- return {
- content = table.concat(outline_lines, '\n'),
- filename = name,
- filetype = ft,
- }
+ return output
end
---- Get current git diff
----@param type string?
----@param bufnr number
-function M.gitdiff(type, bufnr)
- type = type or 'unstaged'
- local bufname = vim.api.nvim_buf_get_name(bufnr)
- local file_path = bufname:gsub('^%w+://', '')
- local dir = vim.fn.fnamemodify(file_path, ':h')
- if not dir or dir == '' then
+--- Get data for a file
+---@param filename string
+---@param filetype string
+---@return CopilotChat.context.embed?
+local function get_file(filename, filetype)
+ local modified = utils.file_mtime(filename)
+ if not modified then
return nil
end
- dir = dir:gsub('.git$', '')
- local cmd = 'git -C ' .. dir .. ' diff --no-color --no-ext-diff'
+ local cached = file_cache[filename]
+ if cached and cached.modified >= modified then
+ return cached.outline
+ end
- if type == 'staged' then
- cmd = cmd .. ' --staged'
+ local content = utils.read_file(filename)
+ if content then
+ local outline = build_outline(content, filename, filetype)
+ file_cache[filename] = {
+ outline = outline,
+ modified = modified,
+ }
+
+ return outline
end
- local handle = io.popen(cmd)
- if not handle then
+ return nil
+end
+
+--- Get list of all files in workspace
+---@param winnr number?
+---@param with_content boolean
+---@return table
+function M.files(winnr, with_content)
+ local cwd = utils.win_cwd(winnr)
+
+ notify.publish(notify.STATUS, 'Scanning files')
+
+ local files = utils.scan_dir(cwd, {
+ add_dirs = false,
+ respect_gitignore = true,
+ })
+
+ notify.publish(notify.STATUS, 'Reading files')
+
+ local out = {}
+
+ -- Read all files if we want content as well
+ if with_content then
+ async.util.scheduler()
+
+ files = vim.tbl_filter(
+ function(file)
+ return file.ft ~= nil
+ end,
+ vim.tbl_map(function(file)
+ return {
+ name = utils.filepath(file),
+ ft = utils.filetype(file),
+ }
+ end, files)
+ )
+
+ for _, file in ipairs(files) do
+ local file_data = get_file(file.name, file.ft)
+ if file_data then
+ table.insert(out, file_data)
+ end
+ end
+
+ return out
+ end
+
+ -- Create file list in chunks
+ local chunk_size = 100
+ for i = 1, #files, chunk_size do
+ local chunk = {}
+ for j = i, math.min(i + chunk_size - 1, #files) do
+ table.insert(chunk, files[j])
+ end
+
+ local chunk_number = math.floor(i / chunk_size)
+ local chunk_name = chunk_number == 0 and 'file_map' or 'file_map' .. tostring(chunk_number)
+
+ table.insert(out, {
+ content = table.concat(chunk, '\n'),
+ filename = chunk_name,
+ filetype = 'text',
+ })
+ end
+
+ return out
+end
+
+--- Get the content of a file
+---@param filename? string
+---@return CopilotChat.context.embed?
+function M.file(filename)
+ if not filename or filename == '' then
+ return nil
+ end
+
+ notify.publish(notify.STATUS, 'Reading file ' .. filename)
+
+ async.util.scheduler()
+ local ft = utils.filetype(filename)
+ if not ft then
+ return nil
+ end
+
+ return get_file(utils.filepath(filename), ft)
+end
+
+--- Get the content of a buffer
+---@param bufnr number
+---@return CopilotChat.context.embed?
+function M.buffer(bufnr)
+ async.util.scheduler()
+
+ if not utils.buf_valid(bufnr) then
return nil
end
- local result = handle:read('*a')
- handle:close()
- if not result or result == '' then
+ local content = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
+ if not content or #content == 0 then
return nil
end
+ return build_outline(
+ table.concat(content, '\n'),
+ utils.filepath(vim.api.nvim_buf_get_name(bufnr)),
+ vim.bo[bufnr].filetype
+ )
+end
+
+--- Get content of all buffers
+---@param buf_type string
+---@return table
+function M.buffers(buf_type)
+ async.util.scheduler()
+
+ return vim.tbl_map(
+ M.buffer,
+ vim.tbl_filter(function(b)
+ return utils.buf_valid(b)
+ and vim.fn.buflisted(b) == 1
+ and (buf_type == 'listed' or #vim.fn.win_findbuf(b) > 0)
+ end, vim.api.nvim_list_bufs())
+ )
+end
+
+--- Get the content of an URL
+---@param url string
+---@return CopilotChat.context.embed?
+function M.url(url)
+ if not url or url == '' then
+ return nil
+ end
+
+ local content = url_cache[url]
+ if not content then
+ notify.publish(notify.STATUS, 'Fetching ' .. url)
+
+ local ok, out = async.util.apcall(utils.system, { 'lynx', '-dump', url })
+ if ok and out and out.code == 0 then
+ -- Use lynx to fetch content
+ content = out.stdout
+ else
+ -- Fallback to curl if lynx fails
+ local response = utils.curl_get(url, { raw = { '-L' } })
+ if not response or not response.body then
+ return nil
+ end
+
+ content = vim.trim(response
+ .body
+ -- Remove script, style tags and their contents first
+ :gsub(
+ '',
+ ''
+ )
+ :gsub('', '')
+ -- Remove XML/CDATA in one go
+ :gsub('', '')
+ -- Remove all HTML tags (both opening and closing) in one go
+ :gsub(
+ '<%/?%w+[^>]*>',
+ ' '
+ )
+ -- Handle common HTML entities
+ :gsub('&(%w+);', {
+ nbsp = ' ',
+ lt = '<',
+ gt = '>',
+ amp = '&',
+ quot = '"',
+ })
+ -- Remove any remaining HTML entities (numeric or named)
+ :gsub('?%w+;', ''))
+ end
+
+ url_cache[url] = content
+ end
+
+ return {
+ content = content,
+ filename = url,
+ filetype = 'text',
+ }
+end
+
+--- Get current git diff
+---@param type string
+---@param winnr number
+---@return CopilotChat.context.embed?
+function M.gitdiff(type, winnr)
+ notify.publish(notify.STATUS, 'Fetching git diff')
+
+ local cwd = utils.win_cwd(winnr)
+ local cmd = {
+ 'git',
+ '-C',
+ cwd,
+ 'diff',
+ '--no-color',
+ '--no-ext-diff',
+ }
+
+ if type == 'staged' then
+ table.insert(cmd, '--staged')
+ end
+
+ local out = utils.system(cmd)
+
return {
- content = result,
+ content = out.stdout,
filename = 'git_diff_' .. type,
filetype = 'diff',
}
end
----@class CopilotChat.context.find_for_query.opts
----@field embeddings table
----@field prompt string
----@field selection string?
----@field filename string
----@field filetype string
+--- Return contents of specified register
+---@param register string
+---@return CopilotChat.context.embed?
+function M.register(register)
+ local lines = vim.fn.getreg(register)
+ if not lines or lines == '' then
+ return nil
+ end
+
+ return {
+ content = lines,
+ filename = 'vim_register_' .. register,
+ filetype = '',
+ }
+end
--- Filter embeddings based on the query
---@param copilot CopilotChat.Copilot
----@param opts CopilotChat.context.find_for_query.opts
----@return table
-function M.filter_embeddings(copilot, opts)
- local embeddings = opts.embeddings
- local prompt = opts.prompt
- local selection = opts.selection
- local filename = opts.filename
- local filetype = opts.filetype
-
- local out = copilot:embed(embeddings)
- if #out == 0 then
- return {}
+---@param prompt string
+---@param embeddings table
+---@return table
+function M.filter_embeddings(copilot, prompt, embeddings)
+ -- If we dont need to embed anything, just return directly
+ if #embeddings < MULTI_FILE_THRESHOLD then
+ return embeddings
end
- -- If selection is too big, truncate it
- if selection then
- local lines = vim.split(selection, '\n')
- selection = #lines > selection_threshold
- and table.concat(vim.list_slice(lines, 1, selection_threshold), '\n')
- or selection
+ -- Rank embeddings by symbols
+ embeddings = data_ranked_by_symbols(prompt, embeddings, TOP_SYMBOLS)
+ log.debug('Ranked data:', #embeddings)
+ for i, item in ipairs(embeddings) do
+ log.debug(string.format('%s: %s - %s', i, item.score, item.filename))
end
- log.debug(string.format('Got %s embeddings', #out))
-
- local query_out = copilot:embed({
- {
- prompt = prompt,
- content = selection,
- filename = filename,
- filetype = filetype,
- },
+ -- Add prompt so it can be embedded
+ table.insert(embeddings, {
+ content = prompt,
+ filename = 'prompt',
+ filetype = 'raw',
})
- local query = query_out[1]
- if not query then
- return {}
- end
-
- local data = data_ranked_by_relatedness(query, out, 20)
+ -- Get embeddings from all items
+ embeddings = copilot:embed(embeddings)
- log.debug('Prompt:', query.prompt)
- log.debug('Content:', query.content)
- log.debug('Ranked data:', #data)
- for i, item in ipairs(data) do
+ -- Rate embeddings by relatedness to the query
+ local embedded_query = table.remove(embeddings, #embeddings)
+ log.debug('Embedded query:', embedded_query.content)
+ embeddings = data_ranked_by_relatedness(embedded_query, embeddings, TOP_RELATED)
+ log.debug('Ranked embeddings:', #embeddings)
+ for i, item in ipairs(embeddings) do
log.debug(string.format('%s: %s - %s', i, item.score, item.filename))
end
- return data
+ -- Return embeddings with original content
+ return vim.tbl_map(function(item)
+ return vim.tbl_extend('force', item, { content = item.original or item.content })
+ end, embeddings)
end
return M
diff --git a/lua/CopilotChat/copilot.lua b/lua/CopilotChat/copilot.lua
index 7d4254b9..761aa6c5 100644
--- a/lua/CopilotChat/copilot.lua
+++ b/lua/CopilotChat/copilot.lua
@@ -1,47 +1,30 @@
----@class CopilotChat.copilot.embed
----@field filename string
----@field filetype string
----@field prompt string?
----@field content string?
-
---@class CopilotChat.copilot.ask.opts
----@field selection CopilotChat.config.selection?
----@field embeddings table?
----@field filename string?
----@field filetype string?
----@field start_row number?
----@field end_row number?
+---@field selection CopilotChat.select.selection?
+---@field embeddings table?
---@field system_prompt string?
---@field model string?
---@field agent string?
---@field temperature number?
+---@field no_history boolean?
---@field on_progress nil|fun(response: string):nil
----@class CopilotChat.copilot.embed.opts
----@field model string?
----@field chunk_size number?
-
----@class CopilotChat.Copilot
----@field ask fun(self: CopilotChat.Copilot, prompt: string, opts: CopilotChat.copilot.ask.opts):string,number,number
----@field embed fun(self: CopilotChat.Copilot, inputs: table, opts: CopilotChat.copilot.embed.opts?):table
----@field stop fun(self: CopilotChat.Copilot):boolean
----@field reset fun(self: CopilotChat.Copilot):boolean
----@field save fun(self: CopilotChat.Copilot, name: string, path: string):nil
----@field load fun(self: CopilotChat.Copilot, name: string, path: string):table
----@field running fun(self: CopilotChat.Copilot):boolean
----@field list_models fun(self: CopilotChat.Copilot):table
----@field list_agents fun(self: CopilotChat.Copilot):table
-
-local async = require('plenary.async')
local log = require('plenary.log')
-local curl = require('plenary.curl')
local prompts = require('CopilotChat.prompts')
local tiktoken = require('CopilotChat.tiktoken')
+local notify = require('CopilotChat.notify')
local utils = require('CopilotChat.utils')
local class = utils.class
local temp_file = utils.temp_file
-local timeout = 30000
-local version_headers = {
+
+--- Constants
+local CONTEXT_FORMAT = '[#file:%s](#file:%s-context)'
+local LINE_CHARACTERS = 100
+local BIG_FILE_THRESHOLD = 2000 * LINE_CHARACTERS
+local BIG_EMBED_THRESHOLD = 200 * LINE_CHARACTERS
+local EMBED_MODEL = 'text-embedding-3-small'
+local TRUNCATED = '... (truncated)'
+local TIMEOUT = 30000
+local VERSION_HEADERS = {
['editor-version'] = 'Neovim/'
.. vim.version().major
.. '.'
@@ -57,71 +40,8 @@ local version_headers = {
-- ['x-github-api-version'] = '2023-07-07',
}
-local curl_get = async.wrap(function(url, opts, callback)
- opts = vim.tbl_deep_extend('force', opts, {
- callback = callback,
- on_error = function(err)
- err = err and err.stderr or vim.inspect(err)
- callback(nil, err)
- end,
- })
- curl.get(url, opts)
-end, 3)
-
-local curl_post = async.wrap(function(url, opts, callback)
- opts = vim.tbl_deep_extend('force', opts, {
- callback = callback,
- on_error = function(err)
- err = err and err.stderr or vim.inspect(err)
- callback(nil, err)
- end,
- })
- curl.post(url, opts)
-end, 3)
-
-local tiktoken_load = async.wrap(function(tokenizer, callback)
- tiktoken.load(tokenizer, callback)
-end, 2)
-
-local function uuid()
- local template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
- return (
- string.gsub(template, '[xy]', function(c)
- local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb)
- return string.format('%x', v)
- end)
- )
-end
-
-local function machine_id()
- local length = 65
- local hex_chars = '0123456789abcdef'
- local hex = ''
- for _ = 1, length do
- local index = math.random(1, #hex_chars)
- hex = hex .. hex_chars:sub(index, index)
- end
- return hex
-end
-
-local function find_config_path()
- local config = vim.fn.expand('$XDG_CONFIG_HOME')
- if config and vim.fn.isdirectory(config) > 0 then
- return config
- end
- if vim.fn.has('win32') > 0 then
- config = vim.fn.expand('$LOCALAPPDATA')
- if not config or vim.fn.isdirectory(config) == 0 then
- config = vim.fn.expand('$HOME/AppData/Local')
- end
- else
- config = vim.fn.expand('$HOME/.config')
- end
- if config and vim.fn.isdirectory(config) > 0 then
- return config
- end
-end
-
+--- Get the github oauth cached token
+---@return string|nil
local function get_cached_token()
-- loading token from the environment only in GitHub Codespaces
local token = os.getenv('GITHUB_TOKEN')
@@ -131,7 +51,7 @@ local function get_cached_token()
end
-- loading token from the file
- local config_path = find_config_path()
+ local config_path = utils.config_path()
if not config_path then
return nil
end
@@ -156,20 +76,43 @@ local function get_cached_token()
return nil
end
-local function generate_line_numbers(content, start_row)
+--- Generate content block with line numbers, truncating if necessary
+---@param content string: The content
+---@param threshold number: The threshold for truncation
+---@param start_line number|nil: The starting line number
+---@return string
+local function generate_content_block(content, threshold, start_line)
local lines = vim.split(content, '\n')
- local total_lines = #lines
- local max_length = #tostring(total_lines)
+ local total_chars = 0
+
for i, line in ipairs(lines) do
- local formatted_line_number = string.format('%' .. max_length .. 'd', i - 1 + (start_row or 1))
- lines[i] = formatted_line_number .. ': ' .. line
+ total_chars = total_chars + #line
+ if total_chars > threshold then
+ lines = vim.list_slice(lines, 1, i)
+ table.insert(lines, TRUNCATED)
+ break
+ end
+ end
+
+ if start_line ~= -1 then
+ local total_lines = #lines
+ local max_length = #tostring(total_lines)
+ for i, line in ipairs(lines) do
+ local formatted_line_number =
+ string.format('%' .. max_length .. 'd', i - 1 + (start_line or 1))
+ lines[i] = formatted_line_number .. ': ' .. line
+ end
end
- content = table.concat(lines, '\n')
- return content
+
+ return table.concat(lines, '\n')
end
-local function generate_selection_messages(filename, filetype, selection)
- local content = selection.lines
+--- Generate messages for the given selection
+--- @param selection CopilotChat.select.selection
+local function generate_selection_messages(selection)
+ local filename = selection.filename or 'unknown'
+ local filetype = selection.filetype or 'text'
+ local content = selection.content
if not content or content == '' then
return {}
@@ -177,62 +120,59 @@ local function generate_selection_messages(filename, filetype, selection)
local out = string.format('# FILE:%s CONTEXT\n', filename:upper())
out = out .. "User's active selection:\n"
- if selection.start_row and selection.start_row > 0 then
+ if selection.start_line and selection.end_line then
out = out
.. string.format(
'Excerpt from %s, lines %s to %s:\n',
filename,
- selection.start_row,
- selection.end_row
+ selection.start_line,
+ selection.end_line
)
end
out = out
.. string.format(
'```%s\n%s\n```',
filetype,
- generate_line_numbers(content, selection.start_row)
+ generate_content_block(content, BIG_FILE_THRESHOLD, selection.start_line)
)
if selection.diagnostics then
local diagnostics = {}
for _, diagnostic in ipairs(selection.diagnostics) do
- local start_row = diagnostic.start_row
- local end_row = diagnostic.end_row
- if start_row == end_row then
- table.insert(
- diagnostics,
- string.format('%s line=%d: %s', diagnostic.severity, start_row, diagnostic.message)
- )
- else
- table.insert(
- diagnostics,
- string.format(
- '%s line=%d-%d: %s',
- diagnostic.severity,
- start_row,
- end_row,
- diagnostic.message
- )
+ table.insert(
+ diagnostics,
+ string.format(
+ '%s line=%d-%d: %s',
+ diagnostic.severity,
+ diagnostic.start_line,
+ diagnostic.end_line,
+ diagnostic.content
)
- end
+ )
end
out = out
- .. string.format('\n# FILE:%s DIAGNOSTICS:\n%s', filename, table.concat(diagnostics, '\n'))
+ .. string.format(
+ "\nDiagnostics in user's active selection:\n%s",
+ table.concat(diagnostics, '\n')
+ )
end
return {
{
+ context = string.format(CONTEXT_FORMAT, filename, filename),
content = out,
role = 'user',
},
}
end
+--- Generate messages for the given embeddings
+--- @param embeddings table
local function generate_embeddings_messages(embeddings)
local files = {}
for _, embedding in ipairs(embeddings) do
- local filename = embedding.filename
+ local filename = embedding.filename or 'unknown'
if not files[filename] then
files[filename] = {}
end
@@ -242,17 +182,22 @@ local function generate_embeddings_messages(embeddings)
local out = {}
for filename, group in pairs(files) do
+ local filetype = group[1].filetype or 'text'
table.insert(out, {
+ context = string.format(CONTEXT_FORMAT, filename, filename),
content = string.format(
'# FILE:%s CONTEXT\n```%s\n%s\n```',
filename:upper(),
- group[1].filetype,
- generate_line_numbers(table.concat(
- vim.tbl_map(function(e)
- return vim.trim(e.content)
- end, group),
- '\n'
- ))
+ filetype,
+ generate_content_block(
+ table.concat(
+ vim.tbl_map(function(e)
+ return vim.trim(e.content)
+ end, group),
+ '\n'
+ ),
+ BIG_FILE_THRESHOLD
+ )
),
role = 'user',
})
@@ -271,8 +216,10 @@ local function generate_ask_request(
max_output_tokens,
stream
)
+ local is_o1 = vim.startswith(model, 'o1')
local messages = {}
- local system_role = stream and 'system' or 'user'
+ local system_role = is_o1 and 'user' or 'system'
+ local contexts = {}
if system_prompt ~= '' then
table.insert(messages, {
@@ -282,13 +229,24 @@ local function generate_ask_request(
end
for _, message in ipairs(generated_messages) do
- table.insert(messages, message)
+ table.insert(messages, {
+ content = message.content,
+ role = message.role,
+ })
+
+ if message.context then
+ contexts[message.context] = true
+ end
end
for _, message in ipairs(history) do
table.insert(messages, message)
end
+ if not vim.tbl_isempty(contexts) then
+ prompt = table.concat(vim.tbl_keys(contexts), '\n') .. '\n' .. prompt
+ end
+
table.insert(messages, {
content = prompt,
role = 'user',
@@ -298,14 +256,14 @@ local function generate_ask_request(
messages = messages,
model = model,
stream = stream,
+ n = 1,
}
if max_output_tokens then
out.max_tokens = max_output_tokens
end
- if stream then
- out.n = 1
+ if not is_o1 then
out.temperature = temperature
out.top_p = 1
end
@@ -313,93 +271,99 @@ local function generate_ask_request(
return out
end
-local function generate_embedding_request(inputs, model)
+local function generate_embedding_request(inputs, model, threshold)
return {
- input = vim.tbl_map(function(input)
- local out = ''
- if input.prompt then
- out = input.prompt .. '\n'
- end
- if input.content then
- out = out
- .. string.format(
- '# FILE:%s CONTEXT\n```%s\n%s\n```',
- input.filename:upper(),
- input.filetype,
- input.content
- )
+ dimensions = 512,
+ input = vim.tbl_map(function(embedding)
+ local content = generate_content_block(embedding.content, threshold, -1)
+ if embedding.filetype == 'raw' then
+ return content
+ else
+ return string.format(
+ 'File: `%s`\n```%s\n%s\n```',
+ embedding.filename,
+ embedding.filetype,
+ content
+ )
end
- return out
end, inputs),
model = model,
}
end
-local function count_history_tokens(history)
- local count = 0
- for _, msg in ipairs(history) do
- count = count + tiktoken.count(msg.content)
- end
- return count
-end
-
+---@class CopilotChat.Copilot : Class
+---@field history table
+---@field embedding_cache table
+---@field policies table
+---@field models table?
+---@field agents table?
+---@field current_job string?
+---@field github_token string?
+---@field token table?
+---@field sessionid string?
+---@field machineid string
+---@field request_args table
local Copilot = class(function(self, proxy, allow_insecure)
self.history = {}
- self.github_token = nil
- self.token = nil
- self.sessionid = nil
- self.machineid = machine_id()
+ self.embedding_cache = {}
+ self.policies = {}
self.models = nil
self.agents = nil
- self.claude_enabled = false
+
self.current_job = nil
+ self.github_token = nil
+ self.token = nil
+ self.sessionid = nil
+ self.machineid = utils.machine_id()
+ self.github_token = get_cached_token()
+
self.request_args = {
- timeout = timeout,
+ timeout = TIMEOUT,
proxy = proxy,
insecure = allow_insecure,
raw = {
+ -- Properly fail on errors
+ '--fail-with-body',
-- Retry failed requests twice
'--retry',
'2',
-- Wait 1 second between retries
'--retry-delay',
'1',
- -- Maximum time for the request
- '--max-time',
- math.floor(timeout * 2 / 1000),
- -- Timeout for initial connection
+ -- Keep connections alive for better performance
+ '--keepalive-time',
+ '60',
+ -- Disable compression (since responses are already streamed efficiently)
+ '--no-compressed',
+ -- Connect timeout of 10 seconds
'--connect-timeout',
'10',
- '--no-keepalive', -- Don't reuse connections
- '--tcp-nodelay', -- Disable Nagle's algorithm for faster streaming
- '--no-buffer', -- Disable output buffering for streaming
+ -- Streaming optimizations
+ '--tcp-nodelay',
+ '--no-buffer',
},
}
end)
+--- Authenticate with GitHub and get the required headers
+---@return table
function Copilot:authenticate()
if not self.github_token then
- self.github_token = get_cached_token()
- if not self.github_token then
- error(
- 'No GitHub token found, please use `:Copilot auth` to set it up from copilot.lua or `:Copilot setup` for copilot.vim'
- )
- end
+ error(
+ 'No GitHub token found, please use `:Copilot auth` to set it up from copilot.lua or `:Copilot setup` for copilot.vim'
+ )
end
if
not self.token or (self.token.expires_at and self.token.expires_at <= math.floor(os.time()))
then
- local sessionid = uuid() .. tostring(math.floor(os.time() * 1000))
- local headers = {
+ local sessionid = utils.uuid() .. tostring(math.floor(os.time() * 1000))
+ local headers = vim.tbl_extend('force', {
['authorization'] = 'token ' .. self.github_token,
['accept'] = 'application/json',
- }
- for key, value in pairs(version_headers) do
- headers[key] = value
- end
+ }, VERSION_HEADERS)
- local response, err = curl_get(
+ local response, err = utils.curl_get(
'https://api.github.com/copilot_internal/v2/token',
vim.tbl_extend('force', self.request_args, {
headers = headers,
@@ -420,7 +384,7 @@ function Copilot:authenticate()
local headers = {
['authorization'] = 'Bearer ' .. self.token.token,
- ['x-request-id'] = uuid(),
+ ['x-request-id'] = utils.uuid(),
['vscode-sessionid'] = self.sessionid,
['vscode-machineid'] = self.machineid,
['copilot-integration-id'] = 'vscode-chat',
@@ -428,19 +392,23 @@ function Copilot:authenticate()
['openai-intent'] = 'conversation-panel',
['content-type'] = 'application/json',
}
- for key, value in pairs(version_headers) do
+ for key, value in pairs(VERSION_HEADERS) do
headers[key] = value
end
return headers
end
+--- Fetch models from the Copilot API
+---@return table
function Copilot:fetch_models()
if self.models then
return self.models
end
- local response, err = curl_get(
+ notify.publish(notify.STATUS, 'Fetching models')
+
+ local response, err = utils.curl_get(
'https://api.githubcopilot.com/models',
vim.tbl_extend('force', self.request_args, {
headers = self:authenticate(),
@@ -459,22 +427,30 @@ function Copilot:fetch_models()
local models = vim.json.decode(response.body)['data']
local out = {}
for _, model in ipairs(models) do
+ if not model['policy'] or model['policy']['state'] == 'enabled' then
+ self.policies[model['id']] = true
+ end
+
if model['capabilities']['type'] == 'chat' then
out[model['id']] = model
end
end
- log.info('Models fetched')
+ log.trace(models)
self.models = out
return out
end
+--- Fetch agents from the Copilot API
+---@return table
function Copilot:fetch_agents()
if self.agents then
return self.agents
end
- local response, err = curl_get(
+ notify.publish(notify.STATUS, 'Fetching agents')
+
+ local response, err = utils.curl_get(
'https://api.githubcopilot.com/agents',
vim.tbl_extend('force', self.request_args, {
headers = self:authenticate(),
@@ -497,47 +473,34 @@ function Copilot:fetch_agents()
out['copilot'] = { name = 'Copilot', default = true, description = 'Default noop agent' }
- log.info('Agents fetched')
+ log.trace(agents)
self.agents = out
return out
end
-function Copilot:enable_claude()
- if self.claude_enabled then
- return true
+--- Enable policy for the given model if required
+---@param model string: The model to enable policy for
+function Copilot:enable_policy(model)
+ if self.policies[model] then
+ return
end
- local business_check = 'cannot enable policy inline for business users'
- local business_msg =
- 'Claude is probably enabled (for business users needs to be enabled manually).'
+ notify.publish(notify.STATUS, 'Enabling ' .. model .. ' policy')
- local response, err = curl_post(
- 'https://api.githubcopilot.com/models/claude-3.5-sonnet/policy',
+ local response, err = utils.curl_post(
+ 'https://api.githubcopilot.com/models/' .. model .. '/policy',
vim.tbl_extend('force', self.request_args, {
headers = self:authenticate(),
body = vim.json.encode({ state = 'enabled' }),
})
)
- if err then
- error(err)
- end
-
- -- Handle business user case
- if response.status ~= 200 and string.find(tostring(response.body), business_check) then
- self.claude_enabled = true
- log.info(business_msg)
- return true
- end
+ self.policies[model] = true
- -- Handle errors
- if response.status ~= 200 then
- error('Failed to enable Claude: ' .. tostring(response.status))
+ if err or response.status ~= 200 then
+ log.warn('Failed to enable policy for ', model, ': ', (err or response.body))
+ return
end
-
- self.claude_enabled = true
- log.info('Claude enabled')
- return true
end
--- Ask a question to Copilot
@@ -547,27 +510,25 @@ function Copilot:ask(prompt, opts)
opts = opts or {}
prompt = vim.trim(prompt)
local embeddings = opts.embeddings or {}
- local filename = opts.filename or ''
- local filetype = opts.filetype or ''
local selection = opts.selection or {}
local system_prompt = vim.trim(opts.system_prompt or prompts.COPILOT_INSTRUCTIONS)
local model = opts.model or 'gpt-4o-2024-05-13'
local agent = opts.agent or 'copilot'
local temperature = opts.temperature or 0.1
+ local no_history = opts.no_history or false
local on_progress = opts.on_progress
- local job_id = uuid()
+ local job_id = utils.uuid()
self.current_job = job_id
- log.trace('System prompt: ' .. system_prompt)
- log.trace('Selection: ' .. (selection.lines or ''))
- log.debug('Prompt: ' .. prompt)
- log.debug('Embeddings: ' .. #embeddings)
- log.debug('Filename: ' .. filename)
- log.debug('Filetype: ' .. filetype)
- log.debug('Model: ' .. model)
- log.debug('Agent: ' .. agent)
- log.debug('Temperature: ' .. temperature)
+ log.trace('System prompt: ', system_prompt)
+ log.trace('Selection: ', selection.content)
+ log.debug('Prompt: ', prompt)
+ log.debug('Embeddings: ', #embeddings)
+ log.debug('Model: ', model)
+ log.debug('Agent: ', agent)
+ log.debug('Temperature: ', temperature)
+ local history = no_history and {} or self.history
local models = self:fetch_models()
local agents = self:fetch_agents()
local agent_config = agents[agent]
@@ -583,12 +544,12 @@ function Copilot:ask(prompt, opts)
local max_tokens = capabilities.limits.max_prompt_tokens -- FIXME: Is max_prompt_tokens the right limit?
local max_output_tokens = capabilities.limits.max_output_tokens
local tokenizer = capabilities.tokenizer
- log.debug('Max tokens: ' .. max_tokens)
- log.debug('Tokenizer: ' .. tokenizer)
- tiktoken_load(tokenizer)
+ log.debug('Max tokens: ', max_tokens)
+ log.debug('Tokenizer: ', tokenizer)
+ tiktoken.load(tokenizer)
local generated_messages = {}
- local selection_messages = generate_selection_messages(filename, filetype, selection)
+ local selection_messages = generate_selection_messages(selection)
local embeddings_messages = generate_embeddings_messages(embeddings)
local generated_tokens = 0
for _, message in ipairs(selection_messages) do
@@ -601,28 +562,28 @@ function Copilot:ask(prompt, opts)
local system_tokens = tiktoken.count(system_prompt)
local required_tokens = prompt_tokens + system_tokens + generated_tokens
- -- Reserve space for first embedding if its smaller than half of max tokens
- local reserved_tokens = 0
- if #embeddings_messages > 0 then
- local file_tokens = tiktoken.count(embeddings_messages[1].content)
- if file_tokens < max_tokens / 2 then
- reserved_tokens = file_tokens
- end
- end
+ -- Reserve space for first embedding
+ local reserved_tokens = #embeddings_messages > 0
+ and tiktoken.count(embeddings_messages[1].content)
+ or 0
-- Calculate how many tokens we can use for history
local history_limit = max_tokens - required_tokens - reserved_tokens
- local history_tokens = count_history_tokens(self.history)
+ local history_tokens = 0
+ for _, msg in ipairs(history) do
+ history_tokens = history_tokens + tiktoken.count(msg.content)
+ end
-- If we're over history limit, truncate history from the beginning
- while history_tokens > history_limit and #self.history > 0 do
- local removed = table.remove(self.history, 1)
+ while history_tokens > history_limit and #history > 0 do
+ local removed = table.remove(history, 1)
history_tokens = history_tokens - tiktoken.count(removed.content)
end
- -- Now add as many files as possible with remaining token budget
+ -- Now add as many files as possible with remaining token budget (back to front)
local remaining_tokens = max_tokens - required_tokens - history_tokens
- for _, message in ipairs(embeddings_messages) do
+ for i = #embeddings_messages, 1, -1 do
+ local message = embeddings_messages[i]
local tokens = tiktoken.count(message.content)
if remaining_tokens - tokens >= 0 then
remaining_tokens = remaining_tokens - tokens
@@ -632,16 +593,6 @@ function Copilot:ask(prompt, opts)
end
end
- -- Prepend links to embeddings to the prompt
- local embeddings_prompt = ''
- for _, embedding in ipairs(embeddings) do
- embeddings_prompt = embeddings_prompt
- .. string.format('[#file:%s](#file:%s-context)\n', embedding.filename, embedding.filename)
- end
- if embeddings_prompt ~= '' then
- prompt = embeddings_prompt .. '\n' .. prompt
- end
-
local last_message = nil
local errored = false
local finished = false
@@ -658,31 +609,12 @@ function Copilot:ask(prompt, opts)
job:shutdown(0)
end
- local function stream_func(err, line, job)
- if not line or errored or finished then
- return
- end
-
- if self.current_job ~= job_id then
- finish_stream(nil, job)
- return
- end
-
- if err or vim.startswith(line, '{"error"') then
- finish_stream('Failed to get response: ' .. (err and vim.inspect(err) or line), job)
- return
- end
-
- if not vim.startswith(line, 'data: ') then
+ local function parse_line(line)
+ if not line then
return
end
- line = line:gsub('^%s*data:%s*', ''):gsub('%s*$', '')
-
- if line == '[DONE]' then
- finish_stream(nil, job)
- return
- end
+ notify.publish(notify.STATUS, '')
local ok, content = pcall(vim.json.decode, line, {
luanil = {
@@ -692,8 +624,7 @@ function Copilot:ask(prompt, opts)
})
if not ok then
- finish_stream('Failed to parse response: ' .. vim.inspect(content) .. '\n' .. line, job)
- return
+ return content
end
if content.copilot_references then
@@ -731,36 +662,76 @@ function Copilot:ask(prompt, opts)
full_response = full_response .. content
end
+ local function parse_stream_line(line, job)
+ line = vim.trim(line)
+ if not vim.startswith(line, 'data: ') then
+ return
+ end
+ line = line:gsub('^data:%s*', '')
+
+ if line == '[DONE]' then
+ if job then
+ finish_stream(nil, job)
+ end
+ return
+ end
+
+ local err = parse_line(line)
+ if err and job then
+ finish_stream('Failed to parse response: ' .. utils.make_string(err) .. '\n' .. line, job)
+ end
+ end
+
+ local function stream_func(err, line, job)
+ if not line or errored or finished then
+ return
+ end
+
+ if self.current_job ~= job_id then
+ finish_stream(nil, job)
+ return
+ end
+
+ if err then
+ finish_stream('Failed to get response: ' .. utils.make_string(err and err or line), job)
+ return
+ end
+
+ parse_stream_line(line, job)
+ end
+
+ local is_stream = not vim.startswith(model, 'o1')
local body = vim.json.encode(
generate_ask_request(
- self.history,
+ history,
prompt,
system_prompt,
generated_messages,
model,
temperature,
max_output_tokens,
- not vim.startswith(model, 'o1')
+ is_stream
)
)
- if vim.startswith(model, 'claude') then
- self:enable_claude()
- end
-
+ self:enable_policy(model)
local url = 'https://api.githubcopilot.com/chat/completions'
if not agent_config.default then
url = 'https://api.githubcopilot.com/agents/' .. agent .. '?chat'
end
- local response, err = curl_post(
- url,
- vim.tbl_extend('force', self.request_args, {
- headers = self:authenticate(),
- body = temp_file(body),
- stream = stream_func,
- })
- )
+ local args = vim.tbl_extend('force', self.request_args, {
+ headers = self:authenticate(),
+ body = temp_file(body),
+ })
+
+ if is_stream then
+ args.stream = stream_func
+ end
+
+ notify.publish(notify.STATUS, 'Thinking')
+
+ local response, err = utils.curl_post(url, args)
if self.current_job ~= job_id then
return nil, nil, nil
@@ -778,6 +749,10 @@ function Copilot:ask(prompt, opts)
return
end
+ log.debug('Response status: ', response.status)
+ log.debug('Response body: ', response.body)
+ log.debug('Response headers: ', response.headers)
+
if response.status ~= 200 then
if response.status == 401 then
local ok, content = pcall(vim.json.decode, response.body, {
@@ -807,6 +782,16 @@ function Copilot:ask(prompt, opts)
return
end
+ if is_stream then
+ if full_response == '' then
+ for _, line in ipairs(vim.split(response.body, '\n')) do
+ parse_stream_line(line)
+ end
+ end
+ else
+ parse_line(response.body)
+ end
+
if full_response == '' then
error('Failed to get response: empty response')
return
@@ -820,26 +805,31 @@ function Copilot:ask(prompt, opts)
end
end
- log.trace('Full response: ' .. full_response)
- log.debug('Last message: ' .. vim.inspect(last_message))
+ log.trace('Full response: ', full_response)
+ log.debug('Last message: ', last_message)
- table.insert(self.history, {
+ table.insert(history, {
content = prompt,
role = 'user',
})
- table.insert(self.history, {
+ table.insert(history, {
content = full_response,
role = 'assistant',
})
+ if not no_history then
+ log.debug('History size increased to ' .. #history)
+ self.history = history
+ end
+
return full_response,
last_message and last_message.usage and last_message.usage.total_tokens,
max_tokens
end
--- List available models
----@return table
+---@return table
function Copilot:list_models()
local models = self:fetch_models()
@@ -862,7 +852,7 @@ function Copilot:list_models()
end
--- List available agents
----@return table
+---@return table
function Copilot:list_agents()
local agents = self:fetch_agents()
@@ -877,66 +867,109 @@ function Copilot:list_agents()
end
--- Generate embeddings for the given inputs
----@param inputs table: The inputs to embed
----@param opts CopilotChat.copilot.embed.opts: Options for the request
-function Copilot:embed(inputs, opts)
- opts = opts or {}
- local model = opts.model or 'copilot-text-embedding-ada-002'
- local chunk_size = opts.chunk_size or 15
-
+---@param inputs table: The inputs to embed
+---@return table
+function Copilot:embed(inputs)
if not inputs or #inputs == 0 then
return {}
end
- local out = {}
+ notify.publish(notify.STATUS, 'Generating embeddings for ' .. #inputs .. ' inputs')
- for i = 1, #inputs, chunk_size do
- local chunk = vim.list_slice(inputs, i, i + chunk_size - 1)
- local body = vim.json.encode(generate_embedding_request(chunk, model))
- local response, err = curl_post(
- 'https://api.githubcopilot.com/embeddings',
- vim.tbl_extend('force', self.request_args, {
- headers = self:authenticate(),
- body = temp_file(body),
- })
- )
+ -- Initialize essentials
+ local model = EMBED_MODEL
+ local to_process = {}
+ local results = {}
+ local initial_chunk_size = 10
- if err then
- error(err)
- return
- end
+ -- Process each input, using cache when possible
+ for _, input in ipairs(inputs) do
+ input.filename = input.filename or 'unknown'
+ input.filetype = input.filetype or 'text'
- if not response then
- error('Failed to get response')
- return
+ if input.content then
+ local cache_key = input.filename .. utils.quick_hash(input.content)
+ if self.embedding_cache[cache_key] then
+ table.insert(results, self.embedding_cache[cache_key])
+ else
+ table.insert(to_process, input)
+ end
end
+ end
- if response.status ~= 200 then
- error('Failed to get response: ' .. tostring(response.status) .. '\n' .. response.body)
- return
+ -- Process inputs in batches with adaptive chunk size
+ while #to_process > 0 do
+ local chunk_size = initial_chunk_size -- Reset chunk size for each new batch
+ local threshold = BIG_EMBED_THRESHOLD -- Reset threshold for each new batch
+
+ -- Take next chunk
+ local batch = {}
+ for _ = 1, math.min(chunk_size, #to_process) do
+ table.insert(batch, table.remove(to_process, 1))
end
- local ok, content = pcall(vim.json.decode, response.body, {
- luanil = {
- object = true,
- array = true,
- },
- })
+ -- Try to get embeddings for batch
+ local success = false
+ local attempts = 0
+ while not success and attempts < 5 do -- Limit total attempts to 5
+ local body = vim.json.encode(generate_embedding_request(batch, model, threshold))
+ local response, err = utils.curl_post(
+ 'https://api.githubcopilot.com/embeddings',
+ vim.tbl_extend('force', self.request_args, {
+ headers = self:authenticate(),
+ body = temp_file(body),
+ })
+ )
- if not ok then
- error('Failed to parse response: ' .. vim.inspect(content) .. '\n' .. response.body)
- return
+ if err or not response or response.status ~= 200 then
+ attempts = attempts + 1
+ -- If we have few items and the request failed, try reducing threshold first
+ if #batch <= 5 then
+ threshold = math.max(5 * LINE_CHARACTERS, math.floor(threshold / 2))
+ log.debug(string.format('Reducing threshold to %d and retrying...', threshold))
+ else
+ -- Otherwise reduce batch size first
+ chunk_size = math.max(1, math.floor(chunk_size / 2))
+ -- Put items back in to_process
+ for i = #batch, 1, -1 do
+ table.insert(to_process, 1, table.remove(batch, i))
+ end
+ -- Take new smaller batch
+ batch = {}
+ for _ = 1, math.min(chunk_size, #to_process) do
+ table.insert(batch, table.remove(to_process, 1))
+ end
+ log.debug(string.format('Reducing batch size to %d and retrying...', chunk_size))
+ end
+ else
+ success = true
+
+ -- Process and cache results
+ local ok, content = pcall(vim.json.decode, response.body)
+ if not ok then
+ error('Failed to parse embedding response: ' .. response.body)
+ end
+
+ for _, embedding in ipairs(content.data) do
+ local result = vim.tbl_extend('keep', batch[embedding.index + 1], embedding)
+ table.insert(results, result)
+
+ local cache_key = result.filename .. utils.quick_hash(result.content)
+ self.embedding_cache[cache_key] = result
+ end
+ end
end
- for _, embedding in ipairs(content.data) do
- table.insert(out, vim.tbl_extend('keep', chunk[embedding.index + 1], embedding))
+ if not success then
+ error('Failed to process embeddings after multiple attempts')
end
end
- return out
+ return results
end
--- Stop the running job
+---@return boolean
function Copilot:stop()
if self.current_job ~= nil then
self.current_job = nil
@@ -947,9 +980,11 @@ function Copilot:stop()
end
--- Reset the history and stop any running job
+---@return boolean
function Copilot:reset()
local stopped = self:stop()
self.history = {}
+ self.embedding_cache = {}
return stopped
end
diff --git a/lua/CopilotChat/debuginfo.lua b/lua/CopilotChat/debuginfo.lua
deleted file mode 100644
index ec10daad..00000000
--- a/lua/CopilotChat/debuginfo.lua
+++ /dev/null
@@ -1,81 +0,0 @@
-local log = require('plenary.log')
-local utils = require('CopilotChat.utils')
-local context = require('CopilotChat.context')
-local M = {}
-
-function M.open()
- local lines = {
- 'If you are facing issues, run `:checkhealth CopilotChat` and share the output.',
- '',
- 'Log file path:',
- '`' .. log.logfile .. '`',
- '',
- 'Temp directory:',
- '`' .. vim.fn.fnamemodify(os.tmpname(), ':h') .. '`',
- '',
- 'Data directory:',
- '`' .. vim.fn.stdpath('data') .. '`',
- '',
- }
-
- local outline = context.outline(vim.api.nvim_get_current_buf())
- if outline then
- table.insert(lines, 'Current buffer outline:')
- table.insert(lines, '`' .. outline.filename .. '`')
- table.insert(lines, '```' .. outline.filetype)
- local outline_lines = vim.split(outline.content, '\n')
- for _, line in ipairs(outline_lines) do
- table.insert(lines, line)
- end
- table.insert(lines, '```')
- end
-
- local files = context.files()
- if files then
- table.insert(lines, 'Current workspace file map:')
- table.insert(lines, '```text')
- for _, file in ipairs(files) do
- for _, line in ipairs(vim.split(file.content, '\n')) do
- table.insert(lines, line)
- end
- end
- table.insert(lines, '```')
- end
-
- local width = 0
- for _, line in ipairs(lines) do
- width = math.max(width, #line)
- end
- local height = math.min(vim.o.lines - 3, #lines)
- local opts = {
- title = 'CopilotChat.nvim Debug Info',
- relative = 'editor',
- width = width,
- height = height,
- row = (vim.o.lines - height) / 2 - 1,
- col = (vim.o.columns - width) / 2,
- style = 'minimal',
- border = 'rounded',
- }
-
- if not utils.is_stable() then
- opts.footer = "Press 'q' to close this window."
- end
-
- local bufnr = vim.api.nvim_create_buf(false, true)
- vim.bo[bufnr].syntax = 'markdown'
- vim.api.nvim_buf_set_lines(bufnr, 0, -1, false, lines)
- vim.bo[bufnr].modifiable = false
- vim.treesitter.start(bufnr, 'markdown')
-
- local win = vim.api.nvim_open_win(bufnr, true, opts)
- vim.wo[win].wrap = true
- vim.wo[win].linebreak = true
- vim.wo[win].cursorline = true
- vim.wo[win].conceallevel = 2
-
- -- Bind 'q' to close the window
- vim.api.nvim_buf_set_keymap(bufnr, 'n', 'q', 'close', { noremap = true, silent = true })
-end
-
-return M
diff --git a/lua/CopilotChat/health.lua b/lua/CopilotChat/health.lua
index b6f7ebb0..3908c74c 100644
--- a/lua/CopilotChat/health.lua
+++ b/lua/CopilotChat/health.lua
@@ -79,6 +79,15 @@ function M.check()
ok('git: ' .. git_version)
end
+ local lynx_version = run_command('lynx', '-version')
+ if lynx_version == false then
+ warn(
+ 'lynx: missing, optional for improved fetching of url contents. See "https://lynx.invisible-island.net/".'
+ )
+ else
+ ok('lynx: ' .. lynx_version)
+ end
+
start('CopilotChat.nvim [dependencies]')
if lualib_installed('plenary') then
diff --git a/lua/CopilotChat/init.lua b/lua/CopilotChat/init.lua
index 9341da11..8017bbd1 100644
--- a/lua/CopilotChat/init.lua
+++ b/lua/CopilotChat/init.lua
@@ -1,217 +1,406 @@
-local default_config = require('CopilotChat.config')
local async = require('plenary.async')
local log = require('plenary.log')
+local default_config = require('CopilotChat.config')
local Copilot = require('CopilotChat.copilot')
-local Chat = require('CopilotChat.chat')
-local Overlay = require('CopilotChat.overlay')
local context = require('CopilotChat.context')
local prompts = require('CopilotChat.prompts')
-local debuginfo = require('CopilotChat.debuginfo')
local utils = require('CopilotChat.utils')
+local Chat = require('CopilotChat.ui.chat')
+local Diff = require('CopilotChat.ui.diff')
+local Overlay = require('CopilotChat.ui.overlay')
+local Debug = require('CopilotChat.ui.debug')
+
local M = {}
-local plugin_name = 'CopilotChat.nvim'
+local PLUGIN_NAME = 'CopilotChat'
+local WORD = '([^%s]+)'
+
+--- @class CopilotChat.source
+--- @field bufnr number
+--- @field winnr number
--- @class CopilotChat.state
--- @field copilot CopilotChat.Copilot?
---- @field chat CopilotChat.Chat?
---- @field source CopilotChat.config.source?
---- @field config CopilotChat.config?
---- @field last_system_prompt string?
+--- @field source CopilotChat.source?
--- @field last_prompt string?
--- @field last_response string?
---- @field last_code_output string?
---- @field diff CopilotChat.Overlay?
---- @field system_prompt CopilotChat.Overlay?
---- @field user_selection CopilotChat.Overlay?
---- @field help CopilotChat.Overlay?
+--- @field chat CopilotChat.ui.Chat?
+--- @field diff CopilotChat.ui.Diff?
+--- @field debug CopilotChat.ui.Debug?
+--- @field overlay CopilotChat.ui.Overlay?
local state = {
copilot = nil,
- chat = nil,
+
+ -- Current state tracking
source = nil,
- config = nil,
- -- State tracking
- last_system_prompt = nil,
+ -- Last state tracking
last_prompt = nil,
last_response = nil,
- last_code_output = nil,
-- Overlays
+ chat = nil,
diff = nil,
- system_prompt = nil,
- user_selection = nil,
- help = nil,
+ overlay = nil,
+ debug = nil,
}
-local function find_lines_between_separator(
- lines,
- current_line,
- start_pattern,
- end_pattern,
- allow_end_of_file
-)
- if not end_pattern then
- end_pattern = start_pattern
+---@param config CopilotChat.config.shared
+---@return CopilotChat.select.selection?
+local function get_selection(config)
+ local bufnr = state.source and state.source.bufnr
+ local winnr = state.source and state.source.winnr
+
+ if
+ config
+ and config.selection
+ and utils.buf_valid(bufnr)
+ and winnr
+ and vim.api.nvim_win_is_valid(winnr)
+ then
+ return config.selection(state.source)
end
- local line_count = #lines
- local separator_line_start = 1
- local separator_line_finish = line_count
- local found_one = false
+ return nil
+end
- -- Find starting separator line
- for i = current_line, 1, -1 do
- local line = lines[i]
+--- Highlights the selection in the source buffer.
+---@param clear boolean
+---@param config CopilotChat.config.shared
+local function highlight_selection(clear, config)
+ local selection_ns = vim.api.nvim_create_namespace('copilot-chat-selection')
+ for _, buf in ipairs(vim.api.nvim_list_bufs()) do
+ vim.api.nvim_buf_clear_namespace(buf, selection_ns, 0, -1)
+ end
- if line and string.match(line, start_pattern) then
- separator_line_start = i + 1
+ if clear or not config.highlight_selection then
+ return
+ end
- for x = separator_line_start, line_count do
- local next_line = lines[x]
- if next_line and string.match(next_line, end_pattern) then
- separator_line_finish = x - 1
- found_one = true
- break
- end
- if allow_end_of_file and x == line_count then
- separator_line_finish = x
- found_one = true
- break
- end
- end
+ local selection = get_selection(config)
+ if
+ not selection
+ or not utils.buf_valid(selection.bufnr)
+ or not selection.start_line
+ or not selection.end_line
+ then
+ return
+ end
+
+ vim.api.nvim_buf_set_extmark(selection.bufnr, selection_ns, selection.start_line - 1, 0, {
+ hl_group = 'CopilotChatSelection',
+ end_row = selection.end_line,
+ strict = false,
+ })
+end
+
+--- Updates the selection based on previous window
+---@param config CopilotChat.config.shared
+local function update_selection(config)
+ local prev_winnr = vim.fn.win_getid(vim.fn.winnr('#'))
+ if prev_winnr ~= state.chat.winnr and vim.fn.win_gettype(prev_winnr) == '' then
+ state.source = {
+ bufnr = vim.api.nvim_win_get_buf(prev_winnr),
+ winnr = prev_winnr,
+ }
+ end
+
+ highlight_selection(false, config)
+end
+
+---@param config CopilotChat.config.shared
+---@return CopilotChat.ui.Diff.Diff?
+local function get_diff(config)
+ local block = state.chat:get_closest_block()
- if found_one then
+ -- If no block found, return nil
+ if not block then
+ return nil
+ end
+
+ -- Initialize variables with selection if available
+ local header = block.header
+ local selection = get_selection(config)
+ local reference = selection and selection.content
+ local start_line = selection and selection.start_line
+ local end_line = selection and selection.end_line
+ local filename = selection and selection.filename
+ local filetype = selection and selection.filetype
+ local bufnr = selection and selection.bufnr
+
+ -- If we have header info, use it as source of truth
+ if header.start_line and header.end_line then
+ -- Try to find matching buffer and window
+ bufnr = nil
+ for _, win in ipairs(vim.api.nvim_list_wins()) do
+ local win_buf = vim.api.nvim_win_get_buf(win)
+ if utils.filename_same(vim.api.nvim_buf_get_name(win_buf), header.filename) then
+ bufnr = win_buf
break
end
end
+
+ filename = header.filename
+ filetype = header.filetype or vim.filetype.match({ filename = filename })
+ start_line = header.start_line
+ end_line = header.end_line
+
+ -- If we found a valid buffer, get the reference content
+ if bufnr and utils.buf_valid(bufnr) then
+ reference =
+ table.concat(vim.api.nvim_buf_get_lines(bufnr, start_line - 1, end_line, false), '\n')
+ filetype = vim.bo[bufnr].filetype
+ end
end
- if not found_one then
- return {}, 1, 1
+ -- If we are missing info, there is no diff to be made
+ if not start_line or not end_line or not filename then
+ return nil
end
- -- Extract everything between the last and next separator or end of file
- local result = {}
- for i = separator_line_start, separator_line_finish do
- table.insert(result, lines[i])
+ return {
+ change = block.content,
+ reference = reference or '',
+ filetype = filetype or '',
+ filename = filename,
+ start_line = start_line,
+ end_line = end_line,
+ bufnr = bufnr,
+ }
+end
+
+---@param winnr number
+---@param bufnr number
+---@param start_line number
+---@param end_line number
+---@param config CopilotChat.config.shared
+local function jump_to_diff(winnr, bufnr, start_line, end_line, config)
+ pcall(vim.api.nvim_win_set_cursor, winnr, { start_line, 0 })
+ pcall(vim.api.nvim_buf_set_mark, bufnr, '<', start_line, 0, {})
+ pcall(vim.api.nvim_buf_set_mark, bufnr, '>', end_line, 0, {})
+ pcall(vim.api.nvim_buf_set_mark, bufnr, '[', start_line, 0, {})
+ pcall(vim.api.nvim_buf_set_mark, bufnr, ']', end_line, 0, {})
+ update_selection(config)
+end
+
+---@param diff CopilotChat.ui.Diff.Diff?
+---@param config CopilotChat.config.shared
+local function apply_diff(diff, config)
+ if not diff or not diff.bufnr then
+ return
+ end
+
+ local winnr = vim.fn.win_findbuf(diff.bufnr)[1]
+ if not winnr then
+ return
end
- return result, separator_line_start, separator_line_finish
+ local lines = vim.split(diff.change, '\n', { trimempty = false })
+ vim.api.nvim_buf_set_lines(diff.bufnr, diff.start_line - 1, diff.end_line, false, lines)
+ jump_to_diff(winnr, diff.bufnr, diff.start_line, diff.start_line + #lines - 1, config)
end
-local function update_prompts(prompt, system_prompt)
+---@param prompt string
+---@param config CopilotChat.config.shared
+---@return string, CopilotChat.config
+local function resolve_prompts(prompt, config)
local prompts_to_use = M.prompts()
- local try_again = false
- local result = string.gsub(prompt, [[/[%w_]+]], function(match)
- local found = prompts_to_use[string.sub(match, 2)]
- if found then
- if found.kind == 'user' then
- local out = found.prompt
- if out and string.match(out, [[/[%w_]+]]) then
- try_again = true
- end
- system_prompt = found.system_prompt or system_prompt
- return out
- elseif found.kind == 'system' then
- system_prompt = found.prompt
- return ''
+ local depth = 0
+ local MAX_DEPTH = 10
+
+ local function resolve(inner_prompt, inner_config)
+ if depth >= MAX_DEPTH then
+ return inner_prompt, inner_config
+ end
+ depth = depth + 1
+
+ inner_prompt = string.gsub(inner_prompt, '/' .. WORD, function(match)
+ local p = prompts_to_use[match]
+ if p then
+ local resolved_prompt, resolved_config = resolve(p.prompt or '', p)
+ inner_config = vim.tbl_deep_extend('force', inner_config, resolved_config)
+ return resolved_prompt
end
+
+ return '/' .. match
+ end)
+
+ depth = depth - 1
+ return inner_prompt, inner_config
+ end
+
+ return resolve(prompt, config)
+end
+
+---@param prompt string
+---@param config CopilotChat.config.shared
+---@return table, string
+local function resolve_embeddings(prompt, config)
+ local contexts = {}
+ local function parse_context(prompt_context)
+ local split = vim.split(prompt_context, ':')
+ local context_name = table.remove(split, 1)
+ local context_input = vim.trim(table.concat(split, ':'))
+ if M.config.contexts[context_name] then
+ table.insert(contexts, {
+ name = context_name,
+ input = (context_input ~= '' and context_input or nil),
+ })
+
+ return true
end
- return match
+ return false
+ end
+
+ prompt = prompt:gsub('#' .. WORD, function(match)
+ if parse_context(match) then
+ return ''
+ end
+ return '#' .. match
end)
- if try_again then
- return update_prompts(result, system_prompt)
+ if config.context then
+ if type(config.context) == 'table' then
+ ---@diagnostic disable-next-line: param-type-mismatch
+ for _, config_context in ipairs(config.context) do
+ parse_context(config_context)
+ end
+ else
+ parse_context(config.context)
+ end
+ end
+
+ local embeddings = utils.ordered_map()
+ for _, context_data in ipairs(contexts) do
+ local context_value = M.config.contexts[context_data.name]
+ for _, embedding in ipairs(context_value.resolve(context_data.input, state.source)) do
+ if embedding then
+ embeddings:set(embedding.filename, embedding)
+ end
+ end
end
- return system_prompt, result
+ return embeddings:values(), prompt
end
-local function get_selection()
- local bufnr = state.source.bufnr
- local winnr = state.source.winnr
- if
- state.config
- and state.config.selection
- and vim.api.nvim_buf_is_valid(bufnr)
- and vim.api.nvim_win_is_valid(winnr)
- then
- return state.config.selection(state.source) or {}
- end
- return {}
+local function resolve_agent(prompt, config)
+ local agents = vim.tbl_keys(state.copilot:list_agents())
+ local selected_agent = config.agent
+ prompt = prompt:gsub('@' .. WORD, function(match)
+ if vim.tbl_contains(agents, match) then
+ selected_agent = match
+ return ''
+ end
+ return '@' .. match
+ end)
+
+ return selected_agent, prompt
+end
+
+local function resolve_model(prompt, config)
+ local models = vim.tbl_keys(state.copilot:list_models())
+ local selected_model = config.model
+ prompt = prompt:gsub('%$' .. WORD, function(match)
+ if vim.tbl_contains(models, match) then
+ selected_model = match
+ return ''
+ end
+ return '$' .. match
+ end)
+
+ return selected_model, prompt
end
-local function finish(config, message, hide_help, start_of_chat)
+---@param start_of_chat boolean?
+local function finish(start_of_chat)
if not start_of_chat then
state.chat:append('\n\n')
end
- state.chat:append(config.question_header .. config.separator .. '\n\n')
-
- local offset = 0
+ state.chat:append(M.config.question_header .. M.config.separator .. '\n\n')
+ -- Reinsert sticky prompts from last prompt
if state.last_prompt then
- for sticky_line in state.last_prompt:gmatch('(>%s+[^\n]+)') do
- state.chat:append(sticky_line .. '\n')
- -- Account for sticky line
- offset = offset + 1
+ local has_sticky = false
+ local lines = vim.split(state.last_prompt, '\n')
+ for _, line in ipairs(lines) do
+ if vim.startswith(line, '> ') then
+ state.chat:append(line .. '\n')
+ has_sticky = true
+ end
end
-
- if offset > 0 then
+ if has_sticky then
state.chat:append('\n')
- -- Account for new line after sticky lines
- offset = offset + 1
end
end
- -- Account for double new line after separator
- offset = offset + 2
-
- if not hide_help then
- state.chat:finish(message, offset)
- end
+ state.chat:finish()
end
-local function show_error(err, config)
- log.error(vim.inspect(err))
+---@param err string|table|nil
+---@param append_newline boolean?
+local function show_error(err, append_newline)
+ err = err or 'Unknown error'
if type(err) == 'string' then
local message = err:match('^[^:]+:[^:]+:(.+)') or err
message = message:gsub('^%s*', '')
err = message
else
- err = vim.inspect(err)
+ err = utils.make_string(err)
+ end
+
+ if append_newline then
+ state.chat:append('\n')
end
- state.chat:append('\n\n' .. config.error_header .. config.separator .. '\n\n')
- state.chat:append('```\n' .. err .. '\n```')
- finish(config)
+ state.chat:append(M.config.error_header .. '\n```error\n' .. err .. '\n```')
+ finish()
end
--- Map a key to a function.
----@param key CopilotChat.config.mapping
+---@param name string
---@param bufnr number
---@param fn function
-local function map_key(key, bufnr, fn)
+local function map_key(name, bufnr, fn)
+ local key = M.config.mappings[name]
if not key then
return
end
if key.normal and key.normal ~= '' then
- vim.keymap.set('n', key.normal, fn, { buffer = bufnr, nowait = true })
+ vim.keymap.set(
+ 'n',
+ key.normal,
+ fn,
+ { buffer = bufnr, nowait = true, desc = PLUGIN_NAME .. ' ' .. name:gsub('_', ' ') }
+ )
end
if key.insert and key.insert ~= '' then
- vim.keymap.set('i', key.insert, fn, { buffer = bufnr })
+ vim.keymap.set('i', key.insert, function()
+ -- If in insert mode and menu visible, use original key
+ if vim.fn.pumvisible() == 1 then
+ local used_key = key.insert == M.config.mappings.complete.insert and '' or key.insert
+ if used_key then
+ vim.api.nvim_feedkeys(
+ vim.api.nvim_replace_termcodes(used_key, true, false, true),
+ 'n',
+ false
+ )
+ end
+ else
+ fn()
+ end
+ end, { buffer = bufnr, desc = PLUGIN_NAME .. ' ' .. name:gsub('_', ' ') })
end
end
--- Get the info for a key.
---@param name string
----@param key CopilotChat.config.mapping?
---@param surround string|nil
---@return string
-local function key_to_info(name, key, surround)
+local function key_to_info(name, surround)
+ local key = M.config.mappings[name]
if not key then
return ''
end
@@ -268,14 +457,20 @@ local function trigger_complete()
return
end
- vim.api.nvim_buf_set_text(bufnr, row - 1, col, row - 1, col, { tostring(value) })
- end)
+ local value_str = tostring(value)
+ vim.api.nvim_buf_set_text(bufnr, row - 1, col, row - 1, col, { value_str })
+ vim.api.nvim_win_set_cursor(0, { row, col + #value_str })
+ end, state.source)
end
return
end
M.complete_items(function(items)
+ if vim.fn.mode() ~= 'i' then
+ return
+ end
+
vim.fn.complete(
cmp_start + 1,
vim.tbl_filter(function(item)
@@ -304,10 +499,20 @@ function M.complete_items(callback)
local items = {}
for name, prompt in pairs(prompts_to_use) do
+ local kind = ''
+ local info = ''
+ if prompt.prompt then
+ kind = 'user'
+ info = prompt.prompt
+ elseif prompt.system_prompt then
+ kind = 'system'
+ info = prompt.system_prompt
+ end
+
items[#items + 1] = {
word = '/' .. name,
- kind = prompt.kind,
- info = prompt.prompt,
+ kind = kind,
+ info = info,
menu = prompt.description or '',
icase = 1,
dup = 0,
@@ -349,32 +554,26 @@ function M.complete_items(callback)
end
table.sort(items, function(a, b)
+ if a.kind == b.kind then
+ return a.word < b.word
+ end
return a.kind < b.kind
end)
- vim.schedule(function()
- callback(items)
- end)
+ async.util.scheduler()
+ callback(items)
end)
end
--- Get the prompts to use.
----@param skip_system boolean|nil
---@return table
-function M.prompts(skip_system)
- local function get_prompt_kind(name)
- return vim.startswith(name, 'COPILOT_') and 'system' or 'user'
- end
-
+function M.prompts()
local prompts_to_use = {}
- if not skip_system then
- for name, prompt in pairs(prompts) do
- prompts_to_use[name] = {
- prompt = prompt,
- kind = get_prompt_kind(name),
- }
- end
+ for name, prompt in pairs(prompts) do
+ prompts_to_use[name] = {
+ system_prompt = prompt,
+ }
end
for name, prompt in pairs(M.config.prompts) do
@@ -382,10 +581,7 @@ function M.prompts(skip_system)
if type(prompt) == 'string' then
val = {
prompt = prompt,
- kind = get_prompt_kind(name),
}
- elseif not val.kind then
- val.kind = get_prompt_kind(name)
end
prompts_to_use[name] = val
@@ -394,36 +590,8 @@ function M.prompts(skip_system)
return prompts_to_use
end
---- Highlights the selection in the source buffer.
----@param clear? boolean
-function M.highlight_selection(clear)
- local selection_ns = vim.api.nvim_create_namespace('copilot-chat-selection')
- for _, buf in ipairs(vim.api.nvim_list_bufs()) do
- vim.api.nvim_buf_clear_namespace(buf, selection_ns, 0, -1)
- end
- if clear then
- return
- end
- local selection = get_selection()
- if not selection.start_row or not selection.end_row then
- return
- end
- vim.api.nvim_buf_set_extmark(
- state.source.bufnr,
- selection_ns,
- selection.start_row - 1,
- selection.start_col - 1,
- {
- hl_group = 'CopilotChatSelection',
- end_row = selection.end_row - 1,
- end_col = selection.end_col,
- strict = false,
- }
- )
-end
-
--- Open the chat window.
----@param config CopilotChat.config|CopilotChat.config.prompt|nil
+---@param config CopilotChat.config.shared?
function M.open(config)
-- If we are already in chat window, do nothing
if state.chat:active() then
@@ -431,14 +599,6 @@ function M.open(config)
end
config = vim.tbl_deep_extend('force', M.config, config or {})
- state.config = config
-
- -- Save the source buffer and window (e.g the buffer we are currently asking about)
- state.source = {
- bufnr = vim.api.nvim_get_current_buf(),
- winnr = vim.api.nvim_get_current_win(),
- }
-
utils.return_to_normal_mode()
state.chat:open(config)
state.chat:follow()
@@ -451,7 +611,7 @@ function M.close()
end
--- Toggle the chat window.
----@param config CopilotChat.config|nil
+---@param config CopilotChat.config.shared?
function M.toggle(config)
if state.chat:visible() then
M.close()
@@ -460,12 +620,13 @@ function M.toggle(config)
end
end
+--- Get the last response.
--- @returns string
function M.response()
return state.last_response
end
---- Select a Copilot GPT model.
+--- Select default Copilot GPT model.
function M.select_model()
async.run(function()
local models = vim.tbl_keys(state.copilot:list_models())
@@ -477,19 +638,18 @@ function M.select_model()
return model
end, models)
- vim.schedule(function()
- vim.ui.select(models, {
- prompt = 'Select a model> ',
- }, function(choice)
- if choice then
- M.config.model = choice:gsub(' %(selected%)', '')
- end
- end)
+ async.util.scheduler()
+ vim.ui.select(models, {
+ prompt = 'Select a model> ',
+ }, function(choice)
+ if choice then
+ M.config.model = choice:gsub(' %(selected%)', '')
+ end
end)
end)
end
---- Select a Copilot agent.
+--- Select default Copilot agent.
function M.select_agent()
async.run(function()
local agents = vim.tbl_keys(state.copilot:list_agents())
@@ -501,122 +661,76 @@ function M.select_agent()
return agent
end, agents)
- vim.schedule(function()
- vim.ui.select(agents, {
- prompt = 'Select an agent> ',
- }, function(choice)
- if choice then
- M.config.agent = choice:gsub(' %(selected%)', '')
- end
- end)
+ async.util.scheduler()
+ vim.ui.select(agents, {
+ prompt = 'Select an agent> ',
+ }, function(choice)
+ if choice then
+ M.config.agent = choice:gsub(' %(selected%)', '')
+ end
end)
end)
end
--- Ask a question to the Copilot model.
----@param prompt string
----@param config CopilotChat.config|CopilotChat.config.prompt|nil
+---@param prompt string?
+---@param config CopilotChat.config.shared?
function M.ask(prompt, config)
config = vim.tbl_deep_extend('force', M.config, config or {})
vim.diagnostic.reset(vim.api.nvim_create_namespace('copilot_diagnostics'))
- M.open(config)
+
+ if not config.headless then
+ M.open(config)
+ end
prompt = vim.trim(prompt or '')
if prompt == '' then
return
end
- if config.clear_chat_on_new_prompt then
- M.stop(true, config)
- elseif state.copilot:stop() then
- finish(config, nil, true)
- end
-
- -- Clear the current input prompt before asking a new question
- local chat_lines = vim.api.nvim_buf_get_lines(state.chat.bufnr, 0, -1, false)
- local _, start_line, end_line =
- find_lines_between_separator(chat_lines, #chat_lines, M.config.separator .. '$', nil, true)
- if #chat_lines == end_line then
- vim.api.nvim_buf_set_lines(state.chat.bufnr, start_line, end_line, false, { '' })
- end
-
- state.chat:append(prompt)
- state.chat:append('\n\n' .. config.answer_header .. config.separator .. '\n\n')
-
- local system_prompt, updated_prompt = update_prompts(prompt or '', config.system_prompt)
- state.last_system_prompt = system_prompt
- state.last_prompt = prompt
- prompt = updated_prompt
- prompt = string.gsub(prompt, '(^|\n)>%s+', '%1')
-
- local selection = get_selection()
- local filetype = selection.filetype
- or (vim.api.nvim_buf_is_valid(state.source.bufnr) and vim.bo[state.source.bufnr].filetype)
- or 'text'
- local filename = selection.filename
- or (vim.api.nvim_buf_is_valid(state.source.bufnr) and vim.api.nvim_buf_get_name(
- state.source.bufnr
- ))
- or 'untitled'
-
- local embeddings = {}
- local function parse_context(prompt_context)
- local split = vim.split(prompt_context, ':')
- local context_name = split[1]
- local context_input = split[2]
- local context_value = config.contexts[context_name]
-
- if context_value then
- for _, embedding in ipairs(context_value.resolve(context_input, state.source)) do
- if embedding then
- table.insert(embeddings, embedding)
- end
- end
-
- prompt = prompt:gsub('#' .. prompt_context .. '%s*', '')
+ if not config.headless then
+ if config.clear_chat_on_new_prompt then
+ M.stop(true)
+ elseif state.copilot:stop() then
+ finish()
end
- end
- if config.context then
- parse_context(config.context)
+ state.last_prompt = prompt
+ state.chat:clear_prompt()
+ state.chat:append('\n\n' .. prompt)
+ state.chat:append('\n\n' .. config.answer_header .. config.separator .. '\n\n')
end
- for prompt_context in prompt:gmatch('#([^%s]+)') do
- parse_context(prompt_context)
- end
+ -- Resolve prompt references
+ local prompt, config = resolve_prompts(prompt, config)
+ local system_prompt = config.system_prompt
- async.run(function()
- local agents = vim.tbl_keys(state.copilot:list_agents())
- local selected_agent = config.agent
- for agent in prompt:gmatch('@([^%s]+)') do
- if vim.tbl_contains(agents, agent) then
- selected_agent = agent
- prompt = prompt:gsub('@' .. agent .. '%s*', '')
- end
- end
+ -- Remove sticky prefix
+ prompt = vim.trim(table.concat(
+ vim.tbl_map(function(l)
+ return l:gsub('^>%s+', '')
+ end, vim.split(prompt, '\n')),
+ '\n'
+ ))
- local models = vim.tbl_keys(state.copilot:list_models())
- local selected_model = config.model
- for model in prompt:gmatch('%$([^%s]+)') do
- if vim.tbl_contains(models, model) then
- selected_model = model
- prompt = prompt:gsub('%$' .. model .. '%s*', '')
- end
- end
+ -- Retrieve the selection
+ local selection = get_selection(config)
+
+ local ok, err = pcall(async.run, function()
+ local embeddings, prompt = resolve_embeddings(prompt, config)
+ local selected_agent, prompt = resolve_agent(prompt, config)
+ local selected_model, prompt = resolve_model(prompt, config)
- local query_ok, filtered_embeddings = pcall(context.filter_embeddings, state.copilot, {
- embeddings = embeddings,
- prompt = prompt,
- selection = selection.lines,
- filename = filename,
- filetype = filetype,
- bufnr = state.source.bufnr,
- })
+ local has_output = false
+ local query_ok, filtered_embeddings =
+ pcall(context.filter_embeddings, state.copilot, prompt, embeddings)
if not query_ok then
- vim.schedule(function()
- show_error(filtered_embeddings, config)
- end)
+ async.util.scheduler()
+ log.error(filtered_embeddings)
+ if not config.headless then
+ show_error(filtered_embeddings, has_output)
+ end
return
end
@@ -624,23 +738,26 @@ function M.ask(prompt, config)
pcall(state.copilot.ask, state.copilot, prompt, {
selection = selection,
embeddings = filtered_embeddings,
- filename = filename,
- filetype = filetype,
system_prompt = system_prompt,
model = selected_model,
agent = selected_agent,
temperature = config.temperature,
- on_progress = function(token)
- vim.schedule(function()
+ no_history = config.headless,
+ on_progress = vim.schedule_wrap(function(token)
+ if not config.headless then
state.chat:append(token)
- end)
- end,
+ end
+ has_output = true
+ end),
})
+ async.util.scheduler()
+
if not ask_ok then
- vim.schedule(function()
- show_error(response, config)
- end)
+ log.error(response)
+ if not config.headless then
+ show_error(response, has_output)
+ end
return
end
@@ -648,52 +765,46 @@ function M.ask(prompt, config)
return
end
- state.last_response = response
-
- vim.schedule(function()
- if token_count and token_max_count and token_count > 0 then
- finish(config, token_count .. '/' .. token_max_count .. ' tokens used')
- else
- finish(config)
- end
+ if not config.headless then
+ state.last_response = response
+ state.chat.token_count = token_count
+ state.chat.token_max_count = token_max_count
+ end
- if config.callback then
- config.callback(response, state.source)
- end
- end)
+ if not config.headless then
+ finish()
+ end
+ if config.callback then
+ config.callback(response, state.source)
+ end
end)
+
+ if not ok then
+ log.error(err)
+ if not config.headless then
+ show_error(err)
+ end
+ end
end
--- Stop current copilot output and optionally reset the chat ten show the help message.
---@param reset boolean?
----@param config CopilotChat.config?
-function M.stop(reset, config)
- config = vim.tbl_deep_extend('force', M.config, config or {})
- local stopped = reset and state.copilot:reset() or state.copilot:stop()
- local wrap = vim.schedule
- if not stopped then
- wrap = function(fn)
- fn()
- end
+function M.stop(reset)
+ if reset then
+ state.copilot:reset()
+ state.chat:clear()
+ state.last_prompt = nil
+ state.last_response = nil
+ else
+ state.copilot:stop()
end
- wrap(function()
- if reset then
- state.chat:clear()
- state.last_system_prompt = nil
- state.last_prompt = nil
- state.last_response = nil
- state.last_code_output = nil
- end
-
- finish(config, nil, nil, reset)
- end)
+ finish(reset)
end
--- Reset the chat window and show the help message.
----@param config CopilotChat.config?
-function M.reset(config)
- M.stop(true, config)
+function M.reset()
+ M.stop(true)
end
--- Save the chat history to a file.
@@ -744,8 +855,7 @@ function M.load(name, history_path)
end
end
- finish(M.config, nil, nil, #history == 0)
- M.open()
+ finish(#history == 0)
end
--- Set the log level
@@ -753,9 +863,9 @@ end
function M.log_level(level)
M.config.log_level = level
M.config.debug = level == 'debug'
- local logfile = string.format('%s/%s.log', vim.fn.stdpath('state'), plugin_name)
+ local logfile = string.format('%s/%s.log', vim.fn.stdpath('state'), PLUGIN_NAME)
log.new({
- plugin = plugin_name,
+ plugin = PLUGIN_NAME,
level = level,
outfile = logfile,
}, true)
@@ -763,8 +873,10 @@ function M.log_level(level)
end
--- Set up the plugin
----@param config CopilotChat.config|nil
+---@param config CopilotChat.config?
function M.setup(config)
+ utils.deprecate("'canary' branch", "'main' branch")
+
-- Handle changed configuration
if config then
if config.mappings then
@@ -779,12 +891,20 @@ function M.setup(config)
normal = key,
}
end
+
+ if name == 'show_system_prompt' then
+ utils.deprecate('config.mappings.' .. name, 'config.mappings.show_info')
+ end
+
+ if name == 'show_user_context' or name == 'show_user_selection' then
+ utils.deprecate('config.mappings.' .. name, 'config.mappings.show_context')
+ end
end
end
- if config.yank_diff_register then
+ if config['yank_diff_register'] then
utils.deprecate('config.yank_diff_register', 'config.mappings.yank_diff.register')
- config.mappings.yank_diff.register = config.yank_diff_register
+ config.mappings.yank_diff.register = config['yank_diff_register']
end
end
@@ -803,7 +923,6 @@ function M.setup(config)
if state.copilot then
state.copilot:stop()
end
-
state.copilot = Copilot(M.config.proxy, M.config.allow_insecure)
if M.config.debug then
@@ -812,19 +931,7 @@ function M.setup(config)
M.log_level(M.config.log_level)
end
- local hl_ns = vim.api.nvim_create_namespace('copilot-chat-highlights')
- vim.api.nvim_set_hl(hl_ns, '@diff.plus', { bg = utils.blend_color_with_neovim_bg('DiffAdd', 20) })
- vim.api.nvim_set_hl(
- hl_ns,
- '@diff.minus',
- { bg = utils.blend_color_with_neovim_bg('DiffDelete', 20) }
- )
- vim.api.nvim_set_hl(
- hl_ns,
- '@diff.delta',
- { bg = utils.blend_color_with_neovim_bg('DiffChange', 20) }
- )
- vim.api.nvim_set_hl(0, 'CopilotChatSpinner', { link = 'CursorColumn', default = true })
+ vim.api.nvim_set_hl(0, 'CopilotChatSpinner', { link = 'DiagnosticInfo', default = true })
vim.api.nvim_set_hl(0, 'CopilotChatHelp', { link = 'DiagnosticInfo', default = true })
vim.api.nvim_set_hl(0, 'CopilotChatSelection', { link = 'Visual', default = true })
vim.api.nvim_set_hl(
@@ -838,69 +945,35 @@ function M.setup(config)
{ link = '@punctuation.special.markdown', default = true }
)
- local overlay_help = key_to_info('close', M.config.mappings.close)
- local diff_help = key_to_info('accept_diff', M.config.mappings.accept_diff)
+ local overlay_help = key_to_info('close')
+ local diff_help = key_to_info('accept_diff')
if overlay_help ~= '' and diff_help ~= '' then
diff_help = diff_help .. '\n' .. overlay_help
end
- if state.diff then
- state.diff:delete()
+ if state.overlay then
+ state.overlay:delete()
end
- state.diff = Overlay('copilot-diff', hl_ns, diff_help, function(bufnr)
- map_key(M.config.mappings.close, bufnr, function()
- state.diff:restore(state.chat.winnr, state.chat.bufnr)
- end)
-
- map_key(M.config.mappings.accept_diff, bufnr, function()
- local current = state.last_code_output
- if not current then
- return
- end
-
- local selection = get_selection()
- if not selection.start_row or not selection.end_row then
- return
- end
-
- local lines = vim.split(current, '\n')
- if #lines > 0 then
- vim.api.nvim_buf_set_text(
- state.source.bufnr,
- selection.start_row - 1,
- selection.start_col - 1,
- selection.end_row - 1,
- selection.end_col,
- lines
- )
- end
+ state.overlay = Overlay('copilot-overlay', overlay_help, function(bufnr)
+ map_key('close', bufnr, function()
+ state.overlay:restore(state.chat.winnr, state.chat.bufnr)
end)
end)
- if state.system_prompt then
- state.system_prompt:delete()
+ if not state.debug then
+ state.debug = Debug()
end
- state.system_prompt = Overlay('copilot-system-prompt', hl_ns, overlay_help, function(bufnr)
- map_key(M.config.mappings.close, bufnr, function()
- state.system_prompt:restore(state.chat.winnr, state.chat.bufnr)
- end)
- end)
- if state.user_selection then
- state.user_selection:delete()
+ if state.diff then
+ state.diff:delete()
end
- state.user_selection = Overlay('copilot-user-selection', hl_ns, overlay_help, function(bufnr)
- map_key(M.config.mappings.close, bufnr, function()
- state.user_selection:restore(state.chat.winnr, state.chat.bufnr)
+ state.diff = Diff(diff_help, function(bufnr)
+ map_key('close', bufnr, function()
+ state.diff:restore(state.chat.winnr, state.chat.bufnr)
end)
- end)
- if state.help then
- state.help:delete()
- end
- state.help = Overlay('copilot-help', hl_ns, overlay_help, function(bufnr)
- map_key(M.config.mappings.close, bufnr, function()
- state.help:restore(state.chat.winnr, state.chat.bufnr)
+ map_key('accept_diff', bufnr, function()
+ apply_diff(state.diff:get_diff(), state.chat.config)
end)
end)
@@ -909,12 +982,16 @@ function M.setup(config)
state.chat:delete()
end
state.chat = Chat(
- M.config.show_help and key_to_info('show_help', M.config.mappings.show_help),
+ M.config.question_header,
+ M.config.answer_header,
+ M.config.separator,
+ key_to_info('show_help'),
function(bufnr)
- map_key(M.config.mappings.show_help, bufnr, function()
+ map_key('show_help', bufnr, function()
local chat_help = '**`Special tokens`**\n'
chat_help = chat_help .. '`@` to select an agent\n'
chat_help = chat_help .. '`#` to select a context\n'
+ chat_help = chat_help .. '`#:` to select input for context\n'
chat_help = chat_help .. '`/` to select a prompt\n'
chat_help = chat_help .. '`$` to select a model\n'
chat_help = chat_help .. '`> ` to make a sticky prompt (copied to next prompt)\n'
@@ -930,51 +1007,34 @@ function M.setup(config)
end)
for _, name in ipairs(chat_keys) do
if name ~= 'close' then
- local key = M.config.mappings[name]
- local info = key_to_info(name, key, '`')
+ local info = key_to_info(name, '`')
if info ~= '' then
chat_help = chat_help .. info .. '\n'
end
end
end
- chat_help = chat_help .. M.config.separator .. '\n'
- state.help:show(chat_help, 'markdown', 'markdown', state.chat.winnr)
+ state.overlay:show(chat_help, state.chat.winnr, 'markdown')
end)
- map_key(M.config.mappings.reset, bufnr, M.reset)
- map_key(M.config.mappings.close, bufnr, M.close)
- map_key(M.config.mappings.complete, bufnr, trigger_complete)
-
- if M.config.chat_autocomplete then
- vim.api.nvim_create_autocmd('TextChangedI', {
- buffer = bufnr,
- callback = function()
- local line = vim.api.nvim_get_current_line()
- local cursor = vim.api.nvim_win_get_cursor(0)
- local col = cursor[2]
- local char = line:sub(col, col)
+ map_key('reset', bufnr, M.reset)
+ map_key('close', bufnr, M.close)
+ map_key('complete', bufnr, trigger_complete)
- if vim.tbl_contains(M.complete_info().triggers, char) then
- utils.debounce(trigger_complete, 100)
- end
- end,
- })
- end
+ map_key('submit_prompt', bufnr, function()
+ local section = state.chat:get_closest_section()
+ if not section or section.answer then
+ return
+ end
- map_key(M.config.mappings.submit_prompt, bufnr, function()
- local chat_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
- local current_line = vim.api.nvim_win_get_cursor(0)[1]
- local lines = find_lines_between_separator(
- chat_lines,
- current_line,
- M.config.separator .. '$',
- nil,
- true
- )
- M.ask(vim.trim(table.concat(lines, '\n')), state.config)
+ M.ask(section.content)
end)
- map_key(M.config.mappings.toggle_sticky, bufnr, function()
+ map_key('toggle_sticky', bufnr, function()
+ local section = state.chat:get_closest_section()
+ if not section or section.answer then
+ return
+ end
+
local current_line = vim.trim(vim.api.nvim_get_current_line())
if current_line == '' then
return
@@ -984,167 +1044,239 @@ function M.setup(config)
local cur_line = cursor[1]
vim.api.nvim_buf_set_lines(bufnr, cur_line - 1, cur_line, false, {})
- local chat_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
- local _, start_line, end_line =
- find_lines_between_separator(chat_lines, cur_line, M.config.separator .. '$', nil, true)
-
if vim.startswith(current_line, '> ') then
return
end
- if start_line then
- local insert_line = start_line
- local first_one = true
-
- for i = insert_line, end_line do
- local line = chat_lines[i]
- if line and vim.trim(line) ~= '' then
- if vim.startswith(line, '> ') then
- first_one = false
- else
- break
- end
- elseif i >= start_line + 1 then
+ local lines = vim.split(section.content, '\n')
+ local insert_line = 1
+ local first_one = true
+
+ for i = insert_line, #lines do
+ local line = lines[i]
+ if line and vim.trim(line) ~= '' then
+ if vim.startswith(line, '> ') then
+ first_one = false
+ else
break
end
-
- insert_line = insert_line + 1
+ elseif i >= 2 then
+ break
end
- local lines = first_one and { '> ' .. current_line, '' } or { '> ' .. current_line }
- vim.api.nvim_buf_set_lines(bufnr, insert_line - 1, insert_line - 1, false, lines)
- vim.api.nvim_win_set_cursor(0, cursor)
+ insert_line = insert_line + 1
end
+
+ insert_line = section.start_line + insert_line - 1
+ local to_insert = first_one and { '> ' .. current_line, '' } or { '> ' .. current_line }
+ vim.api.nvim_buf_set_lines(bufnr, insert_line - 1, insert_line - 1, false, to_insert)
+ vim.api.nvim_win_set_cursor(0, cursor)
end)
- map_key(M.config.mappings.accept_diff, bufnr, function()
- local selection = get_selection()
- if not selection or not selection.start_row or not selection.end_row then
+ map_key('accept_diff', bufnr, function()
+ apply_diff(get_diff(state.chat.config), state.chat.config)
+ end)
+
+ map_key('jump_to_diff', bufnr, function()
+ if
+ not state.source
+ or not state.source.winnr
+ or not vim.api.nvim_win_is_valid(state.source.winnr)
+ then
return
end
- local chat_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
- local current_line = vim.api.nvim_win_get_cursor(0)[1]
- local section_lines, start_line =
- find_lines_between_separator(chat_lines, current_line, M.config.separator .. '$')
- local lines = find_lines_between_separator(
- section_lines,
- current_line - start_line - 1,
- '^```%w+$',
- '^```$'
- )
- if #lines > 0 then
- vim.api.nvim_buf_set_text(
- state.source.bufnr,
- selection.start_row - 1,
- selection.start_col - 1,
- selection.end_row - 1,
- selection.end_col,
- lines
- )
+ local diff = get_diff(state.chat.config)
+ if not diff then
+ return
end
- end)
- map_key(M.config.mappings.yank_diff, bufnr, function()
- local selection = get_selection()
- if not selection or not selection.lines then
- return
+ local diff_bufnr = diff.bufnr
+
+ -- If buffer is not found, try to load it
+ if not diff_bufnr then
+ diff_bufnr = vim.fn.bufadd(diff.filename)
+ vim.fn.bufload(diff_bufnr)
end
- local chat_lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
- local current_line = vim.api.nvim_win_get_cursor(0)[1]
- local section_lines, start_line =
- find_lines_between_separator(chat_lines, current_line, M.config.separator .. '$')
- local lines = find_lines_between_separator(
- section_lines,
- current_line - start_line - 1,
- '^```%w+$',
- '^```$'
+ state.source.bufnr = diff_bufnr
+ vim.api.nvim_win_set_buf(state.source.winnr, diff_bufnr)
+
+ jump_to_diff(
+ state.source.winnr,
+ diff_bufnr,
+ diff.start_line,
+ diff.end_line,
+ state.chat.config
)
- if #lines > 0 then
- local content = table.concat(lines, '\n')
- vim.fn.setreg(M.config.mappings.yank_diff.register, content)
+ end)
+
+ map_key('quickfix_diffs', bufnr, function()
+ local selection = get_selection(state.chat.config)
+ local items = {}
+
+ for _, section in ipairs(state.chat.sections) do
+ for _, block in ipairs(section.blocks) do
+ local header = block.header
+
+ if not header.start_line and selection then
+ header.filename = selection.filename .. ' (selection)'
+ header.start_line = selection.start_line
+ header.end_line = selection.end_line
+ end
+
+ local text = string.format('%s (%s)', header.filename, header.filetype)
+ if header.start_line and header.end_line then
+ text = text .. string.format(' [lines %d-%d]', header.start_line, header.end_line)
+ end
+
+ table.insert(items, {
+ bufnr = bufnr,
+ lnum = block.start_line,
+ end_lnum = block.end_line,
+ text = text,
+ })
+ end
end
+
+ vim.fn.setqflist(items)
+ vim.cmd('copen')
end)
- map_key(M.config.mappings.show_diff, bufnr, function()
- local selection = get_selection()
- if not selection or not selection.lines then
+ map_key('yank_diff', bufnr, function()
+ local diff = get_diff(state.chat.config)
+ if not diff then
return
end
- local chat_lines = vim.api.nvim_buf_get_lines(state.chat.bufnr, 0, -1, false)
- local current_line = vim.api.nvim_win_get_cursor(0)[1]
- local section_lines, start_line =
- find_lines_between_separator(chat_lines, current_line, M.config.separator .. '$')
- local lines = table.concat(
- find_lines_between_separator(
- section_lines,
- current_line - start_line - 1,
- '^```%w+$',
- '^```$'
- ),
- '\n'
- )
- if vim.trim(lines) ~= '' then
- state.last_code_output = lines
-
- local filetype = selection.filetype or vim.bo[state.source.bufnr].filetype
-
- local diff = tostring(vim.diff(selection.lines, lines, {
- result_type = 'unified',
- ignore_blank_lines = true,
- ignore_whitespace = true,
- ignore_whitespace_change = true,
- ignore_whitespace_change_at_eol = true,
- ignore_cr_at_eol = true,
- algorithm = 'myers',
- ctxlen = #selection.lines,
- }))
-
- diff = diff .. '\n' .. M.config.separator .. '\n'
- state.diff:show(diff, filetype, 'diff', state.chat.winnr)
- end
+ vim.fn.setreg(M.config.mappings.yank_diff.register, diff.change)
end)
- map_key(M.config.mappings.show_system_prompt, bufnr, function()
- local prompt = state.last_system_prompt or M.config.system_prompt
- if not prompt then
+ map_key('show_diff', bufnr, function()
+ local diff = get_diff(state.chat.config)
+ if not diff then
return
end
- prompt = prompt .. '\n' .. M.config.separator .. '\n'
- state.system_prompt:show(prompt, 'markdown', 'markdown', state.chat.winnr)
+ state.diff:show(diff, state.chat.winnr)
end)
- map_key(M.config.mappings.show_user_selection, bufnr, function()
- local selection = get_selection()
- if not selection or not selection.lines then
+ map_key('show_info', bufnr, function()
+ local section = state.chat:get_closest_section()
+ if not section or section.answer then
return
end
- local filetype = selection.filetype or vim.bo[state.source.bufnr].filetype
- local lines = selection.lines
- if vim.trim(lines) == '' then
+ local lines = {}
+ local prompt, config = resolve_prompts(section.content, state.chat.config)
+ local system_prompt = config.system_prompt
+
+ async.run(function()
+ local selected_agent = resolve_agent(prompt, config)
+ local selected_model = resolve_model(prompt, config)
+
+ if selected_model then
+ table.insert(lines, '**Model**')
+ table.insert(lines, '```')
+ table.insert(lines, selected_model)
+ table.insert(lines, '```')
+ table.insert(lines, '')
+ end
+
+ if selected_agent then
+ table.insert(lines, '**Agent**')
+ table.insert(lines, '```')
+ table.insert(lines, selected_agent)
+ table.insert(lines, '```')
+ table.insert(lines, '')
+ end
+
+ if system_prompt then
+ table.insert(lines, '**System Prompt**')
+ table.insert(lines, '```')
+ for _, line in ipairs(vim.split(vim.trim(system_prompt), '\n')) do
+ table.insert(lines, line)
+ end
+ table.insert(lines, '```')
+ table.insert(lines, '')
+ end
+
+ async.util.scheduler()
+ state.overlay:show(
+ vim.trim(table.concat(lines, '\n')) .. '\n',
+ state.chat.winnr,
+ 'markdown'
+ )
+ end)
+ end)
+
+ map_key('show_context', bufnr, function()
+ local section = state.chat:get_closest_section()
+ if not section or section.answer then
return
end
- lines = lines .. '\n' .. M.config.separator .. '\n'
- state.user_selection:show(lines, filetype, filetype, state.chat.winnr)
+ local lines = {}
+
+ local selection = get_selection(state.chat.config)
+ if selection then
+ table.insert(lines, '**Selection**')
+ table.insert(lines, '```' .. selection.filetype)
+ for _, line in ipairs(vim.split(selection.content, '\n')) do
+ table.insert(lines, line)
+ end
+ table.insert(lines, '```')
+ table.insert(lines, '')
+ end
+
+ async.run(function()
+ local embeddings = {}
+ if section and not section.answer then
+ embeddings = resolve_embeddings(section.content, state.chat.config)
+ end
+
+ for _, embedding in ipairs(embeddings) do
+ local embed_lines = vim.split(embedding.content, '\n')
+ local preview = vim.list_slice(embed_lines, 1, math.min(10, #embed_lines))
+ local header = string.format('**%s** (%s lines)', embedding.filename, #embed_lines)
+ if #embed_lines > 10 then
+ header = header .. ' (truncated)'
+ end
+
+ table.insert(lines, header)
+ table.insert(lines, '```' .. embedding.filetype)
+ for _, line in ipairs(preview) do
+ table.insert(lines, line)
+ end
+ table.insert(lines, '```')
+ table.insert(lines, '')
+ end
+
+ async.util.scheduler()
+ state.overlay:show(
+ vim.trim(table.concat(lines, '\n')) .. '\n',
+ state.chat.winnr,
+ 'markdown'
+ )
+ end)
end)
vim.api.nvim_create_autocmd({ 'BufEnter', 'BufLeave' }, {
- buffer = state.chat.bufnr,
+ buffer = bufnr,
callback = function(ev)
- if state.config.highlight_selection then
- M.highlight_selection(ev.event == 'BufLeave')
+ local is_enter = ev.event == 'BufEnter'
+
+ if is_enter then
+ update_selection(state.chat.config)
+ else
+ highlight_selection(true, state.chat.config)
end
end,
})
if M.config.insert_at_end then
vim.api.nvim_create_autocmd({ 'InsertEnter' }, {
- buffer = state.chat.bufnr,
+ buffer = bufnr,
callback = function()
vim.cmd('normal! 0')
vim.cmd('normal! G$')
@@ -1153,30 +1285,65 @@ function M.setup(config)
})
end
- finish(M.config, nil, nil, true)
+ if M.config.chat_autocomplete then
+ vim.api.nvim_create_autocmd('TextChangedI', {
+ buffer = bufnr,
+ callback = function()
+ local line = vim.api.nvim_get_current_line()
+ local cursor = vim.api.nvim_win_get_cursor(0)
+ local col = cursor[2]
+ local char = line:sub(col, col)
+
+ if vim.tbl_contains(M.complete_info().triggers, char) then
+ utils.debounce('complete', trigger_complete, 100)
+ end
+ end,
+ })
+
+ -- Add popup and noinsert completeopt if not present
+ if vim.fn.has('nvim-0.11.0') == 1 then
+ local completeopt = vim.opt.completeopt:get()
+ local updated = false
+ if not vim.tbl_contains(completeopt, 'noinsert') then
+ updated = true
+ table.insert(completeopt, 'noinsert')
+ end
+ if not vim.tbl_contains(completeopt, 'popup') then
+ updated = true
+ table.insert(completeopt, 'popup')
+ end
+ if updated then
+ vim.bo[bufnr].completeopt = table.concat(completeopt, ',')
+ end
+ end
+ end
+
+ finish(true)
end
)
- for name, prompt in pairs(M.prompts(true)) do
- vim.api.nvim_create_user_command('CopilotChat' .. name, function(args)
- local input = prompt.prompt
- if args.args and vim.trim(args.args) ~= '' then
- input = input .. ' ' .. args.args
- end
- if input then
- M.ask(input, prompt)
+ for name, prompt in pairs(M.prompts()) do
+ if prompt.prompt then
+ vim.api.nvim_create_user_command('CopilotChat' .. name, function(args)
+ local input = prompt.prompt
+ if args.args and vim.trim(args.args) ~= '' then
+ input = input .. ' ' .. args.args
+ end
+ if input then
+ M.ask(input, prompt)
+ end
+ end, {
+ nargs = '*',
+ force = true,
+ range = true,
+ desc = prompt.description or (PLUGIN_NAME .. ' ' .. name),
+ })
+
+ if prompt.mapping then
+ vim.keymap.set({ 'n', 'v' }, prompt.mapping, function()
+ M.ask(prompt.prompt, prompt)
+ end, { desc = prompt.description or (PLUGIN_NAME .. ' ' .. name) })
end
- end, {
- nargs = '*',
- force = true,
- range = true,
- desc = prompt.description or (plugin_name .. ' ' .. name),
- })
-
- if prompt.mapping then
- vim.keymap.set({ 'n', 'v' }, prompt.mapping, function()
- M.ask(prompt.prompt, prompt)
- end, { desc = prompt.description or (plugin_name .. ' ' .. name) })
end
end
@@ -1210,7 +1377,7 @@ function M.setup(config)
M.reset()
end, { force = true })
vim.api.nvim_create_user_command('CopilotChatDebugInfo', function()
- debuginfo.open()
+ state.debug:open()
end, { force = true })
local function complete_load()
@@ -1224,13 +1391,23 @@ function M.setup(config)
return options
end
-
vim.api.nvim_create_user_command('CopilotChatSave', function(args)
M.save(args.args)
end, { nargs = '*', force = true, complete = complete_load })
vim.api.nvim_create_user_command('CopilotChatLoad', function(args)
M.load(args.args)
end, { nargs = '*', force = true, complete = complete_load })
+
+ -- Store the current directory to window when directory changes
+ -- I dont think there is a better way to do this that functions
+ -- with "rooter" plugins, LSP and stuff as vim.fn.getcwd() when
+ -- i pass window number inside doesnt work
+ vim.api.nvim_create_autocmd({ 'VimEnter', 'WinEnter', 'DirChanged' }, {
+ group = vim.api.nvim_create_augroup('CopilotChat', {}),
+ callback = function()
+ vim.w.cchat_cwd = vim.fn.getcwd()
+ end,
+ })
end
return M
diff --git a/lua/CopilotChat/notify.lua b/lua/CopilotChat/notify.lua
new file mode 100644
index 00000000..db1af837
--- /dev/null
+++ b/lua/CopilotChat/notify.lua
@@ -0,0 +1,34 @@
+local log = require('plenary.log')
+
+local M = {}
+
+M.STATUS = 'status'
+
+M.listeners = {}
+
+--- Publish an event with a message
+---@param event_name string
+---@param data any
+function M.publish(event_name, data)
+ if M.listeners[event_name] then
+ if data and data ~= '' then
+ log.debug(event_name .. ':', data)
+ end
+
+ for _, callback in ipairs(M.listeners[event_name]) do
+ callback(data)
+ end
+ end
+end
+
+--- Listen for an event
+---@param event_name string
+---@param callback fun(data:any)
+function M.listen(event_name, callback)
+ if not M.listeners[event_name] then
+ M.listeners[event_name] = {}
+ end
+ table.insert(M.listeners[event_name], callback)
+end
+
+return M
diff --git a/lua/CopilotChat/prompts.lua b/lua/CopilotChat/prompts.lua
index e9884695..7a7a0cb8 100644
--- a/lua/CopilotChat/prompts.lua
+++ b/lua/CopilotChat/prompts.lua
@@ -21,7 +21,10 @@ You are an AI programming assistant.
]] .. base
M.COPILOT_EXPLAIN = [[
-You are a world-class coding tutor. Your code explanations perfectly balance high-level concepts and granular details. Your approach ensures that students not only understand how to write code, but also grasp the underlying principles that guide effective programming.
+You are a world-class coding tutor.
+Your code explanations perfectly balance high-level concepts and granular details.
+Your approach ensures that students not only understand how to write code, but also grasp the underlying principles that guide effective programming.
+When examining code pay close attention to diagnostics as well. When explaining diagnostics, include diagnostic content in your response.
]] .. base
M.COPILOT_REVIEW = M.COPILOT_INSTRUCTIONS
@@ -80,7 +83,9 @@ Your task is to modify the provided code according to the user's request. Follow
8. If the response do not fits in a single message, split the response into multiple messages.
-9. Above every returned code snippet, add `[file: ]() line:-`
+9. Directly above every returned code snippet, add `[file:]() line:-`. Example: `[file:copilot.lua](nvim/.config/nvim/lua/config/copilot.lua) line:1-98`. This is markdown link syntax, so make sure to follow it.
+
+10. When fixing code pay close attention to diagnostics as well. When fixing diagnostics, include diagnostic content in your response.
Remember that Your response SHOULD CONTAIN ONLY THE MODIFIED CODE to be used as DIRECT REPLACEMENT to the original file.
]]
diff --git a/lua/CopilotChat/select.lua b/lua/CopilotChat/select.lua
index e6f2c6f0..e6b76587 100644
--- a/lua/CopilotChat/select.lua
+++ b/lua/CopilotChat/select.lua
@@ -1,5 +1,27 @@
+---@class CopilotChat.select.selection.diagnostic
+---@field content string
+---@field start_line number
+---@field end_line number
+---@field severity string
+
+---@class CopilotChat.select.selection
+---@field content string
+---@field start_line number
+---@field end_line number
+---@field filename string
+---@field filetype string
+---@field bufnr number
+---@field diagnostics table?
+
+local utils = require('CopilotChat.utils')
+
local M = {}
+--- Get diagnostics in a given range
+--- @param bufnr number
+--- @param start_line number
+--- @param end_line number
+--- @return table|nil
local function get_diagnostics_in_range(bufnr, start_line, end_line)
local diagnostics = vim.diagnostic.get(bufnr)
local range_diagnostics = {}
@@ -14,12 +36,10 @@ local function get_diagnostics_in_range(bufnr, start_line, end_line)
local lnum = diagnostic.lnum + 1
if lnum >= start_line and lnum <= end_line then
table.insert(range_diagnostics, {
- message = diagnostic.message,
severity = severity[diagnostic.severity],
- start_row = lnum,
- start_col = diagnostic.col + 1,
- end_row = lnum,
- end_col = diagnostic.end_col and (diagnostic.end_col + 1) or diagnostic.col + 1,
+ content = diagnostic.message,
+ start_line = lnum,
+ end_line = diagnostic.end_lnum and diagnostic.end_lnum + 1 or lnum,
})
end
end
@@ -27,148 +47,130 @@ local function get_diagnostics_in_range(bufnr, start_line, end_line)
return #range_diagnostics > 0 and range_diagnostics or nil
end
-local function get_selection_lines(bufnr, start_line, start_col, finish_line, finish_col, full_line)
- -- Exit if no actual selection
- if start_line == finish_line and start_col == finish_col then
+--- Select and process current visual selection
+--- @param source CopilotChat.source
+--- @return CopilotChat.select.selection|nil
+function M.visual(source)
+ local bufnr = source.bufnr
+ local start_line = unpack(vim.api.nvim_buf_get_mark(bufnr, '<'))
+ local finish_line = unpack(vim.api.nvim_buf_get_mark(bufnr, '>'))
+ if start_line == 0 or finish_line == 0 then
return nil
end
-
- -- Get line lengths before swapping
- local function get_line_length(line)
- return #vim.api.nvim_buf_get_lines(bufnr, line - 1, line, false)[1]
- end
-
- -- Swap positions if selection is backwards
- if start_line > finish_line or (start_line == finish_line and start_col > finish_col) then
+ if start_line > finish_line then
start_line, finish_line = finish_line, start_line
- start_col, finish_col = finish_col, start_col
- end
-
- -- Handle full line selection
- if full_line then
- start_col = 1
- finish_col = get_line_length(finish_line)
end
- -- Ensure columns are within valid bounds
- start_col = math.max(1, math.min(start_col, get_line_length(start_line)))
- finish_col = math.max(start_col, math.min(finish_col, get_line_length(finish_line)))
-
- -- Get selected text
- local ok, lines = pcall(
- vim.api.nvim_buf_get_text,
- bufnr,
- start_line - 1,
- start_col - 1,
- finish_line - 1,
- finish_col,
- {}
- )
+ local ok, lines = pcall(vim.api.nvim_buf_get_lines, bufnr, start_line - 1, finish_line, false)
if not ok then
return nil
end
-
local lines_content = table.concat(lines, '\n')
if vim.trim(lines_content) == '' then
return nil
end
return {
- lines = lines_content,
- start_row = start_line,
- start_col = start_col,
- end_row = finish_line,
- end_col = finish_col,
+ content = lines_content,
+ filename = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ':p:.'),
+ filetype = vim.bo[bufnr].filetype,
+ start_line = start_line,
+ end_line = finish_line,
+ bufnr = bufnr,
+ diagnostics = get_diagnostics_in_range(bufnr, start_line, finish_line),
}
end
---- Select and process current visual selection
---- @param source CopilotChat.config.source
---- @return CopilotChat.config.selection|nil
-function M.visual(source)
- local bufnr = source.bufnr
-
- local start_line, start_col = unpack(vim.api.nvim_buf_get_mark(bufnr, '<'))
- local finish_line, finish_col = unpack(vim.api.nvim_buf_get_mark(bufnr, '>'))
- start_col = start_col + 1
- finish_col = finish_col + 1
- return get_selection_lines(bufnr, start_line, start_col, finish_line, finish_col, false)
-end
-
--- Select and process whole buffer
---- @param source CopilotChat.config.source
---- @return CopilotChat.config.selection|nil
+--- @param source CopilotChat.source
+--- @return CopilotChat.select.selection|nil
function M.buffer(source)
local bufnr = source.bufnr
local lines = vim.api.nvim_buf_get_lines(bufnr, 0, -1, false)
-
if not lines or #lines == 0 then
return nil
end
local out = {
- lines = table.concat(lines, '\n'),
- start_row = 1,
- start_col = 1,
- end_row = #lines,
- end_col = #lines[#lines],
+ content = table.concat(lines, '\n'),
+ filename = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ':p:.'),
+ filetype = vim.bo[bufnr].filetype,
+ start_line = 1,
+ end_line = #lines,
+ bufnr = bufnr,
}
- out.diagnostics = get_diagnostics_in_range(bufnr, out.start_row, out.end_row)
+ out.diagnostics = get_diagnostics_in_range(bufnr, out.start_line, out.end_line)
return out
end
--- Select and process current line
---- @param source CopilotChat.config.source
---- @return CopilotChat.config.selection|nil
+--- @param source CopilotChat.source
+--- @return CopilotChat.select.selection|nil
function M.line(source)
local bufnr = source.bufnr
local winnr = source.winnr
local cursor = vim.api.nvim_win_get_cursor(winnr)
local line = vim.api.nvim_buf_get_lines(bufnr, cursor[1] - 1, cursor[1], false)[1]
-
if not line then
return nil
end
local out = {
- lines = line,
- start_row = cursor[1],
- start_col = 1,
- end_row = cursor[1],
- end_col = #line,
+ content = line,
+ filename = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ':p:.'),
+ filetype = vim.bo[bufnr].filetype,
+ start_line = cursor[1],
+ end_line = cursor[1],
+ bufnr = bufnr,
}
- out.diagnostics = get_diagnostics_in_range(bufnr, out.start_row, out.end_row)
+ out.diagnostics = get_diagnostics_in_range(bufnr, out.start_line, out.end_line)
return out
end
--- Select and process contents of unnamed register ("). This register contains last deleted, changed or yanked content.
---- @return CopilotChat.config.selection|nil
-function M.unnamed()
- local lines = vim.fn.getreg('"')
+--- @param source CopilotChat.source
+--- @return CopilotChat.select.selection|nil
+function M.unnamed(source)
+ local bufnr = source.bufnr
+ local start_line = unpack(vim.api.nvim_buf_get_mark(bufnr, '['))
+ local finish_line = unpack(vim.api.nvim_buf_get_mark(bufnr, ']'))
+ if start_line == 0 or finish_line == 0 then
+ return nil
+ end
+ if start_line > finish_line then
+ start_line, finish_line = finish_line, start_line
+ end
- if not lines or lines == '' then
+ local ok, lines = pcall(vim.api.nvim_buf_get_lines, bufnr, start_line - 1, finish_line, false)
+ if not ok then
+ return nil
+ end
+ local lines_content = table.concat(lines, '\n')
+ if vim.trim(lines_content) == '' then
return nil
end
return {
- lines = lines,
+ content = lines_content,
+ filename = vim.fn.fnamemodify(vim.api.nvim_buf_get_name(bufnr), ':p:.'),
+ filetype = vim.bo[bufnr].filetype,
+ start_line = start_line,
+ end_line = finish_line,
+ bufnr = bufnr,
+ diagnostics = get_diagnostics_in_range(bufnr, start_line, finish_line),
}
end
---- Select and process contents of plus register (+). This register is synchronized with system clipboard.
---- @return CopilotChat.config.selection|nil
function M.clipboard()
- local lines = vim.fn.getreg('+')
-
- if not lines or lines == '' then
- return nil
- end
+ utils.deprecate('selection.clipboard', 'context.register:+')
+ return nil
+end
- return {
- lines = lines,
- }
+function M.gitdiff()
+ utils.deprecate('selection.gitdiff', 'context.gitdiff')
+ return nil
end
return M
diff --git a/lua/CopilotChat/tiktoken.lua b/lua/CopilotChat/tiktoken.lua
index e488455f..97f1d25d 100644
--- a/lua/CopilotChat/tiktoken.lua
+++ b/lua/CopilotChat/tiktoken.lua
@@ -1,79 +1,66 @@
-local curl = require('plenary.curl')
-local log = require('plenary.log')
-local tiktoken_core = nil
+local async = require('plenary.async')
+local notify = require('CopilotChat.notify')
+local utils = require('CopilotChat.utils')
local current_tokenizer = nil
+local cache_dir = vim.fn.stdpath('cache')
+vim.fn.mkdir(tostring(cache_dir), 'p')
-local function get_cache_path(fname)
- vim.fn.mkdir(tostring(vim.fn.stdpath('cache')), 'p')
- return vim.fn.stdpath('cache') .. '/' .. fname
-end
-
-local function file_exists(name)
- local f = io.open(name, 'r')
- if f ~= nil then
- io.close(f)
- return true
- else
- return false
- end
+local tiktoken_ok, tiktoken_core = pcall(require, 'tiktoken_core')
+if not tiktoken_ok then
+ tiktoken_core = nil
end
--- Load tiktoken data from cache or download it
-local function load_tiktoken_data(done, tokenizer)
+---@param tokenizer string The tokenizer to load
+local function load_tiktoken_data(tokenizer)
local tiktoken_url = 'https://openaipublic.blob.core.windows.net/encodings/'
.. tokenizer
.. '.tiktoken'
- local cache_path = get_cache_path(tiktoken_url:match('.+/(.+)'))
+ local cache_path = cache_dir .. '/' .. tiktoken_url:match('.+/(.+)')
- if file_exists(cache_path) then
- done(cache_path)
- return
+ if utils.file_exists(cache_path) then
+ return cache_path
end
- log.info('Downloading tiktoken data from ' .. tiktoken_url)
- curl.get(tiktoken_url, {
+ notify.publish(notify.STATUS, 'Downloading tiktoken data from ' .. tiktoken_url)
+
+ utils.curl_get(tiktoken_url, {
output = cache_path,
- callback = function()
- done(cache_path)
- end,
})
+
+ return cache_path
end
local M = {}
-function M.load(tokenizer, on_done)
- if tokenizer == current_tokenizer then
- on_done()
+--- Load the tiktoken module
+---@param tokenizer string The tokenizer to load
+M.load = function(tokenizer)
+ if not tiktoken_core then
return
end
- local ok, core = pcall(require, 'tiktoken_core')
- if not ok then
- on_done()
+ if tokenizer == current_tokenizer then
return
end
- vim.schedule(function()
- load_tiktoken_data(
- vim.schedule_wrap(function(path)
- local special_tokens = {}
- special_tokens['<|endoftext|>'] = 100257
- special_tokens['<|fim_prefix|>'] = 100258
- special_tokens['<|fim_middle|>'] = 100259
- special_tokens['<|fim_suffix|>'] = 100260
- special_tokens['<|endofprompt|>'] = 100276
- local pat_str =
- "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
- core.new(path, special_tokens, pat_str)
- tiktoken_core = core
- current_tokenizer = tokenizer
- on_done()
- end),
- tokenizer
- )
- end)
+ local path = load_tiktoken_data(tokenizer)
+ async.util.scheduler()
+ local special_tokens = {}
+ special_tokens['<|endoftext|>'] = 100257
+ special_tokens['<|fim_prefix|>'] = 100258
+ special_tokens['<|fim_middle|>'] = 100259
+ special_tokens['<|fim_suffix|>'] = 100260
+ special_tokens['<|endofprompt|>'] = 100276
+ local pat_str =
+ "(?i:'s|'t|'re|'ve|'m|'ll|'d)|[^\\r\\n\\p{L}\\p{N}]?\\p{L}+|\\p{N}{1,3}| ?[^\\s\\p{L}\\p{N}]+[\\r\\n]*|\\s*[\\r\\n]+|\\s+(?!\\S)|\\s+"
+ tiktoken_core.new(path, special_tokens, pat_str)
+ current_tokenizer = tokenizer
end
+--- Encode a prompt
+---@param prompt string The prompt to encode
+---@return table?
function M.encode(prompt)
if not tiktoken_core then
return nil
@@ -88,6 +75,9 @@ function M.encode(prompt)
return tiktoken_core.encode(prompt)
end
+--- Count the tokens in a prompt
+---@param prompt string The prompt to count
+---@return number
function M.count(prompt)
if not tiktoken_core then
return math.ceil(#prompt * 0.5) -- Fallback to 1/2 character count
diff --git a/lua/CopilotChat/ui/chat.lua b/lua/CopilotChat/ui/chat.lua
new file mode 100644
index 00000000..7a9c14d6
--- /dev/null
+++ b/lua/CopilotChat/ui/chat.lua
@@ -0,0 +1,534 @@
+local Overlay = require('CopilotChat.ui.overlay')
+local Spinner = require('CopilotChat.ui.spinner')
+local utils = require('CopilotChat.utils')
+local is_stable = utils.is_stable
+local class = utils.class
+
+function CopilotChatFoldExpr(lnum, separator)
+ local to_match = separator .. '$'
+ if string.match(vim.fn.getline(lnum), to_match) then
+ return '1'
+ elseif string.match(vim.fn.getline(lnum + 1), to_match) then
+ return '0'
+ end
+ return '='
+end
+
+---@param header? string
+---@return string?, number?, number?
+local function match_header(header)
+ if not header then
+ return
+ end
+
+ local header_filename, header_start_line, header_end_line =
+ header:match('%[file:.+%]%((.+)%) line:(%d+)-(%d+)')
+ if not header_filename then
+ header_filename, header_start_line, header_end_line =
+ header:match('%[file:(.+)%] line:(%d+)-(%d+)')
+ end
+
+ if header_filename then
+ header_filename = vim.fn.fnamemodify(header_filename, ':p:.')
+ header_start_line = tonumber(header_start_line) or 1
+ header_end_line = tonumber(header_end_line) or header_start_line
+ end
+
+ return header_filename, header_start_line, header_end_line
+end
+
+---@class CopilotChat.ui.Chat.Section.Block.Header
+---@field filename string
+---@field start_line number
+---@field end_line number
+---@field filetype string
+
+---@class CopilotChat.ui.Chat.Section.Block
+---@field header CopilotChat.ui.Chat.Section.Block.Header
+---@field start_line number
+---@field end_line number
+---@field content string?
+
+---@class CopilotChat.ui.Chat.Section
+---@field answer boolean
+---@field start_line number
+---@field end_line number
+---@field blocks table
+---@field content string?
+
+---@class CopilotChat.ui.Chat : CopilotChat.ui.Overlay
+---@field question_header string
+---@field answer_header string
+---@field separator string
+---@field header_ns number
+---@field winnr number?
+---@field spinner CopilotChat.ui.Spinner
+---@field sections table
+---@field config CopilotChat.config.shared
+---@field token_count number?
+---@field token_max_count number?
+local Chat = class(function(self, question_header, answer_header, separator, help, on_buf_create)
+ Overlay.init(self, 'copilot-chat', help, on_buf_create)
+ vim.treesitter.language.register('markdown', self.name)
+
+ self.question_header = question_header
+ self.answer_header = answer_header
+ self.separator = separator
+
+ self.header_ns = vim.api.nvim_create_namespace('copilot-chat-headers')
+ self.winnr = nil
+ self.spinner = nil
+ self.sections = {}
+
+ -- Variables
+ self.config = {}
+ self.token_count = nil
+ self.token_max_count = nil
+end, Overlay)
+
+---@return number
+function Chat:create()
+ local bufnr = Overlay.create(self)
+ vim.bo[bufnr].syntax = 'markdown'
+ vim.bo[bufnr].textwidth = 0
+
+ vim.api.nvim_create_autocmd({ 'TextChanged', 'InsertLeave' }, {
+ buffer = bufnr,
+ callback = function()
+ utils.debounce(self.name, function()
+ self:render()
+ end, 100)
+ end,
+ })
+
+ if not self.spinner then
+ self.spinner = Spinner(bufnr)
+ else
+ self.spinner.bufnr = bufnr
+ end
+
+ return bufnr
+end
+
+function Chat:validate()
+ Overlay.validate(self)
+ if
+ self.winnr
+ and vim.api.nvim_win_is_valid(self.winnr)
+ and vim.api.nvim_win_get_buf(self.winnr) ~= self.bufnr
+ then
+ vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
+ end
+end
+
+---@return boolean
+function Chat:visible()
+ return self.winnr
+ and vim.api.nvim_win_is_valid(self.winnr)
+ and vim.api.nvim_win_get_buf(self.winnr) == self.bufnr
+ or false
+end
+
+function Chat:render()
+ vim.api.nvim_buf_clear_namespace(self.bufnr, self.header_ns, 0, -1)
+ local lines = vim.api.nvim_buf_get_lines(self.bufnr, 0, -1, false)
+ local line_count = #lines
+
+ local sections = {}
+ local current_section = nil
+ local current_block = nil
+
+ for l, line in ipairs(lines) do
+ local separator_found = false
+
+ if line == self.answer_header .. self.separator then
+ separator_found = true
+ if current_section then
+ current_section.end_line = l - 1
+ table.insert(sections, current_section)
+ end
+ current_section = {
+ answer = true,
+ start_line = l + 1,
+ blocks = {},
+ }
+ elseif line == self.question_header .. self.separator then
+ separator_found = true
+ if current_section then
+ current_section.end_line = l - 1
+ table.insert(sections, current_section)
+ end
+ current_section = {
+ answer = false,
+ start_line = l + 1,
+ blocks = {},
+ }
+ elseif l == line_count then
+ if current_section then
+ current_section.end_line = l
+ table.insert(sections, current_section)
+ end
+ end
+
+ -- Highlight separators
+ if self.config.highlight_headers and separator_found then
+ local sep = vim.fn.strwidth(line) - vim.fn.strwidth(self.separator)
+ -- separator line
+ vim.api.nvim_buf_set_extmark(self.bufnr, self.header_ns, l - 1, sep, {
+ virt_text_win_col = sep,
+ virt_text = {
+ { string.rep(self.separator, vim.go.columns), 'CopilotChatSeparator' },
+ },
+ priority = 100,
+ strict = false,
+ })
+ -- header hl group
+ vim.api.nvim_buf_set_extmark(self.bufnr, self.header_ns, l - 1, 0, {
+ end_col = sep + 1,
+ hl_group = 'CopilotChatHeader',
+ priority = 100,
+ strict = false,
+ })
+ end
+
+ -- Parse code blocks
+ if current_section and current_section.answer then
+ local filetype = line:match('^```(%w+)$')
+ if filetype and not current_block then
+ local filename, start_line, end_line = match_header(lines[l - 1])
+ if not filename then
+ filename, start_line, end_line = match_header(lines[l - 2])
+ end
+ filename = filename or 'code-block'
+
+ current_block = {
+ header = {
+ filename = filename,
+ start_line = start_line,
+ end_line = end_line,
+ filetype = filetype,
+ },
+ start_line = l + 1,
+ }
+ elseif line == '```' and current_block then
+ current_block.end_line = l - 1
+ table.insert(current_section.blocks, current_block)
+ current_block = nil
+ end
+ end
+ end
+
+ local last_section = sections[#sections]
+ if last_section and not last_section.answer then
+ local msg = self.config.show_help and self.help or ''
+ if self.token_count and self.token_max_count then
+ if msg ~= '' then
+ msg = msg .. '\n'
+ end
+ msg = msg .. self.token_count .. '/' .. self.token_max_count .. ' tokens used'
+ end
+
+ self:show_help(msg, last_section.start_line - last_section.end_line - 1)
+ else
+ self:clear_help()
+ end
+
+ self.sections = sections
+end
+
+---@return CopilotChat.ui.Chat.Section?
+function Chat:get_closest_section()
+ if not self:visible() then
+ return nil
+ end
+
+ self:render()
+ local cursor_pos = vim.api.nvim_win_get_cursor(self.winnr)
+ local cursor_line = cursor_pos[1]
+ local closest_section = nil
+ local max_line_below_cursor = -1
+
+ for _, section in ipairs(self.sections) do
+ if section.start_line <= cursor_line and section.start_line > max_line_below_cursor then
+ max_line_below_cursor = section.start_line
+ closest_section = section
+ end
+ end
+
+ if not closest_section then
+ return nil
+ end
+
+ local section_content = vim.api.nvim_buf_get_lines(
+ self.bufnr,
+ closest_section.start_line - 1,
+ closest_section.end_line,
+ false
+ )
+
+ return {
+ answer = closest_section.answer,
+ start_line = closest_section.start_line,
+ end_line = closest_section.end_line,
+ content = table.concat(section_content, '\n'),
+ }
+end
+
+---@return CopilotChat.ui.Chat.Section.Block?
+function Chat:get_closest_block()
+ if not self:visible() then
+ return nil
+ end
+
+ self:render()
+ local cursor_pos = vim.api.nvim_win_get_cursor(self.winnr)
+ local cursor_line = cursor_pos[1]
+ local closest_block = nil
+ local max_line_below_cursor = -1
+
+ for _, section in pairs(self.sections) do
+ for _, block in ipairs(section.blocks) do
+ if block.start_line <= cursor_line and block.start_line > max_line_below_cursor then
+ max_line_below_cursor = block.start_line
+ closest_block = block
+ end
+ end
+ end
+
+ if not closest_block then
+ return nil
+ end
+
+ local block_content = vim.api.nvim_buf_get_lines(
+ self.bufnr,
+ closest_block.start_line - 1,
+ closest_block.end_line,
+ false
+ )
+
+ return {
+ header = closest_block.header,
+ start_line = closest_block.start_line,
+ end_line = closest_block.end_line,
+ content = table.concat(block_content, '\n'),
+ }
+end
+
+function Chat:clear_prompt()
+ if not self:visible() then
+ return
+ end
+
+ self:render()
+ local section = self.sections[#self.sections]
+ if not section or section.answer then
+ return
+ end
+
+ vim.bo[self.bufnr].modifiable = true
+ vim.api.nvim_buf_set_lines(self.bufnr, section.start_line - 1, section.end_line, false, {})
+ vim.bo[self.bufnr].modifiable = false
+end
+
+---@return boolean
+function Chat:active()
+ return vim.api.nvim_get_current_win() == self.winnr
+end
+
+---@return number, number, number
+function Chat:last()
+ self:validate()
+ local line_count = vim.api.nvim_buf_line_count(self.bufnr)
+ local last_line = line_count - 1
+ if last_line < 0 then
+ return 0, 0, line_count
+ end
+ local last_line_content = vim.api.nvim_buf_get_lines(self.bufnr, -2, -1, false)
+ if not last_line_content or #last_line_content == 0 then
+ return last_line, 0, line_count
+ end
+ local last_column = #last_line_content[1]
+ return last_line, last_column, line_count
+end
+
+---@param str string
+function Chat:append(str)
+ self:validate()
+ vim.bo[self.bufnr].modifiable = true
+
+ if self:active() then
+ utils.return_to_normal_mode()
+ end
+
+ if self.spinner then
+ self.spinner:start()
+ end
+
+ -- Decide if we should follow cursor after appending text.
+ local should_follow_cursor = self.config.auto_follow_cursor
+ if should_follow_cursor and self:visible() then
+ local current_pos = vim.api.nvim_win_get_cursor(self.winnr)
+ local line_count = vim.api.nvim_buf_line_count(self.bufnr)
+ -- Follow only if the cursor is currently at the last line.
+ should_follow_cursor = current_pos[1] == line_count
+ end
+
+ local last_line, last_column, _ = self:last()
+ vim.api.nvim_buf_set_text(
+ self.bufnr,
+ last_line,
+ last_column,
+ last_line,
+ last_column,
+ vim.split(str, '\n')
+ )
+
+ if should_follow_cursor then
+ self:follow()
+ end
+
+ vim.bo[self.bufnr].modifiable = false
+end
+
+function Chat:clear()
+ self:validate()
+ self.token_count = nil
+ self.token_max_count = nil
+ vim.bo[self.bufnr].modifiable = true
+ vim.api.nvim_buf_set_lines(self.bufnr, 0, -1, false, {})
+ vim.bo[self.bufnr].modifiable = false
+end
+
+---@param config CopilotChat.config.shared
+function Chat:open(config)
+ self:validate()
+ self.config = config
+
+ local window = config.window or {}
+ local layout = window.layout
+ local width = window.width > 1 and window.width or math.floor(vim.o.columns * window.width)
+ local height = window.height > 1 and window.height or math.floor(vim.o.lines * window.height)
+
+ if self.config.window.layout ~= layout then
+ self:close()
+ end
+
+ if self:visible() then
+ return
+ end
+
+ if layout == 'float' then
+ local win_opts = {
+ style = 'minimal',
+ width = width,
+ height = height,
+ zindex = window.zindex,
+ relative = window.relative,
+ border = window.border,
+ title = window.title,
+ row = window.row or math.floor((vim.o.lines - height) / 2),
+ col = window.col or math.floor((vim.o.columns - width) / 2),
+ }
+ if not is_stable() then
+ win_opts.footer = window.footer
+ end
+ self.winnr = vim.api.nvim_open_win(self.bufnr, false, win_opts)
+ elseif layout == 'vertical' then
+ local orig = vim.api.nvim_get_current_win()
+ local cmd = 'vsplit'
+ if width ~= 0 then
+ cmd = width .. cmd
+ end
+ vim.cmd(cmd)
+ self.winnr = vim.api.nvim_get_current_win()
+ vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
+ vim.api.nvim_set_current_win(orig)
+ elseif layout == 'horizontal' then
+ local orig = vim.api.nvim_get_current_win()
+ local cmd = 'split'
+ if height ~= 0 then
+ cmd = height .. cmd
+ end
+ vim.cmd(cmd)
+ self.winnr = vim.api.nvim_get_current_win()
+ vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
+ vim.api.nvim_set_current_win(orig)
+ elseif layout == 'replace' then
+ self.winnr = vim.api.nvim_get_current_win()
+ vim.api.nvim_win_set_buf(self.winnr, self.bufnr)
+ end
+
+ vim.wo[self.winnr].wrap = true
+ vim.wo[self.winnr].linebreak = true
+ vim.wo[self.winnr].cursorline = true
+ vim.wo[self.winnr].conceallevel = 2
+ vim.wo[self.winnr].foldlevel = 99
+ if config.show_folds then
+ vim.wo[self.winnr].foldcolumn = '1'
+ vim.wo[self.winnr].foldmethod = 'expr'
+ vim.wo[self.winnr].foldexpr = "v:lua.CopilotChatFoldExpr(v:lnum, '" .. self.separator .. "')"
+ else
+ vim.wo[self.winnr].foldcolumn = '0'
+ end
+
+ self:render()
+end
+
+---@param bufnr number?
+function Chat:close(bufnr)
+ if not self:visible() then
+ return
+ end
+
+ if self:active() then
+ utils.return_to_normal_mode()
+ end
+
+ if self.config.window.layout == 'replace' then
+ if bufnr then
+ self:restore(self.winnr, bufnr)
+ end
+ else
+ vim.api.nvim_win_close(self.winnr, true)
+ end
+
+ self.winnr = nil
+end
+
+function Chat:focus()
+ if not self:visible() then
+ return
+ end
+
+ vim.api.nvim_set_current_win(self.winnr)
+ if self.config.auto_insert_mode and self:active() and vim.bo[self.bufnr].modifiable then
+ vim.cmd('startinsert')
+ end
+end
+
+function Chat:follow()
+ if not self:visible() then
+ return
+ end
+
+ local last_line, last_column, line_count = self:last()
+ if line_count == 0 then
+ return
+ end
+
+ vim.api.nvim_win_set_cursor(self.winnr, { last_line + 1, last_column })
+end
+
+function Chat:finish()
+ if not self.spinner then
+ return
+ end
+
+ self.spinner:finish()
+ vim.bo[self.bufnr].modifiable = true
+ if self.config.auto_insert_mode and self:active() then
+ vim.cmd('startinsert')
+ end
+end
+
+return Chat
diff --git a/lua/CopilotChat/ui/debug.lua b/lua/CopilotChat/ui/debug.lua
new file mode 100644
index 00000000..16f9893c
--- /dev/null
+++ b/lua/CopilotChat/ui/debug.lua
@@ -0,0 +1,138 @@
+local async = require('plenary.async')
+local log = require('plenary.log')
+local utils = require('CopilotChat.utils')
+local context = require('CopilotChat.context')
+local Overlay = require('CopilotChat.ui.overlay')
+local class = utils.class
+
+---@return table
+local function build_debug_info()
+ local lines = {
+ 'If you are facing issues, run `:checkhealth CopilotChat` and share the output.',
+ '',
+ 'Log file path:',
+ '`' .. log.logfile .. '`',
+ '',
+ 'Data directory:',
+ '`' .. vim.fn.stdpath('data') .. '`',
+ '',
+ 'Config directory:',
+ '`' .. utils.config_path() .. '`',
+ '',
+ 'Temp directory:',
+ '`' .. vim.fn.fnamemodify(os.tmpname(), ':h') .. '`',
+ '',
+ }
+
+ local buf = context.buffer(0)
+ if buf then
+ if buf.symbols then
+ table.insert(lines, 'Current buffer symbols:')
+ for _, symbol in ipairs(buf.symbols) do
+ table.insert(
+ lines,
+ string.format(
+ '%s `%s` (%s %s %s %s) - `%s`',
+ symbol.type,
+ symbol.name,
+ symbol.start_row,
+ symbol.start_col,
+ symbol.end_row,
+ symbol.end_col,
+ symbol.signature
+ )
+ )
+ end
+ table.insert(lines, '')
+ end
+
+ table.insert(lines, 'Current buffer outline:')
+ table.insert(lines, '`' .. buf.filename .. '`')
+ table.insert(lines, '```' .. buf.filetype)
+ local outline_lines = vim.split(buf.content, '\n')
+ for _, line in ipairs(outline_lines) do
+ table.insert(lines, line)
+ end
+ table.insert(lines, '```')
+ end
+
+ local files = context.files()
+ if files then
+ table.insert(lines, 'Current workspace file map:')
+ table.insert(lines, '```text')
+ for _, file in ipairs(files) do
+ for _, line in ipairs(vim.split(file.content, '\n')) do
+ table.insert(lines, line)
+ end
+ end
+ table.insert(lines, '```')
+ end
+
+ return lines
+end
+
+---@class CopilotChat.ui.Debug : CopilotChat.ui.Overlay
+local Debug = class(function(self)
+ Overlay.init(self, 'copilot-debug', nil, function(bufnr)
+ vim.keymap.set('n', 'q', function()
+ vim.api.nvim_win_close(0, true)
+ end, { buffer = bufnr })
+ end)
+end, Overlay)
+
+function Debug:close()
+ if not self.winnr then
+ return
+ end
+
+ if vim.api.nvim_win_is_valid(self.winnr) then
+ vim.api.nvim_win_close(self.winnr, true)
+ end
+
+ self.winnr = nil
+end
+
+function Debug:open()
+ self:validate()
+ self:close()
+
+ async.run(function()
+ local lines = build_debug_info()
+ async.util.scheduler()
+
+ local height = math.min(vim.o.lines - 3, #lines)
+ local width = 0
+ for _, line in ipairs(lines) do
+ width = math.max(width, #line)
+ end
+
+ local win_opts = {
+ title = 'CopilotChat.nvim Debug Info',
+ relative = 'editor',
+ width = width,
+ height = height,
+ row = math.floor((vim.o.lines - height) / 2) - 1,
+ col = math.floor((vim.o.columns - width) / 2),
+ style = 'minimal',
+ border = 'rounded',
+ zindex = 50,
+ }
+
+ if not utils.is_stable() then
+ win_opts.footer = "Press 'q' to close this window."
+ end
+
+ -- Open window
+ self.winnr = vim.api.nvim_open_win(self.bufnr, true, win_opts)
+ vim.wo[self.winnr].wrap = true
+ vim.wo[self.winnr].linebreak = true
+ vim.wo[self.winnr].cursorline = true
+ vim.wo[self.winnr].conceallevel = 2
+
+ -- Show content
+ self:show(table.concat(lines, '\n'), self.winnr, 'markdown')
+ vim.api.nvim_win_set_cursor(self.winnr, { 1, 0 })
+ end)
+end
+
+return Debug
diff --git a/lua/CopilotChat/ui/diff.lua b/lua/CopilotChat/ui/diff.lua
new file mode 100644
index 00000000..4cf92805
--- /dev/null
+++ b/lua/CopilotChat/ui/diff.lua
@@ -0,0 +1,64 @@
+local Overlay = require('CopilotChat.ui.overlay')
+local utils = require('CopilotChat.utils')
+local class = utils.class
+
+---@class CopilotChat.ui.Diff.Diff
+---@field change string
+---@field reference string
+---@field filename string
+---@field filetype string
+---@field start_line number
+---@field end_line number
+---@field bufnr number?
+
+---@class CopilotChat.ui.Diff : CopilotChat.ui.Overlay
+---@field hl_ns number
+---@field diff CopilotChat.ui.Diff.Diff?
+local Diff = class(function(self, help, on_buf_create)
+ Overlay.init(self, 'copilot-diff', help, on_buf_create)
+ self.hl_ns = vim.api.nvim_create_namespace('copilot-chat-highlights')
+ vim.api.nvim_set_hl(self.hl_ns, '@diff.plus', { bg = utils.blend_color('DiffAdd', 20) })
+ vim.api.nvim_set_hl(self.hl_ns, '@diff.minus', { bg = utils.blend_color('DiffDelete', 20) })
+ vim.api.nvim_set_hl(self.hl_ns, '@diff.delta', { bg = utils.blend_color('DiffChange', 20) })
+
+ self.diff = nil
+end, Overlay)
+
+---@param diff CopilotChat.ui.Diff.Diff
+---@param winnr number
+function Diff:show(diff, winnr)
+ self.diff = diff
+ self:validate()
+ vim.api.nvim_win_set_hl_ns(winnr, self.hl_ns)
+
+ Overlay.show(
+ self,
+ tostring(vim.diff(diff.reference, diff.change, {
+ result_type = 'unified',
+ ignore_blank_lines = true,
+ ignore_whitespace = true,
+ ignore_whitespace_change = true,
+ ignore_whitespace_change_at_eol = true,
+ ignore_cr_at_eol = true,
+ algorithm = 'myers',
+ ctxlen = #diff.reference,
+ })),
+ winnr,
+ diff.filetype,
+ 'diff'
+ )
+end
+
+---@param winnr number
+---@param bufnr number
+function Diff:restore(winnr, bufnr)
+ Overlay.restore(self, winnr, bufnr)
+ vim.api.nvim_win_set_hl_ns(winnr, 0)
+end
+
+---@return CopilotChat.ui.Diff.Diff?
+function Diff:get_diff()
+ return self.diff
+end
+
+return Diff
diff --git a/lua/CopilotChat/overlay.lua b/lua/CopilotChat/ui/overlay.lua
similarity index 54%
rename from lua/CopilotChat/overlay.lua
rename to lua/CopilotChat/ui/overlay.lua
index 94d86021..b5d15317 100644
--- a/lua/CopilotChat/overlay.lua
+++ b/lua/CopilotChat/ui/overlay.lua
@@ -1,33 +1,32 @@
----@class CopilotChat.Overlay
----@field bufnr number
----@field valid fun(self: CopilotChat.Overlay)
----@field validate fun(self: CopilotChat.Overlay)
----@field show fun(self: CopilotChat.Overlay, text: string, filetype: string, syntax: string, winnr: number)
----@field restore fun(self: CopilotChat.Overlay, winnr: number, bufnr: number)
----@field delete fun(self: CopilotChat.Overlay)
----@field show_help fun(self: CopilotChat.Overlay, msg: string, offset: number)
-
local utils = require('CopilotChat.utils')
local class = utils.class
-local Overlay = class(function(self, name, hl_ns, help, on_buf_create)
- self.hl_ns = hl_ns
+---@class CopilotChat.ui.Overlay : Class
+---@field name string
+---@field help string
+---@field help_ns number
+---@field on_buf_create fun(bufnr: number)
+---@field bufnr number?
+local Overlay = class(function(self, name, help, on_buf_create)
+ self.name = name
self.help = help
+ self.help_ns = vim.api.nvim_create_namespace('copilot-chat-help')
self.on_buf_create = on_buf_create
self.bufnr = nil
-
- self.buf_create = function()
- local bufnr = vim.api.nvim_create_buf(false, true)
- vim.bo[bufnr].filetype = name
- vim.api.nvim_buf_set_name(bufnr, name)
- return bufnr
- end
end)
+---@return number
+function Overlay:create()
+ local bufnr = vim.api.nvim_create_buf(false, true)
+ vim.bo[bufnr].filetype = self.name
+ vim.bo[bufnr].modifiable = false
+ vim.api.nvim_buf_set_name(bufnr, self.name)
+ return bufnr
+end
+
+---@return boolean
function Overlay:valid()
- return self.bufnr
- and vim.api.nvim_buf_is_valid(self.bufnr)
- and vim.api.nvim_buf_is_loaded(self.bufnr)
+ return utils.buf_valid(self.bufnr)
end
function Overlay:validate()
@@ -35,23 +34,35 @@ function Overlay:validate()
return
end
- self.bufnr = self.buf_create(self)
- self.on_buf_create(self.bufnr)
+ self.bufnr = self:create()
+ if self.on_buf_create then
+ self.on_buf_create(self.bufnr)
+ end
end
-function Overlay:show(text, filetype, syntax, winnr)
+---@param text string
+---@param winnr number
+---@param filetype? string
+---@param syntax string?
+function Overlay:show(text, winnr, filetype, syntax)
+ if not text or vim.trim(text) == '' then
+ return
+ end
+
self:validate()
+ text = text .. '\n'
vim.api.nvim_win_set_buf(winnr, self.bufnr)
-
vim.bo[self.bufnr].modifiable = true
vim.api.nvim_buf_set_lines(self.bufnr, 0, -1, false, vim.split(text, '\n'))
vim.bo[self.bufnr].modifiable = false
self:show_help(self.help, -1)
vim.api.nvim_win_set_cursor(winnr, { vim.api.nvim_buf_line_count(self.bufnr), 0 })
+ filetype = filetype or 'text'
+ syntax = syntax or filetype
+
-- Dual mode with treesitter (for diffs for example)
- vim.api.nvim_win_set_hl_ns(winnr, self.hl_ns)
local ok, parser = pcall(vim.treesitter.get_parser, self.bufnr, syntax)
if ok and parser then
vim.treesitter.start(self.bufnr, syntax)
@@ -61,10 +72,10 @@ function Overlay:show(text, filetype, syntax, winnr)
end
end
+---@param winnr number
+---@param bufnr number?
function Overlay:restore(winnr, bufnr)
- self.current = nil
vim.api.nvim_win_set_buf(winnr, bufnr or 0)
- vim.api.nvim_win_set_hl_ns(winnr, 0)
end
function Overlay:delete()
@@ -73,6 +84,8 @@ function Overlay:delete()
end
end
+---@param msg string
+---@param offset number
function Overlay:show_help(msg, offset)
if not msg then
return
@@ -84,9 +97,8 @@ function Overlay:show_help(msg, offset)
end
self:validate()
- local help_ns = vim.api.nvim_create_namespace('copilot-chat-help')
local line = vim.api.nvim_buf_line_count(self.bufnr) + offset
- vim.api.nvim_buf_set_extmark(self.bufnr, help_ns, math.max(0, line - 1), 0, {
+ vim.api.nvim_buf_set_extmark(self.bufnr, self.help_ns, math.max(0, line - 1), 0, {
id = 1,
hl_mode = 'combine',
priority = 100,
@@ -96,4 +108,8 @@ function Overlay:show_help(msg, offset)
})
end
+function Overlay:clear_help()
+ vim.api.nvim_buf_del_extmark(self.bufnr, self.help_ns, 1)
+end
+
return Overlay
diff --git a/lua/CopilotChat/spinner.lua b/lua/CopilotChat/ui/spinner.lua
similarity index 63%
rename from lua/CopilotChat/spinner.lua
rename to lua/CopilotChat/ui/spinner.lua
index 4c3f8f13..a55a36ae 100644
--- a/lua/CopilotChat/spinner.lua
+++ b/lua/CopilotChat/ui/spinner.lua
@@ -1,9 +1,4 @@
----@class CopilotChat.Spinner
----@field bufnr number
----@field set fun(self: CopilotChat.Spinner, text: string, virt_line: boolean)
----@field start fun(self: CopilotChat.Spinner)
----@field finish fun(self: CopilotChat.Spinner)
-
+local notify = require('CopilotChat.notify')
local utils = require('CopilotChat.utils')
local class = utils.class
@@ -20,11 +15,22 @@ local spinner_frames = {
'⠏',
}
+---@class CopilotChat.ui.Spinner : Class
+---@field ns number
+---@field bufnr number
+---@field timer table
+---@field index number
+---@field status string?
local Spinner = class(function(self, bufnr)
- self.ns = vim.api.nvim_create_namespace('copilot-chat-help')
+ self.ns = vim.api.nvim_create_namespace('copilot-chat-spinner')
self.bufnr = bufnr
self.timer = nil
self.index = 1
+ self.status = nil
+
+ notify.listen(notify.STATUS, function(status)
+ self.status = tostring(status)
+ end)
end)
function Spinner:start()
@@ -37,15 +43,16 @@ function Spinner:start()
0,
100,
vim.schedule_wrap(function()
- if
- not vim.api.nvim_buf_is_valid(self.bufnr)
- or not vim.api.nvim_buf_is_loaded(self.bufnr)
- or not self.timer
- then
+ if not utils.buf_valid(self.bufnr) or not self.timer then
self:finish()
return
end
+ local frame = spinner_frames[self.index]
+ if self.status then
+ frame = self.status .. ' ' .. frame
+ end
+
vim.api.nvim_buf_set_extmark(
self.bufnr,
self.ns,
@@ -55,9 +62,9 @@ function Spinner:start()
id = 1,
hl_mode = 'combine',
priority = 100,
- virt_text = vim.tbl_map(function(t)
- return { t, 'CopilotChatSpinner' }
- end, vim.split(spinner_frames[self.index], '\n')),
+ virt_text = {
+ { frame, 'CopilotChatSpinner' },
+ },
}
)
diff --git a/lua/CopilotChat/utils.lua b/lua/CopilotChat/utils.lua
index 85a1f776..83745249 100644
--- a/lua/CopilotChat/utils.lua
+++ b/lua/CopilotChat/utils.lua
@@ -1,9 +1,18 @@
+local async = require('plenary.async')
+local curl = require('plenary.curl')
+local scandir = require('plenary.scandir')
+
local M = {}
+M.timers = {}
+
+---@class Class
+---@field new fun(...):table
+---@field init fun(self, ...)
--- Create class
---@param fn function The class constructor
---@param parent table? The parent class
----@return table
+---@return Class
function M.class(fn, parent)
local out = {}
out.__index = out
@@ -26,9 +35,50 @@ function M.class(fn, parent)
return self
end
+ function out.init(self, ...)
+ fn(self, ...)
+ end
+
return out
end
+---@class OrderedMap
+---@field set fun(self:OrderedMap, key:any, value:any)
+---@field get fun(self:OrderedMap, key:any):any
+---@field keys fun(self:OrderedMap):table
+---@field values fun(self:OrderedMap):table
+
+--- Create an ordered map
+---@return OrderedMap
+function M.ordered_map()
+ return {
+ _keys = {},
+ _data = {},
+ set = function(self, key, value)
+ if not self._data[key] then
+ table.insert(self._keys, key)
+ end
+ self._data[key] = value
+ end,
+
+ get = function(self, key)
+ return self._data[key]
+ end,
+
+ keys = function(self)
+ return self._keys
+ end,
+
+ values = function(self)
+ local result = {}
+ for _, key in ipairs(self._keys) do
+ table.insert(result, self._data[key])
+ end
+ return result
+ end,
+ }
+end
+
--- Check if the current version of neovim is stable
---@return boolean
function M.is_stable()
@@ -49,32 +99,31 @@ function M.temp_file(text)
return temp_file
end
---- Check if a table is equal to another table
----@param a table The first table
----@param b table The second table
----@return boolean
-function M.table_equals(a, b)
- if type(a) ~= type(b) then
- return false
- end
- if type(a) ~= 'table' then
- return a == b
+--- Finds the path to the user's config directory
+---@return string?
+function M.config_path()
+ local config = vim.fn.expand('$XDG_CONFIG_HOME')
+ if config and vim.fn.isdirectory(config) > 0 then
+ return config
end
- for k, v in pairs(a) do
- if not M.table_equals(v, b[k]) then
- return false
+ if vim.fn.has('win32') > 0 then
+ config = vim.fn.expand('$LOCALAPPDATA')
+ if not config or vim.fn.isdirectory(config) == 0 then
+ config = vim.fn.expand('$HOME/AppData/Local')
end
+ else
+ config = vim.fn.expand('$HOME/.config')
end
- for k, v in pairs(b) do
- if not M.table_equals(v, a[k]) then
- return false
- end
+ if config and vim.fn.isdirectory(config) > 0 then
+ return config
end
- return true
end
--- Blend a color with the neovim background
-function M.blend_color_with_neovim_bg(color_name, blend)
+---@param color_name string The color name
+---@param blend number The blend percentage
+---@return string?
+function M.blend_color(color_name, blend)
local color_int = vim.api.nvim_get_hl(0, { name = color_name }).fg
local bg_int = vim.api.nvim_get_hl(0, { name = 'Normal' }).bg
@@ -95,9 +144,8 @@ function M.return_to_normal_mode()
local mode = vim.fn.mode():lower()
if mode:find('v') then
vim.cmd([[execute "normal! \"]])
- elseif mode:find('i') then
- vim.cmd('stopinsert')
end
+ vim.cmd('stopinsert')
end
--- Mark a function as deprecated
@@ -106,11 +154,220 @@ function M.deprecate(old, new)
end
--- Debounce a function
-function M.debounce(fn, delay)
- if M.timer then
- M.timer:stop()
+function M.debounce(id, fn, delay)
+ if M.timers[id] then
+ M.timers[id]:stop()
+ M.timers[id] = nil
+ end
+ M.timers[id] = vim.defer_fn(fn, delay)
+end
+
+--- Create key-value list from table
+---@param tbl table The table
+---@return table
+function M.kv_list(tbl)
+ local result = {}
+ for k, v in pairs(tbl) do
+ table.insert(result, {
+ key = k,
+ value = v,
+ })
+ end
+
+ return result
+end
+
+--- Check if a buffer is valid
+---@param bufnr number? The buffer number
+---@return boolean
+function M.buf_valid(bufnr)
+ return bufnr and vim.api.nvim_buf_is_valid(bufnr) and vim.api.nvim_buf_is_loaded(bufnr) or false
+end
+
+--- Check if file paths are the same
+---@param file1 string? The first file path
+---@param file2 string? The second file path
+---@return boolean
+function M.filename_same(file1, file2)
+ if not file1 or not file2 then
+ return false
+ end
+ return vim.fn.fnamemodify(file1, ':p') == vim.fn.fnamemodify(file2, ':p')
+end
+
+--- Get the filetype of a file
+---@param filename string The file name
+---@return string|nil
+function M.filetype(filename)
+ local ft = vim.filetype.match({ filename = filename })
+ if ft == '' then
+ return nil
+ end
+ return ft
+end
+
+--- Get the file path
+---@param filename string The file name
+---@return string
+function M.filepath(filename)
+ return vim.fn.fnamemodify(filename, ':p:.')
+end
+
+--- Generate a UUID
+---@return string
+function M.uuid()
+ local template = 'xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'
+ return (
+ string.gsub(template, '[xy]', function(c)
+ local v = (c == 'x') and math.random(0, 0xf) or math.random(8, 0xb)
+ return string.format('%x', v)
+ end)
+ )
+end
+
+--- Generate machine id
+---@return string
+function M.machine_id()
+ local length = 65
+ local hex_chars = '0123456789abcdef'
+ local hex = ''
+ for _ = 1, length do
+ local index = math.random(1, #hex_chars)
+ hex = hex .. hex_chars:sub(index, index)
+ end
+ return hex
+end
+
+--- Generate a quick hash
+---@param str string The string to hash
+---@return string
+function M.quick_hash(str)
+ return #str .. str:sub(1, 32) .. str:sub(-32)
+end
+
+--- Make a string from arguments
+---@vararg any The arguments
+---@return string
+function M.make_string(...)
+ local t = {}
+ for i = 1, select('#', ...) do
+ local x = select(i, ...)
+
+ if type(x) == 'table' then
+ x = vim.inspect(x)
+ else
+ x = tostring(x)
+ end
+
+ t[#t + 1] = x
+ end
+ return table.concat(t, ' ')
+end
+
+--- Get current working directory for target window
+---@param winnr number? The buffer number
+---@return string
+function M.win_cwd(winnr)
+ if not winnr then
+ return '.'
end
- M.timer = vim.defer_fn(fn, delay)
+
+ local dir = vim.w[winnr].cchat_cwd
+ if not dir or dir == '' then
+ return '.'
+ end
+
+ return dir
+end
+
+--- Send curl get request
+---@param url string The url
+---@param opts table? The options
+M.curl_get = async.wrap(function(url, opts, callback)
+ curl.get(
+ url,
+ vim.tbl_deep_extend('force', opts or {}, {
+ callback = callback,
+ on_error = function(err)
+ err = M.make_string(err and err.stderr or err)
+ callback(nil, err)
+ end,
+ })
+ )
+end, 3)
+
+--- Send curl post request
+---@param url string The url
+---@param opts table? The options
+M.curl_post = async.wrap(function(url, opts, callback)
+ curl.post(
+ url,
+ vim.tbl_deep_extend('force', opts or {}, {
+ callback = callback,
+ on_error = function(err)
+ err = M.make_string(err and err.stderr or err)
+ callback(nil, err)
+ end,
+ })
+ )
+end, 3)
+
+--- Scan a directory
+---@param path string The directory path
+---@param opts table The options
+M.scan_dir = async.wrap(function(path, opts, callback)
+ scandir.scan_dir_async(
+ path,
+ vim.tbl_deep_extend('force', opts, {
+ on_exit = callback,
+ })
+ )
+end, 3)
+
+--- Check if a file exists
+---@param path string The file path
+M.file_exists = function(path)
+ local err, stat = async.uv.fs_stat(path)
+ return err == nil and stat ~= nil
end
+--- Get last modified time of a file
+---@param path string The file path
+---@return number?
+M.file_mtime = function(path)
+ local err, stat = async.uv.fs_stat(path)
+ if err or not stat then
+ return nil
+ end
+ return stat.mtime.sec
+end
+
+--- Read a file
+---@param path string The file path
+M.read_file = function(path)
+ local err, fd = async.uv.fs_open(path, 'r', 438)
+ if err or not fd then
+ return nil
+ end
+
+ local err, stat = async.uv.fs_fstat(fd)
+ if err or not stat then
+ async.uv.fs_close(fd)
+ return nil
+ end
+
+ local err, data = async.uv.fs_read(fd, stat.size, 0)
+ async.uv.fs_close(fd)
+ if err or not data then
+ return nil
+ end
+ return data
+end
+
+--- Call a system command
+---@param cmd table The command
+M.system = async.wrap(function(cmd, callback)
+ vim.system(cmd, { text = true }, callback)
+end, 2)
+
return M
diff --git a/test/plugin_spec.lua b/test/plugin_spec.lua
index cb3e4b47..c09cdb88 100644
--- a/test/plugin_spec.lua
+++ b/test/plugin_spec.lua
@@ -8,6 +8,7 @@ package.loaded['plenary.async'] = {
}
package.loaded['plenary.curl'] = {}
package.loaded['plenary.log'] = {}
+package.loaded['plenary.scandir'] = {}
describe('CopilotChat plugin', function()
it('should be able to load', function()