3 -- Use your language server to automatically format your code on save.
4 -- Adds additional commands as well to manage the behavior
7 'neovim/nvim-lspconfig',
9 -- Switch for controlling whether you want autoformatting.
10 -- Use :KickstartFormatToggle to toggle autoformatting on or off
11 local format_is_enabled = true
12 vim.api.nvim_create_user_command('KickstartFormatToggle', function()
13 format_is_enabled = not format_is_enabled
14 print('Setting autoformatting to: ' .. tostring(format_is_enabled))
17 -- Create an augroup that is used for managing our formatting autocmds.
18 -- We need one augroup per client to make sure that multiple clients
19 -- can attach to the same buffer without interfering with each other.
21 local get_augroup = function(client)
22 if not _augroups[client.id] then
23 local group_name = 'kickstart-lsp-format-' .. client.name
24 local id = vim.api.nvim_create_augroup(group_name, { clear = true })
25 _augroups[client.id] = id
28 return _augroups[client.id]
31 -- Whenever an LSP attaches to a buffer, we will run this function.
33 -- See `:help LspAttach` for more information about this autocmd event.
34 vim.api.nvim_create_autocmd('LspAttach', {
35 group = vim.api.nvim_create_augroup('kickstart-lsp-attach-format', { clear = true }),
36 -- This is where we attach the autoformatting for reasonable clients
37 callback = function(args)
38 local client_id = args.data.client_id
39 local client = vim.lsp.get_client_by_id(client_id)
40 local bufnr = args.buf
42 -- Only attach to clients that support document formatting
43 if not client.server_capabilities.documentFormattingProvider then
47 -- Tsserver usually works poorly. Sorry you work with bad languages
48 -- You can remove this line if you know what you're doing :)
49 -- if client.name == 'tsserver' then
53 -- Create an autocmd that will run *before* we save the buffer.
54 -- Run the formatting command for the LSP that has just attached.
55 vim.api.nvim_create_autocmd('BufWritePre', {
56 group = get_augroup(client),
59 if not format_is_enabled then
66 return c.id == client.id