@@ -101,6 +101,7 @@ function M.buf_attach(force, bufnr)
101101 end
102102
103103 vim .lsp .buf_attach_client (bufnr , M .id )
104+ util .set_buffer_previous_ft (bufnr , vim .bo [bufnr ].filetype )
104105 if force then
105106 logger .debug (" force attached to buffer" )
106107 util .set_buffer_attach_status (bufnr , ATTACH_STATUS_FORCE_ATTACHED )
@@ -110,11 +111,12 @@ function M.buf_attach(force, bufnr)
110111 end
111112end
112113
113- function M .buf_detach ()
114- if M .buf_is_attached (0 ) then
115- vim .lsp .buf_detach_client (0 , M .id )
116- logger .trace (" buffer manuall detached" )
117- util .set_buffer_attach_status (vim .api .nvim_get_current_buf (), ATTACH_STATUS_MANUALLY_DETACHED )
114+ --- @param bufnr ? integer
115+ function M .buf_detach_if_attached (bufnr )
116+ bufnr = bufnr or vim .api .nvim_get_current_buf ()
117+ if M .buf_is_attached (bufnr ) then
118+ vim .lsp .buf_detach_client (bufnr , M .id )
119+ util .set_buffer_attach_status (bufnr , ATTACH_STATUS_NOT_ATTACHED_PREFIX .. " detached" )
118120 end
119121end
120122
@@ -166,6 +168,23 @@ function M.use_client(callback)
166168 end
167169end
168170
171+ --- @param bufnr integer
172+ local function on_filetype (bufnr )
173+ logger .trace (" filetype autocmd called" )
174+ vim .schedule (function ()
175+ -- todo: when we do lazy/late attaching this needs changing
176+
177+ -- This is to handle the case where the filetype changes after the buffer is already attached,
178+ -- causing the LSP to raise an error
179+ if util .get_buffer_previous_ft (bufnr ) ~= vim .bo [bufnr ].filetype then
180+ logger .trace (" filetype changed, detaching and re-attaching" )
181+ M .buf_detach_if_attached (bufnr )
182+ end
183+
184+ M .buf_attach (false , bufnr )
185+ end )
186+ end
187+
169188function M .setup ()
170189 logger .trace (" setting up client" )
171190 local node_command = config .copilot_node_command
@@ -193,11 +212,7 @@ function M.setup()
193212 group = M .augroup ,
194213 callback = function (args )
195214 local bufnr = (args and args .buf ) or nil
196- logger .trace (" filetype autocmd called" )
197- vim .schedule (function ()
198- -- todo: when we do lazy/late attaching this needs changing
199- M .buf_attach (false , bufnr )
200- end )
215+ on_filetype (bufnr )
201216 end ,
202217 desc = " [copilot] (suggestion) file type" ,
203218 })
0 commit comments