From 507cd63418ac56fa5e5d263e3e2d38cfec651f26 Mon Sep 17 00:00:00 2001 From: Mathias Fussenegger Date: Thu, 19 Mar 2026 08:53:38 +0100 Subject: [PATCH] fix(lsp): handle completion/resolve response arriving after on_insert_leave If a user accepts completion and immediately exits insert mode, it could happen that `Context.cursor` was nil by the time the `completion/resolve` response arrives, leading to an error. --- runtime/lua/vim/lsp/completion.lua | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/runtime/lua/vim/lsp/completion.lua b/runtime/lua/vim/lsp/completion.lua index 4734ab935e..b433fab1bf 100644 --- a/runtime/lua/vim/lsp/completion.lua +++ b/runtime/lua/vim/lsp/completion.lua @@ -850,6 +850,10 @@ local function on_complete_done() local position_encoding = client.offset_encoding or 'utf-16' local resolve_provider = (client.server_capabilities.completionProvider or {}).resolveProvider + -- Keep reference to avoid race where completion/resolve response arrives after on_insert_leave + -- and Context.cursor got cleared before clear_word() gets called + local context_cursor = assert(Context.cursor) + local function clear_word() if not expand_snippet then return nil @@ -858,8 +862,8 @@ local function on_complete_done() -- Remove the already inserted word. api.nvim_buf_set_text( bufnr, - Context.cursor[1] - 1, - Context.cursor[2] - 1, + context_cursor[1] - 1, + context_cursor[2] - 1, cursor_row, cursor_col, { '' }