Skip to content

Instantly share code, notes, and snippets.

@saiashirwad
Created March 15, 2025 12:44
Show Gist options
  • Save saiashirwad/bdc5ee747c0e19d15c284c4bf9c66a1f to your computer and use it in GitHub Desktop.
Save saiashirwad/bdc5ee747c0e19d15c284c4bf9c66a1f to your computer and use it in GitHub Desktop.
-- Function to collect all diagnostic errors and copy them to clipboard
local function copy_errors_to_clipboard()
-- Get the current buffer number
local current_buf = vim.api.nvim_get_current_buf()
-- Get all diagnostics for the current buffer
local diagnostics = vim.diagnostic.get(current_buf)
-- Format each diagnostic into readable lines
local lines = {}
table.insert(lines, '# Errors from ' .. vim.fn.bufname(current_buf))
table.insert(lines, '')
if #diagnostics == 0 then
table.insert(lines, 'No errors found.')
else
for i, diag in ipairs(diagnostics) do
local severity = vim.diagnostic.severity[diag.severity] or 'UNKNOWN'
local line_num = diag.lnum + 1 -- Convert to 1-based line numbering
local col_num = diag.col + 1 -- Convert to 1-based column numbering
local message = diag.message:gsub('\n', ' ') -- Replace any newlines in the message
-- Format: [LINE:COL] [SEVERITY] Message
table.insert(lines, string.format('[%d:%d] [%s] %s', line_num, col_num, severity, message))
end
end
-- Join all lines with newline characters
local error_text = table.concat(lines, '\n')
-- Copy to clipboard
vim.fn.setreg('+', error_text) -- Copy to system clipboard
vim.fn.setreg('"', error_text) -- Copy to unnamed register
-- Notify the user
local count = #diagnostics
local message = count .. ' error' .. (count == 1 and '' or 's') .. ' copied to clipboard'
vim.notify(message, vim.log.levels.INFO)
end
-- Register the command
vim.api.nvim_create_user_command('CopyErrors', function()
copy_errors_to_clipboard()
end, {})
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment