Format & lint

  • There are many plugins for this , I will use null-ls.nvim in this example!

Install null-ls

  1. ["jose-elias-alvarez/null-ls.nvim"] = {
  2. after = "nvim-lspconfig",
  3. config = function()
  4. require("custom.plugins.null-ls").setup()
  5. end,
  6. }
  7. -- load it after nvim-lspconfig cuz we lazy loaded lspconfig

Null-ls config

  • NOTE : The below config is my personal one! So use it as a reference or check null-ls docs
  1. local null_ls = require "null-ls"
  2. local b = null_ls.builtins
  3. local sources = {
  4. b.formatting.prettierd.with { filetypes = { "html", "markdown", "css" } },
  5. b.formatting.deno_fmt,
  6. -- Lua
  7. b.formatting.stylua,
  8. b.diagnostics.luacheck.with { extra_args = { "--global vim" } },
  9. -- Shell
  10. b.formatting.shfmt,
  11. b.diagnostics.shellcheck.with { diagnostics_format = "#{m} [#{c}]" },
  12. }
  13. local M = {}
  14. M.setup = function()
  15. null_ls.setup {
  16. debug = true,
  17. sources = sources,
  18. -- format on save
  19. on_attach = function(client)
  20. if client.resolved_capabilities.document_formatting then
  21. vim.cmd "autocmd BufWritePre <buffer> lua vim.lsp.buf.formatting_sync()"
  22. end
  23. end,
  24. }
  25. end
  26. return M
  • Format code : <leader> + fm
  • Check null-ls builtins to get config for your language!
  • Also note that in the above example I’ve added some config of linters and formatters in null-ls config, so those programs must be installed on my system as well! Like prettierd, stylua, shfmt, eslint_d etc.