How can I stop nvim from saving a file with errors?

Viewed 33

I'm using nvim for Flutter development. From time to time, if I save a file with compilation errors, then the emulator still hotloads it and my PC hangs.

I use a custom key mapping to save my files. I'd like that to call a function which checks that (pseudo code)

if lua vim.lsp.diagnostic.get_count() > 0 echo an error, else do the save

1 Answers

With Neovim LSP diagnostics, you could use this function to get count of diagnostics of each type (error, warning, info, hint) :

get_diag_count = function()
  local diagnostics = vim.diagnostic.get(0)
  local count = { 0, 0, 0, 0 }

  for _, diagnostic in ipairs(diagnostics) do
    if vim.startswith(vim.diagnostic.get_namespace(diagnostic.namespace).name, 'vim.lsp') then
      count[diagnostic.severity] = count[diagnostic.severity] + 1
    end
  end

  error_count = count[vim.diagnostic.severity.ERROR]
  warning_count = count[vim.diagnostic.severity.WARN]
  info_count = count[vim.diagnostic.severity.INFO]
  hint_count = count[vim.diagnostic.severity.HINT]

  return error_count, warning_count, info_count, hint_count
end
Related