DEV Community

Cason Adams
Cason Adams

Posted on

Neovim LSP only show line error on CursorHold

I've been using lunarvim for just a bit now, and It is pretty well setup. I recommend trying it out.

Here is a fun little trick to show only the line error for the given line the cursor is on.

There are somethings it doesn't do and that is change the line color base on the error type (Error, Warn, etc..). It is setup to just use highlight for Comment

Open ~/.config/lvim/config.lua and add the following:

lvim.lsp.diagnostics.virtual_text = false


function PrintDiagnostics(opts, bufnr, line_nr, client_id)
  opts = opts or {}

  bufnr = bufnr or 0
  line_nr = line_nr or (vim.api.nvim_win_get_cursor(0)[1] - 1)

  local line_diagnostics = vim.lsp.diagnostic.get_line_diagnostics(bufnr, line_nr, opts, client_id)
  if vim.tbl_isempty(line_diagnostics) then return end

  local diagnostic_message = ""
  for i, diagnostic in ipairs(line_diagnostics) do
    diagnostic_message = diagnostic_message .. string.format("%s ", diagnostic.message or "")
  end
  -- print(diagnostic_message) -- on comment to print to MsgArea
  vim.api.nvim_buf_set_virtual_text(bufnr, 1, line_nr , {{diagnostic_message, "Comment"}}, {})
end

function Clear(_, bufnr, _, _)
-- print("    ") -- on comment to print to MsgArea
  vim.api.nvim_buf_clear_namespace(bufnr, 1, 0, -1)
end

vim.cmd [[ autocmd CursorHold * lua PrintDiagnostics() ]]
vim.cmd [[ autocmd CursorMoved * lua Clear() ]]
Enter fullscreen mode Exit fullscreen mode

Top comments (0)