autoformat.lua 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566
  1. -- autoformat.lua
  2. --
  3. -- Use your language server to automatically format your code on save.
  4. -- Adds additional commands as well to manage the behavior
  5. return {
  6. 'neovim/nvim-lspconfig',
  7. config = function()
  8. -- Switch for controlling whether you want autoformatting.
  9. -- Use :KickstartFormatToggle to toggle autoformatting on or off
  10. local format_is_enabled = true
  11. vim.api.nvim_create_user_command('KickstartFormatToggle', function()
  12. format_is_enabled = not format_is_enabled
  13. print('Setting autoformatting to: ' .. tostring(format_is_enabled))
  14. end, {})
  15. -- Create an augroup that is used for managing our formatting autocmds.
  16. -- We need one augroup per client to make sure that multiple clients
  17. -- can attach to the same buffer without interfering with each other.
  18. local _augroups = {}
  19. local get_augroup = function(client)
  20. if not _augroups[client.id] then
  21. local group_name = 'kickstart-lsp-format-' .. client.name
  22. local id = vim.api.nvim_create_augroup(group_name, { clear = true })
  23. _augroups[client.id] = id
  24. end
  25. return _augroups[client.id]
  26. end
  27. vim.api.nvim_create_autocmd('LspAttach', {
  28. group = vim.api.nvim_create_augroup('kickstart-lsp-attach-format', { clear = true }),
  29. -- This is where we attach the autoformatting for reasonable clients
  30. callback = function(args)
  31. local client_id = args.data.client_id
  32. local client = vim.lsp.get_client_by_id(client_id)
  33. local bufnr = args.buf
  34. -- Only attach to clients that support document formatting
  35. if not client.server_capabilities.documentFormattingProvider then
  36. return
  37. end
  38. -- Tsserver usually works poorly. Sorry you work with bad languages
  39. -- You can remove this line if you know what you're doing :)
  40. if client.name == 'tsserver' then
  41. return
  42. end
  43. vim.api.nvim_create_autocmd('BufWritePre', {
  44. group = get_augroup(client),
  45. buffer = bufnr,
  46. callback = function()
  47. if not format_is_enabled then
  48. return
  49. end
  50. vim.lsp.buf.format { async = false }
  51. end,
  52. })
  53. end,
  54. })
  55. end,
  56. }