Add custom highlight group based on `user_data` diagnostic information

Hi!

Is there a way to extend/override the diagnostics API to be able to, for example, add a new diagnostic highlight group based on user_data diagnostic information?

I’m trying to add a new highlight group when user_data.lsp.tags includes value 2 (deprecated tag) to strikethrough instead of underline the current word.

If this is not posible, do you know another way to achieve this like VS does?

Screenshot 2021-12-04 at 20.25.59

Thank you!

You can create a new handler for this, see :h diagnostic-handlers

You can create a new handler for this, see :h diagnostic-handlers

Done! Thanks for the tip. I’m leaving the code here in case someone wants to use it:

vim.diagnostic.handlers["strikethrough"] = {
  show = function(namespace, bufnr, diagnostics, _)
    local ns = vim.diagnostic.get_namespace(namespace)

    if not ns.user_data.strikethrough_ns then
      ns.user_data.strikethrough_ns = vim.api.nvim_create_namespace ""
    end

    local higroup = "DiagnosticStrikethroughDeprecated"
    local strikethrough_ns = ns.user_data.strikethrough_ns

    for _, diagnostic in ipairs(diagnostics) do
      local user_data = diagnostic.user_data

      if user_data and user_data.lsp.tags and vim.tbl_contains(user_data.lsp.tags, 2) then
        vim.highlight.range(
          bufnr,
          strikethrough_ns,
          higroup,
          { diagnostic.lnum, diagnostic.col },
          { diagnostic.end_lnum, diagnostic.end_col }
        )
      end
    end
  end,
  hide = function(namespace, bufnr)
    local ns = vim.diagnostic.get_namespace(namespace)

    if ns.user_data.strikethrough_ns then
      vim.api.nvim_buf_clear_namespace(bufnr, ns.user_data.strikethrough_ns, 0, -1)
    end
  end,
}

vim.cmd [[
  augroup diagnostic_strikethrough_deprecated
    autocmd!
    autocmd ColorScheme * highlight DiagnosticStrikethroughDeprecated gui=strikethrough
  augroup END
]]

And here it is working:

Screenshot 2021-12-06 at 17.22.24

1 Like