format.lua (2070B)
1 if not pcall(require, 'conform') then 2 return 3 end 4 5 local prettier = { 'prettier' } 6 local shfmt = { 'shfmt' } 7 require 'conform'.setup { 8 formatters_by_ft = { 9 dart = { 'injected' }, 10 python = { 'autopep8' }, 11 sh = shfmt, 12 bash = shfmt, 13 zsh = shfmt, 14 yaml = prettier, 15 json = prettier, 16 markdown = prettier, 17 html = prettier, 18 htmlangular = prettier, 19 css = prettier, 20 graphql = prettier, 21 scss = prettier, 22 xml = { 'xmlformat' }, 23 }, 24 formatters = { 25 prettier = { 26 args = { '--stdin-filepath', '$FILENAME' }, 27 range_args = function(_, ctx) 28 local args = { '$FILENAME' } 29 local start_offset, end_offset = require "conform.util".get_offsets_from_range(ctx.buf, ctx.range) 30 return vim.list_extend(args, { 31 "--range-start=" .. start_offset, 32 "--range-end=" .. end_offset, 33 }) 34 end, 35 } 36 }, 37 } 38 39 vim.o.formatexpr = "v:lua.require'conform'.formatexpr({'lsp_fallback': 'always'})" 40 41 vim.api.nvim_create_autocmd("BufWritePre", { 42 pattern = "*", 43 callback = function(args) 44 -- Disable with a global or buffer-local variable 45 if vim.g.disable_autoformat or vim.b[args.buf].disable_autoformat then 46 return 47 end 48 require("conform").format({ bufnr = args.buf, lsp_fallback = "always", timeout_ms = 500 }) 49 end, 50 }) 51 52 vim.keymap.set('n', 'gQ', function() 53 require 'conform'.format { lsp_fallback = "always" } 54 end, { desc = 'Format' }) 55 56 vim.api.nvim_create_user_command("Format", function() 57 require 'conform'.format { lsp_fallback = "always" } 58 end, { desc = "Format" }) 59 60 vim.api.nvim_create_user_command("FormatDisable", function(args) 61 if args.bang then 62 -- FormatDisable! will disable formatting just for this buffer 63 vim.b.disable_autoformat = true 64 else 65 vim.g.disable_autoformat = true 66 end 67 end, { 68 desc = "Disable autoformat-on-save", 69 bang = true, 70 }) 71 72 vim.api.nvim_create_user_command("FormatEnable", function() 73 vim.b.disable_autoformat = false 74 vim.g.disable_autoformat = false 75 end, { 76 desc = "Re-enable autoformat-on-save", 77 })