zbirenbaum / copilot-cmp

Lua plugin to turn github copilot into a cmp source
MIT License
1.13k stars 41 forks source link

Avoiding triggering on empty lines #76

Closed naquad closed 1 year ago

naquad commented 1 year ago

When trying to format the code Copilot emits a suggestion:

image

This is an undesired behavior that breaks a usual flow. How do I make Copilot trigger on the non-empty lines OR when manually requested via cmp.mapping.complete()?

I've been trying to follow #56 and tried trigger_characters = {'[^ ]'} and other variations of non-blank characters but unfortunately I couldn't stop it from showing up.

naquad commented 1 year ago

Looks like the plugin is not maintained anymore. As a quick and dirty fix here's what I did:

diff --git a/lua/copilot_cmp/source.lua b/lua/copilot_cmp/source.lua
index 4a0c84d..ff8e938 100644
--- a/lua/copilot_cmp/source.lua
+++ b/lua/copilot_cmp/source.lua
@@ -1,3 +1,5 @@
+local types = require('cmp.types')
+
 local source = {
   executions = {},
 }
@@ -33,6 +35,18 @@ source.is_available = function(self)
   return true
 end

+source.complete = function(self, params, callback)
+  local skip =
+    params.context:get_reason() == types.cmp.ContextReason.Auto and
+    not params.context.cursor_before_line:match('%S')
+
+  if skip then
+    callback({})
+  else
+    self:completer(params, callback)
+  end
+end
+
 source.new = function(client, opts)
   local completion_functions = require("copilot_cmp.completion_functions")

@@ -42,7 +56,7 @@ source.new = function(client, opts)

   self.client = client
   self.request_ids = {}
-  self.complete = completion_functions.init('getCompletionsCycling', opts)
+  self.completer = completion_functions.init('getCompletionsCycling', opts)

   return self
 end

(Full source)

What this "patch" does is it checks if the completion has been automatically triggered and if yes then make sure there's at least one non-whitespace character and if it is there then provide some suggestions otherwise return no suggestions.

zbirenbaum commented 1 year ago

Plugin is maintained, but the majority of issues are things that are infeasible to address without causing more problems, are upstream problems or have been addressed in the past. My turnaround on actual breaking problems is usually within 1-3 weeks. Things like this are handled through the cmp side, and aren't actually copilot-cmp issues.

For the record here's how I handle it in my cmp config

local has_words_before = function()
  if vim.api.nvim_get_option_value("buftype", {buf=0}) == "prompt" then return false end
  local line, col = unpack(vim.api.nvim_win_get_cursor(0))
  return col ~= 0 and vim.api.nvim_buf_get_text(0, line-1, 0, line-1, col, {})[1]:match("^%s*$") == nil
end
cmp.setup({
  mapping = {
    ["<Tab>"] = function (fallback)
      if cmp.visible() and has_words_before() then
        cmp.select_next_item({ behavior = cmp.SelectBehavior.Select })
      else
        fallback()
      end
    end,
  }
})