Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Chat with GitHub Copilot in Neovim

License

NotificationsYou must be signed in to change notification settings

CopilotC-Nvim/CopilotChat.nvim

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

CopilotChat.nvim brings GitHub Copilot Chat capabilities directly into Neovim with a focus on transparency and user control.

  • 🤖Multiple AI Models - GitHub Copilot (including GPT-4o, Gemini 2.5 Pro, Claude 4 Sonnet, Claude 3.7 Sonnet, Claude 3.5 Sonnet, o3-mini, o4-mini) + custom providers (Ollama, Mistral.ai). The exact list of available models depends on yourGitHub Copilot settings and the models provided by GitHub's API.
  • 🔧Tool Calling - LLM can use workspace functions (file reading, git operations, search) with your explicit approval
  • 🔒Explicit Control - Only shares what you specifically request - no background data collection
  • 📝Interactive Chat - Rich UI with completion, diffs, and quickfix integration
  • 🎯Smart Prompts - Composable templates and sticky prompts for consistent context
  • Efficient - Smart token usage with tiktoken counting and history management
  • 🔌Extensible -Custom functions andproviders, plus integrations likemcphub.nvim

Installation

Requirements

Warning

For Neovim < 0.11.0, addnoinsert ornoselect to yourcompleteopt otherwise chat autocompletion will not work.For best autocompletion experience, also addpopup to yourcompleteopt (even on Neovim 0.11.0+).

Optional Dependencies

Integration with pickers

For various plugin pickers to work correctly, you need to replacevim.ui.select with your desired picker (as the defaultvim.ui.select is very basic). Here are some examples:

  • fzf-lua - callrequire('fzf-lua').register_ui_select()
  • telescope - setuptelescope-ui-select.nvim plugin
  • snacks.picker - enableui_select config
  • mini.pick - setvim.ui.select = require('mini.pick').ui_select
return {  {"CopilotC-Nvim/CopilotChat.nvim",dependencies= {      {"nvim-lua/plenary.nvim",branch="master"},    },build="make tiktoken",opts= {-- See Configuration section for options    },  },}
callplug#begin()Plug'nvim-lua/plenary.nvim'Plug'CopilotC-Nvim/CopilotChat.nvim'callplug#end()lua << EOFrequire("CopilotChat").setup()EOF

Core Concepts

  • Resources (#<name>) - Add specific content (files, git diffs, URLs) to your prompt
  • Tools (@<name>) - Give LLM access to functions it can call with your approval
  • Sticky Prompts (> <text>) - Persist context across single chat session
  • Models ($<model>) - Specify which AI model to use for the chat
  • Prompts (/PromptName) - Use predefined prompt templates for common tasks

Examples

#Add specific file to context#file:src/main.lua#Give LLM access to workspace tools@copilot What files are in this project?#Sticky prompt that persists>#buffer:current>You are a helpful coding assistant

When you use@copilot, the LLM can call functions likeglob,file,gitdiff etc. You'll see the proposed function call and can approve/reject it before execution.

Usage

Commands

CommandDescription
:CopilotChat <input>?Open chat with optional input
:CopilotChatOpenOpen chat window
:CopilotChatCloseClose chat window
:CopilotChatToggleToggle chat window
:CopilotChatStopStop current output
:CopilotChatResetReset chat window
:CopilotChatSave <name>?Save chat history
:CopilotChatLoad <name>?Load chat history
:CopilotChatPromptsView/select prompt templates
:CopilotChatModelsView/select available models
:CopilotChat<PromptName>Use specific prompt template

Chat Key Mappings

InsertNormalAction
<Tab>-Trigger/accept completion menu for tokens
<C-c>qClose the chat window
<C-l><C-l>Reset and clear the chat window
<C-s><CR>Submit the current prompt
-grrToggle sticky prompt for line under cursor
-grxClear all sticky prompts in prompt
<C-y><C-y>Accept nearest diff
-gjJump to section of nearest diff
-gqaAdd all answers from chat to quickfix list
-gqdAdd all diffs from chat to quickfix list
-gyYank nearest diff to register
-gdShow diff between source and nearest diff
-gcShow info about current chat
-ghShow help message

Warning

Some plugins (e.g.copilot.vim) may also map common keys like<Tab> in insert mode.
To avoid conflicts, disable Copilot's default<Tab> mapping with:

vim.g.copilot_no_tab_map=truevim.keymap.set('i','<S-Tab>','copilot#Accept("\\<S-Tab>")', {expr=true,replace_keycodes=false })

You can also customize CopilotChat keymaps in your config.

Predefined Functions

All predefined functions belong to thecopilot group.

FunctionDescriptionExample Usage
bufferRetrieves content from a specific buffer#buffer
buffersFetches content from multiple buffers#buffers:visible
diagnosticsCollects code diagnostics (errors, warnings)#diagnostics:current
fileReads content from a specified file path#file:path/to/file
gitdiffRetrieves git diff information#gitdiff:staged
gitstatusRetrieves git status information#gitstatus
globLists filenames matching a pattern in workspace#glob:**/*.lua
grepSearches for a pattern across files in workspace#grep:TODO
quickfixIncludes content of files in quickfix list#quickfix
registerProvides access to specified Vim register#register:+
selectionIncludes the current visual selection#selection
urlFetches content from a specified URL#url:https://...

Predefined Prompts

PromptDescription
ExplainWrite detailed explanation of selected code as paragraphs
ReviewComprehensive code review with line-specific issue reporting
FixIdentify problems and rewrite code with fixes and explanation
OptimizeImprove performance and readability with optimization strategy
DocsAdd documentation comments to selected code
TestsGenerate tests for selected code
CommitGenerate commit message with commitizen convention from staged changes

Configuration

For all available configuration options, seelua/CopilotChat/config.lua.

Quick Setup

Most users only need to configure a few options:

{model='gpt-4.1',-- AI model to usetemperature=0.1,-- Lower = focused, higher = creativewindow= {layout='vertical',-- 'vertical', 'horizontal', 'float'width=0.5,-- 50% of screen width  },auto_insert_mode=true,-- Enter insert mode when opening}

Window & Appearance

{window= {layout='float',width=80,-- Fixed width in columnsheight=20,-- Fixed height in rowsborder='rounded',-- 'single', 'double', 'rounded', 'solid'title='🤖 AI Assistant',zindex=100,-- Ensure window stays on top  },headers= {user='👤 You',assistant='🤖 Copilot',tool='🔧 Tool',  },separator='━━',auto_fold=true,-- Automatically folds non-assistant messages}

Buffer Behavior

-- Auto-command to customize chat buffer behaviorvim.api.nvim_create_autocmd('BufEnter', {pattern='copilot-*',callback=function()vim.opt_local.relativenumber=falsevim.opt_local.number=falsevim.opt_local.conceallevel=0end,})

Highlights

You can customize colors by setting highlight groups in your config:

-- In your colorscheme or init.luavim.api.nvim_set_hl(0,'CopilotChatHeader', {fg='#7C3AED',bold=true })vim.api.nvim_set_hl(0,'CopilotChatSeparator', {fg='#374151'})

Types of copilot highlights:

  • CopilotChatHeader - Header highlight in chat buffer
  • CopilotChatSeparator - Separator highlight in chat buffer
  • CopilotChatSelection - Selection highlight in source buffer
  • CopilotChatStatus - Status and spinner in chat buffer
  • CopilotChatHelp - Help text in chat buffer
  • CopilotChatResource - Resource highlight in chat buffer (e.g.#file,#gitdiff)
  • CopilotChatTool - Tool call highlight in chat buffer (e.g.@copilot)
  • CopilotChatPrompt - Prompt highlight in chat buffer (e.g./Explain,/Review)
  • CopilotChatModel - Model highlight in chat buffer (e.g.$gpt-4.1)
  • CopilotChatUri - URI highlight in chat buffer (e.g.##https://...)
  • CopilotChatAnnotation - Annotation highlight in chat buffer (file headers, tool call headers, tool call body)

Prompts

Define your own prompts in the configuration:

{prompts= {MyCustomPrompt= {prompt='Explain how it works.',system_prompt='You are very good at explaining stuff',mapping='<leader>ccmc',description='My custom prompt description',    },Yarrr= {system_prompt='You are fascinated by pirates, so please respond in pirate speak.',    },NiceInstructions= {system_prompt='You are a nice coding tutor, so please respond in a friendly and helpful manner.',    }  }}

Functions

Define your own functions in the configuration with input handling and schema:

{functions= {birthday= {description="Retrieves birthday information for a person",uri="birthday://{name}",schema= {type='object',required= {'name'},properties= {name= {type='string',enum= {'Alice','Bob','Charlie'},description="Person's name",          },        },      },resolve=function(input)return {          {uri='birthday://'..input.name,mimetype='text/plain',data=input.name..' birthday info',          }        }end    }  }}

Providers

Add custom AI providers:

{providers= {my_provider= {get_url=function(opts)return"https://api.example.com/chat"end,get_headers=function()return { ["Authorization"]="Bearer"..api_key }end,get_models=function()return { {id="gpt-4.1",name="GPT-4.1 model"} }end,prepare_input=require('CopilotChat.config.providers').copilot.prepare_input,prepare_output=require('CopilotChat.config.providers').copilot.prepare_output,    }  }}

Provider Interface:

{-- Optional: Disable providerdisabled?:boolean,-- Optional: Extra info about the provider displayed in info panelget_info?():string[]-- Optional: Get extra request headers with optional expiration timeget_headers?():table<string,string>,number?,-- Optional: Get API endpoint URLget_url?(opts:CopilotChat.Provider.options):string,-- Optional: Prepare request inputprepare_input?(inputs:table<CopilotChat.Provider.input>,opts:CopilotChat.Provider.options):table,-- Optional: Prepare response outputprepare_output?(output:table,opts:CopilotChat.Provider.options):CopilotChat.Provider.output,-- Optional: Get available modelsget_models?(headers:table):table<CopilotChat.Provider.model>,}

Built-in providers:

  • copilot - GitHub Copilot (default)
  • github_models - GitHub Marketplace models (disabled by default)

API Reference

Core

localchat=require("CopilotChat")-- Basic Chat Functionschat.ask(prompt,config)-- Ask a question with optional configchat.response()-- Get the last response textchat.resolve_prompt()-- Resolve prompt referenceschat.resolve_tools()-- Resolve tools that are available for automatic use by LLMchat.resolve_model()-- Resolve model from prompt (WARN: async, requires plenary.async.run)-- Window Managementchat.open(config)-- Open chat window with optional configchat.close()-- Close chat windowchat.toggle(config)-- Toggle chat window visibility with optional configchat.reset()-- Reset the chatchat.stop()-- Stop current output-- Source Managementchat.get_source()-- Get the current source buffer and windowchat.set_source(winnr)-- Set the source window-- Prompt & Model Managementchat.select_prompt(config)-- Open prompt selector with optional configchat.select_model()-- Open model selector-- History Managementchat.load(name,history_path)-- Load chat historychat.save(name,history_path)-- Save chat history-- Configurationchat.setup(config)-- Update configurationchat.log_level(level)-- Set log level (debug, info, etc.)

Chat Window

You can also access the chat window UI methods through thechat.chat object:

localwindow=require("CopilotChat").chat-- Chat UI Statewindow:visible()-- Check if chat window is visiblewindow:focused()-- Check if chat window is focused-- Message Managementwindow:get_message(role,cursor)-- Get chat message by role, either last or closest to cursorwindow:add_message({role,content },replace)-- Add or replace a message in chatwindow:remove_message(role,cursor)-- Remove chat message by role, either last or closest to cursorwindow:get_block(role,cursor)-- Get code block by role, either last or closest to cursorwindow:add_sticky(sticky)-- Add sticky prompt to chat message-- Content Managementwindow:append(text)-- Append text to chat windowwindow:clear()-- Clear chat window contentwindow:start()-- Start writing to chat windowwindow:finish()-- Finish writing to chat window-- Navigationwindow:follow()-- Move cursor to end of chat contentwindow:focus()-- Focus the chat window-- Advanced Featureswindow:overlay(opts)-- Show overlay with specified options

Example Usage

-- Open chat, ask a question and handle responserequire("CopilotChat").open()require("CopilotChat").ask("#buffer Explain this code", {callback=function(response)vim.notify("Got response:"..response:sub(1,50).."...")returnresponseend,})-- Save and load chat historyrequire("CopilotChat").save("my_debugging_session")require("CopilotChat").load("my_debugging_session")-- Use custom sticky and modelrequire("CopilotChat").ask("How can I optimize this?", {model="gpt-4.1",sticky= {"#buffer","#gitdiff:staged"}})

For more examples, see theexamples wiki page.

Development

Setup

To set up the environment:

  1. Clone the repository:
git clone https://github.com/CopilotC-Nvim/CopilotChat.nvimcd CopilotChat.nvim
  1. Install development dependencies:
make install-pre-commit

To run tests:

maketest

Contributing

  1. Fork the repository
  2. Create your feature branch
  3. Make your changes
  4. Run tests and lint checks
  5. Submit a pull request

SeeCONTRIBUTING.md for detailed guidelines.

Contributors

Thanks goes to these wonderful people (emoji key):

gptlang
gptlang

💻📖
Dung Duc Huynh (Kaka)
Dung Duc Huynh (Kaka)

💻📖
Ahmed Haracic
Ahmed Haracic

💻
Trí Thiện Nguyễn
Trí Thiện Nguyễn

💻
He Zhizhou
He Zhizhou

💻
Guruprakash Rajakkannu
Guruprakash Rajakkannu

💻
kristofka
kristofka

💻
PostCyberPunk
PostCyberPunk

📖
Katsuhiko Nishimra
Katsuhiko Nishimra

💻
Erno Hopearuoho
Erno Hopearuoho

💻
Shaun Garwood
Shaun Garwood

💻
neutrinoA4
neutrinoA4

💻📖
Jack Muratore
Jack Muratore

💻
Adriel Velazquez
Adriel Velazquez

💻📖
Tomas Slusny
Tomas Slusny

💻📖
Nisal
Nisal

📖
Tobias Gårdhus
Tobias Gårdhus

📖
Petr Dlouhý
Petr Dlouhý

📖
Dylan Madisetti
Dylan Madisetti

💻
Aaron Weisberg
Aaron Weisberg

💻📖
Jose Tlacuilo
Jose Tlacuilo

💻📖
Kevin Traver
Kevin Traver

💻📖
dTry
dTry

💻
Arata Furukawa
Arata Furukawa

💻
Ling
Ling

💻
Ivan Frolov
Ivan Frolov

💻
Folke Lemaitre
Folke Lemaitre

💻📖
GitMurf
GitMurf

💻
Dmitrii Lipin
Dmitrii Lipin

💻
jinzhongjia
jinzhongjia

📖
guill
guill

💻
Sjon-Paul Brown
Sjon-Paul Brown

💻
Renzo Mondragón
Renzo Mondragón

💻📖
fjchen7
fjchen7

💻
Radosław Woźniak
Radosław Woźniak

💻
JakubPecenka
JakubPecenka

💻
thomastthai
thomastthai

📖
Tomáš Janoušek
Tomáš Janoušek

💻
Toddneal Stallworth
Toddneal Stallworth

📖
Sergey Alexandrov
Sergey Alexandrov

💻
Léopold Mebazaa
Léopold Mebazaa

💻
JunKi Jin
JunKi Jin

💻
abdennourzahaf
abdennourzahaf

📖
Josiah
Josiah

💻
Tony Fischer
Tony Fischer

💻📖
Kohei Wada
Kohei Wada

💻
Sebastian Yaghoubi
Sebastian Yaghoubi

📖
johncming
johncming

💻
Rokas Brazdžionis
Rokas Brazdžionis

💻
Sola
Sola

📖💻
Mani Chandra
Mani Chandra

💻
Nischal Basuti
Nischal Basuti

📖
Teo Ljungberg
Teo Ljungberg

💻
Joe Price
Joe Price

💻
Yufan You
Yufan You

📖💻
Manish Kumar
Manish Kumar

💻
Anton Ždanov
Anton Ždanov

📖💻
Fredrik Averpil
Fredrik Averpil

💻
Aaron D Borden
Aaron D Borden

💻
Md. Iftakhar Awal Chowdhury
Md. Iftakhar Awal Chowdhury

💻📖
Danilo Horta
Danilo Horta

💻
Mihamina Rakotomandimby
Mihamina Rakotomandimby

📖💻
Ajmal S
Ajmal S

💻
Samiul Islam
Samiul Islam

💻
Rui Costa
Rui Costa

💻

This project follows theall-contributors specification. Contributions of any kind are welcome!

Stargazers

Stargazers over time

Sponsor this project

  •  
  •  

Packages

No packages published

Languages


[8]ページ先頭

©2009-2025 Movatter.jp