Remap Copilot suggestions in Nvim with Lua

Table of Contents

Tags:

My coc.nvim config allows me to accept suggestions using TAB. Copilot however also accepts suggestions using TAB. These two settings conflict for me, therefore i remapped accepting copilots suggestions to <C-Enter>.

Info

If you don’t know your paths for configuring neovim i recommend reading the official documentation or my blog series on it:

  1. Part
  2. Part
  3. Part

TLDR:

your neovim config is at ~/.config/nvim/init.lua, modify it and insert the following lua code snippets into it and restart nvim to apply the changes

Disable default keybind

The copilot documentation (:help copilot-maps) tells us to set g:copilot_no_tab_map to true. With lua we can do this by modifying this global option using the following snippet:

1vim.g.copilot_no_tab_map = true

This disables accepting copilot suggestions on TAB.

Map a key to accepting suggestions

The above referenced documentation also displays a snippet for binding <C-J> (Control+J) to accepting copilot suggestions.

1imap <silent><script><expr> <C-J> copilot#Accept("\<CR>")

This snippet is written with vim script so we need to translate this to lua using a fancy key mapping helper I introduced in Part II of the personalized development environment series: post.

1-- helper for mapping custom keybindings
2-- source: https://gist.github.com/Jarmos-san/d46605cd3a795513526448f36e0db18e#file-example-keymap-lua
3function map(mode, lhs, rhs, opts)
4    local options = { noremap = true }
5    if opts then
6        options = vim.tbl_extend("force", options, opts)
7    end
8    vim.api.nvim_set_keymap(mode, lhs, rhs, options)
9end

To translate the mapping while keeping in mind we want to use <C-Enter> to accept the suggestion we can write the following:

1-- i: only map the keybind to insert mode
2-- <C-Enter>: execute on ctrl+Enter
3-- copilot#Accept("<CR>") function to execute,
4--      argument is inserted if no suggestion found
5-- options:
6--  - silent:
7--      execute function without logging it in the command bar at the bottom
8map("i", "<C-Enter>", "copilot#Accept('<CR>')", { silent = true, expr = true })