How to display diagnostic code

I am trying to figure out how to display the diagnostic code in the virtual text and/or float window. Is this possible?

Being able to see the code would be useful for me with shellcheck, because I frequently need to disable specific linter errors. Currently, in order to know which code is causing the error, I have to google the error message from the diagnostic float window.

I would love of there were an option that is similar to source = "always", but to display the code if it is specified in the diagnostic.

For a bit more context, if it is helpful, I am invoking shellcheck through null-ls. It does set the code field here, but I just haven’t been able to figure out how to display it in the diagnostic text.

After this PR, you can use diagnostic.code in format key when configuring vim.diagnostic

local function fmt(diagnostic)
  if diagnostic.code then
    return ("[%s] %s"):format(diagnostic.code, diagnostic.message)
  end
  return diagnostic.message
end

vim.diagnostic.config({
  virtual_text = {
    source = "always",
    format = fmt,
  },
  float = {
    source = "always",
    format = fmt,
  },
})

For null-ls, based on this reference, you can use diagnostic_format = "[#{c}] #{m}" when registering your source

local null_ls = require("null-ls")
local diagnostics = null_ls.builtins.diagnostics
local code_w_msg = "[#{c}] #{m}"

null_ls.setup({
  sources = {
    diagnostics.shellcheck.with({ diagnostics_format = code_w_msg }),
  },
})
1 Like