Skip to content

Commit

Permalink
feat(functions): auto format on save by ESLint if possible
Browse files Browse the repository at this point in the history
  • Loading branch information
ecosse3 committed Sep 29, 2023
1 parent 5c9ecb0 commit d9edbcc
Showing 1 changed file with 27 additions and 8 deletions.
35 changes: 27 additions & 8 deletions lua/lsp/functions.lua
Original file line number Diff line number Diff line change
@@ -1,14 +1,33 @@
local M = {}

function M.enable_format_on_save()
local group = vim.api.nvim_create_augroup("format_on_save", { clear = false })
vim.api.nvim_create_autocmd("BufWritePre", {
callback = function()
vim.lsp.buf.format()
end,
group = group,
})
require("notify")("Enabled format on save", "info", { title = "LSP", timeout = 2000 })
local group = vim.api.nvim_create_augroup("format_on_save", { clear = false })
vim.api.nvim_create_autocmd("BufWritePre", {
callback = function()
local root_dir = vim.fn.getcwd() -- Adjust this if you have a more accurate way to find the project root
local eslintrc_json = root_dir .. "/.eslintrc.json"
local eslintrc_js = root_dir .. "/.eslintrc.js"

-- Check if eslint LSP is active
local active_clients = vim.lsp.buf_get_clients()
local eslint_is_active = false

for _, client in ipairs(active_clients) do
if client.name == "eslint" then
eslint_is_active = true
break
end
end

if eslint_is_active and (vim.fn.filereadable(eslintrc_json) == 1 or vim.fn.filereadable(eslintrc_js) == 1) then
vim.cmd("EslintFixAll")
else
vim.lsp.buf.format()
end
end,
group = group,
})
require("notify")("Enabled format on save", "info", { title = "LSP", timeout = 2000 })
end

function M.disable_format_on_save()
Expand Down

0 comments on commit d9edbcc

Please sign in to comment.