neovim configuration using rocks.nvim plugin manager
1local Util = require("utils")
2
3---@class bt.util.format
4local M = {}
5
6---@param buf? number
7---@return boolean
8function M.enabled(buf)
9 buf = (buf == nil or buf == 0) and vim.api.nvim_get_current_buf() or buf
10
11 -- autoformat options fallback. buffer > editorconfig > global
12 -- stylua: ignore
13 return vim.F.if_nil(
14 vim.b[buf].autoformat,
15 vim.b[buf].editorconfig_autoformat,
16 vim.g.autoformat
17 )
18end
19
20function M.toggle()
21 -- TODO: if editorconfig says autoformat in that buffer is enabled,
22 -- disable it with buffer-local variable
23 if vim.b.editorconfig_autoformat ~= nil or vim.b.autoformat ~= nil then
24 vim.b.autoformat = not M.enabled()
25 else
26 vim.g.autoformat = not M.enabled()
27 vim.b.autoformat = nil
28 end
29 M.info()
30end
31
32---@param buf? number
33function M.info(buf)
34 buf = buf or vim.api.nvim_get_current_buf()
35 Util.notify.info({
36 ("* Status *%s*"):format(M.enabled(buf) and "enabled" or "disabled"),
37 ("- (%s) global"):format(vim.g.autoformat and "x" or " "),
38 ("- (%s) editorconfig"):format(vim.b[buf].editorconfig_autoformat and "x" or " "),
39 ("- (%s) buffer"):format(vim.b[buf].autoformat and "x" or " "),
40 })
41end
42
43function M.setup()
44 vim.g.autoformat = false
45 -- Autoformat autocmd
46 vim.api.nvim_create_autocmd("BufWritePre", {
47 group = vim.api.nvim_create_augroup("AutoFormat", {}),
48 callback = function(event)
49 if M.enabled(event.buf) then
50 require("conform").format({
51 lsp_fallback = true,
52 async = false,
53 })
54 end
55 end,
56 })
57
58 vim.api.nvim_create_user_command("Format", function(args)
59 local range = nil
60 if args.count ~= -1 then
61 local end_line = vim.api.nvim_buf_get_lines(0, args.line2 - 1, args.line2, true)[1]
62 range = {
63 start = { args.line1, 0 },
64 ["end"] = { args.line2, end_line:len() },
65 }
66 end
67
68 local ok = require("conform").format({
69 lsp_fallback = true,
70 async = true,
71 range = range,
72 })
73 -- TODO: check that ranged-format failed
74 if not ok then
75 Util.notify.warn("No formatter available", { title = "Formatter" })
76 end
77 end, {
78 desc = "Format selection or buffer",
79 range = true,
80 })
81
82 vim.api.nvim_create_user_command("FormatInfo", function()
83 M.info()
84 end, { desc = "Show info about the formatters for the current buffer" })
85
86 vim.api.nvim_create_user_command("FormatToggle", function()
87 M.toggle()
88 end, { desc = "Toggle autoformat option" })
89end
90return M