fix(image): do not attach to invalid buffers (#1238)

## Description

**Problem**: Sometimes when entering Insert mode, I would get an error
message from image's `attach` function:

```
Error executing vim.schedule lua callback: ...cal/share/nvim/lazy/snacks.nvim/lua/snacks/image/doc.lua:215: scoped variable: Invalid buffer id: 88
stack traceback:
        [C]: in function '__index'
        ...cal/share/nvim/lazy/snacks.nvim/lua/snacks/image/doc.lua:215: in function 'attach'
        ...al/share/nvim/lazy/snacks.nvim/lua/snacks/image/init.lua:174: in function <...al/share/nvim/lazy/snacks.nvim/lua/snacks/image/init.lua:173>
```

Looks like by the time the `attach` function is called, the buffer is no
longer valid. This is caused by using `vim.schedule`, which introduces a
small delay, during which the buffer can be deleted.

I suspect this is related to blink.cmp, but I cannot tell for certain.

**Solution**: Make sure that the buffer is valid using
`vim.api.nvim_buf_is_valid` inside the `vim.schedule` callback, before
calling `attach`.

With this fix, the error does not show up anymore.

## Screenshots

I used to get this error when entering Insert mode:

<img width="1474" alt="image"
src="https://github.com/user-attachments/assets/e256a36a-7ff6-4f84-8cdf-9e7b8132a3a1"
/>
This commit is contained in:
Grzegorz Rozdzialik 2025-02-17 13:28:37 +01:00 committed by GitHub
parent 507c1836e3
commit 9a5e4deaec
No known key found for this signature in database
GPG key ID: B5690EEEBB952194

View file

@ -177,7 +177,9 @@ function M.setup(ev)
local lang = vim.treesitter.language.get_lang(ft)
if vim.tbl_contains(langs, lang) then
vim.schedule(function()
M.doc.attach(e.buf)
if vim.api.nvim_buf_is_valid(e.buf) then
M.doc.attach(e.buf)
end
end)
end
end,