@@ -101,6 +101,7 @@ function M.buf_attach(force, bufnr)
101
101
end
102
102
103
103
vim .lsp .buf_attach_client (bufnr , M .id )
104
+ util .set_buffer_previous_ft (bufnr , vim .bo [bufnr ].filetype )
104
105
if force then
105
106
logger .debug (" force attached to buffer" )
106
107
util .set_buffer_attach_status (bufnr , ATTACH_STATUS_FORCE_ATTACHED )
@@ -110,11 +111,12 @@ function M.buf_attach(force, bufnr)
110
111
end
111
112
end
112
113
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" )
118
120
end
119
121
end
120
122
@@ -166,6 +168,23 @@ function M.use_client(callback)
166
168
end
167
169
end
168
170
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
+
169
188
function M .setup ()
170
189
logger .trace (" setting up client" )
171
190
local node_command = config .copilot_node_command
@@ -193,11 +212,7 @@ function M.setup()
193
212
group = M .augroup ,
194
213
callback = function (args )
195
214
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 )
201
216
end ,
202
217
desc = " [copilot] (suggestion) file type" ,
203
218
})
0 commit comments