From 1970d2ac43059639e4e2c83223d86397b38786ff Mon Sep 17 00:00:00 2001 From: Gregory Anders <8965202+gpanders@users.noreply.github.com> Date: Tue, 13 Sep 2022 08:33:39 -0600 Subject: [PATCH] feat(diagnostic): pass diagnostics as data to DiagnosticChanged autocmd (#20173) --- runtime/doc/diagnostic.txt | 12 ++++++++++-- runtime/lua/vim/diagnostic.lua | 1 + test/functional/lua/diagnostic_spec.lua | 15 +++++++++++---- 3 files changed, 22 insertions(+), 6 deletions(-) diff --git a/runtime/doc/diagnostic.txt b/runtime/doc/diagnostic.txt index e1b52746be..78254c6f2b 100644 --- a/runtime/doc/diagnostic.txt +++ b/runtime/doc/diagnostic.txt @@ -295,10 +295,18 @@ option in the "signs" table of |vim.diagnostic.config()| or 10 if unset). EVENTS *diagnostic-events* *DiagnosticChanged* -DiagnosticChanged After diagnostics have changed. +DiagnosticChanged After diagnostics have changed. When used from Lua, + the new diagnostics are passed to the autocmcd + callback in the "data" table. Example: > - autocmd DiagnosticChanged * lua vim.diagnostic.setqflist({ open = false }) + + vim.api.nvim_create_autocmd('DiagnosticChanged', { + callback = function(args) + local diagnostics = args.data.diagnostics + vim.pretty_print(diagnostics) + end, + }) < ============================================================================== Lua module: vim.diagnostic *diagnostic-api* diff --git a/runtime/lua/vim/diagnostic.lua b/runtime/lua/vim/diagnostic.lua index 4f7d8cccd5..172bd867c7 100644 --- a/runtime/lua/vim/diagnostic.lua +++ b/runtime/lua/vim/diagnostic.lua @@ -727,6 +727,7 @@ function M.set(namespace, bufnr, diagnostics, opts) vim.api.nvim_exec_autocmds('DiagnosticChanged', { modeline = false, buffer = bufnr, + data = { diagnostics = diagnostics }, }) end diff --git a/test/functional/lua/diagnostic_spec.lua b/test/functional/lua/diagnostic_spec.lua index 1514dadca8..28a8679205 100644 --- a/test/functional/lua/diagnostic_spec.lua +++ b/test/functional/lua/diagnostic_spec.lua @@ -1983,19 +1983,26 @@ end) end) it('triggers the autocommand when diagnostics are set', function() - eq(true, exec_lua [[ + eq({true, true}, exec_lua [[ -- Set a different buffer as current to test that is being set properly in -- DiagnosticChanged callbacks local tmp = vim.api.nvim_create_buf(false, true) vim.api.nvim_set_current_buf(tmp) - vim.g.diagnostic_autocmd_triggered = 0 - vim.cmd('autocmd DiagnosticChanged * let g:diagnostic_autocmd_triggered = +expand("")') + local triggered = {} + vim.api.nvim_create_autocmd('DiagnosticChanged', { + callback = function(args) + triggered = {args.buf, #args.data.diagnostics} + end, + }) vim.api.nvim_buf_set_name(diagnostic_bufnr, "test | test") vim.diagnostic.set(diagnostic_ns, diagnostic_bufnr, { make_error('Diagnostic', 0, 0, 0, 0) }) - return vim.g.diagnostic_autocmd_triggered == diagnostic_bufnr + return { + triggered[1] == diagnostic_bufnr, + triggered[2] == 1, + } ]]) end)