autoformat.lua 2.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  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. -- Whenever an LSP attaches to a buffer, we will run this function.
  28. --
  29. -- See `:help LspAttach` for more information about this autocmd event.
  30. vim.api.nvim_create_autocmd('LspAttach', {
  31. group = vim.api.nvim_create_augroup('kickstart-lsp-attach-format', { clear = true }),
  32. -- This is where we attach the autoformatting for reasonable clients
  33. callback = function(args)
  34. local client_id = args.data.client_id
  35. local client = vim.lsp.get_client_by_id(client_id)
  36. local bufnr = args.buf
  37. -- Only attach to clients that support document formatting
  38. if not client.server_capabilities.documentFormattingProvider then
  39. return
  40. end
  41. -- Tsserver usually works poorly. Sorry you work with bad languages
  42. -- You can remove this line if you know what you're doing :)
  43. if client.name == 'tsserver' then
  44. return
  45. end
  46. -- Create an autocmd that will run *before* we save the buffer.
  47. -- Run the formatting command for the LSP that has just attached.
  48. vim.api.nvim_create_autocmd('BufWritePre', {
  49. group = get_augroup(client),
  50. buffer = bufnr,
  51. callback = function()
  52. if not format_is_enabled then
  53. return
  54. end
  55. vim.lsp.buf.format {
  56. async = false,
  57. filter = function(c)
  58. return c.id == client.id
  59. end,
  60. }
  61. end,
  62. })
  63. end,
  64. })
  65. end,
  66. }