Add keymaps and commands for turning off/on auto formatting on save.

This commit is contained in:
Martin Larsson 2025-01-13 13:49:55 +01:00
parent e1d2f81f32
commit 56ee18a475
4 changed files with 51 additions and 2 deletions

View file

@ -28,6 +28,9 @@ require("terminal")
-- Initialize the custom window management functionality
require("window_management").setup()
-- Initializes custom commands and keybindings for handling code formatting
require("format_handler").setup()
-- Set configs for servers and enable them in the Neovim LSP Client
require("lsp/setup")

View file

@ -0,0 +1,44 @@
local utils = require("utils")
local M = {}
M.format_on_save = true
function M.format(force)
local do_force = force or false
if M.format_on_save or do_force then
vim.lsp.buf.format()
end
end
function M.format_enable()
M.format_on_save = true
end
function M.format_disable()
M.format_on_save = false
end
function M.setup()
local user_commands = {
{ "FormatEnable", "lua require('format_handler').format_enable()" },
{ "FormatDisable", "lua require('format_handler').format_disable()" },
}
for _, cmd in ipairs(user_commands) do
vim.api.nvim_command("command! " .. cmd[1] .. " " .. cmd[2])
end
utils.add_keymaps({
n = {
["<leader>ff"] = {
cmd = function() M.format(true) end
},
["<leader>fe"] = {
cmd = M.format_enable,
},
["<leader>fd"] = {
cmd = M.format_disable,
},
},
})
end
return M

View file

@ -1,5 +1,6 @@
local utils = require("utils")
local inlay_hints_handler = require("inlay_hints_handler")
local format_handler = require("format_handler")
local function chain_on_attach(...)
local funcs = { ... }
@ -18,7 +19,7 @@ local function global_on_attach(client, bufnr)
vim.api.nvim_create_autocmd("BufWritePre", {
buffer = bufnr,
callback = function()
vim.lsp.buf.format()
format_handler.format()
end,
})
end

View file

@ -1,5 +1,6 @@
local utils = require("utils")
local inlay_hints_handler = require("inlay_hints_handler")
local format_handler = require("format_handler")
return {
"mrcjkb/rustaceanvim",
@ -24,7 +25,7 @@ return {
vim.api.nvim_create_autocmd("BufWritePre", {
buffer = bufnr,
callback = function()
vim.lsp.buf.format()
format_handler.format()
end,
})
end