Skip to content

bug: nvim_exec_autocmds re-fire missing data and buffer validation after lazy-load #9

@MomePP

Description

@MomePP

Description

After commit 6b351e5 ("fix: lazy-loaded plugins not fully activating"), event.lua re-fires the original autocmd via nvim_exec_autocmds once the plugin is loaded. However, the re-fired event does not forward the original ev.data and does not check whether the buffer is still valid.

This causes two classes of errors:

  1. attempt to index field 'data' (a nil value) — Any autocmd callback that reads event.data (e.g., LspAttach expects event.data.client_id) crashes because data is not forwarded.
  2. Invalid buffer id: N — If the buffer that triggered the original event has been wiped before the re-fire, nvim_exec_autocmds errors on the stale buffer id.

Current code (event.lua:84-88)

if #other_events > 0 then
  util.autocmd(other_events, function(ev)
    loader.process_spec(pack_spec)
    vim.api.nvim_exec_autocmds(ev.event, { buffer = ev.buf, modeline = false })
  end, { group = state.lazy_group, once = true, pattern = normalized_event.pattern })
end

Suggested fix

if #other_events > 0 then
  util.autocmd(other_events, function(ev)
    loader.process_spec(pack_spec)
    if vim.api.nvim_buf_is_valid(ev.buf) then
      vim.api.nvim_exec_autocmds(ev.event, { buffer = ev.buf, data = ev.data, modeline = false })
    end
  end, { group = state.lazy_group, once = true, pattern = normalized_event.pattern })
end

Two changes:

  • Forward data = ev.data so downstream callbacks receive the original event data.
  • Guard with nvim_buf_is_valid(ev.buf) to skip re-fire for wiped buffers.

Reproduction

Minimal init.lua:

vim.pack.add({ 'https://github.com/zuqini/zpack.nvim' })

require('zpack').setup({
  -- Any plugin that lazy-loads on LspAttach
  {
    'https://github.com/someone/example-plugin',
    event = 'LspAttach',
  },
})

-- Callback that depends on event.data
vim.api.nvim_create_autocmd('LspAttach', {
  callback = function(event)
    -- This crashes: event.data is nil when re-fired by zpack
    local client_id = event.data.client_id
    print('attached client:', client_id)
  end,
})

Steps:

  1. Open a file with an LSP server configured (e.g., nvim test.lua).
  2. Wait for the LSP to attach — this triggers the lazy-load of the plugin.
  3. zpack loads the plugin, then re-fires LspAttach without data.

Errors observed:

Error  Lua callback: .../lsp-config.lua:129: attempt to index field 'data' (a nil value)
Error  .../zpack/lazy_trigger/event.lua:87: Invalid buffer id: 1

Environment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions