feat: Add Prettier formatter

This commit is contained in:
punkfairie 2025-01-03 20:55:49 -08:00
parent f7f9a74f65
commit e2dc45069b
Signed by: punkfairie
GPG key ID: A509E8F77FB9D696
4 changed files with 80 additions and 9 deletions

View file

@ -130,6 +130,7 @@ with final.pkgs.lib; let
shfmt
stylua
biome
nodePackages.prettier
];
in {
# This is the neovim derivation returned by the overlay.

View file

@ -2,6 +2,7 @@
local M = {}
M.lsp = require('lib.lsp')
M.prettier = require('lib.prettier')
---Find the root of a project based on `vim.g.root_spec`. Defaults to
---`{ '.git' }` if unset.

54
nvim/lua/lib/prettier.lua Normal file
View file

@ -0,0 +1,54 @@
---@class lib.prettier
local M = {}
---@alias ConformCtx {buf: number, filename: string, dirname: string}
M.supported = {
'css',
'graphql',
'handlebars',
'html',
'javascript',
'javascriptreact',
'json',
'jsonc',
'less',
'markdown',
'markdown.mdx',
'scss',
'typescript',
'typescriptreact',
'vue',
'yaml',
}
---Check if a parser exists for the given context.
---@param ctx ConformCtx
function M.has_parser(ctx)
local ft = vim.bo[ctx.buf].filetype --[[@as string]]
-- Default filetypes are always supported.
if vim.tbl_contains(M.supported, ft) then
return true
end
-- Otherwise, check if a parser can be inferred.
local inferred = vim.fn.system({ 'prettier', '--file-info', ctx.filename })
---@type boolean, string?
local ok, parser = pcall(function()
return vim.fn.json_decode(inferred).inferredParser
end)
return ok and parser and parser ~= vim.NIL
end
---Check if a Prettier config file exists in the current context.
---@param ctx ConformCtx
function M.has_config(ctx)
vim.fn.system({ 'prettier', '--find-config-path', ctx.filename })
return vim.v.shell_error == 0
end
return M

View file

@ -32,25 +32,40 @@ return {
return { timeout_ms = 3000, lsp_format = 'fallback' }
end,
-- Prettier is last but only activated if there is a config available,
-- thereby giving it priority only when it is wanted.
formatters_by_ft = {
css = { 'biome' },
css = { 'biome', 'prettier' },
fish = { 'fish_indent' },
graphql = { 'biome' },
javascript = { 'biome' },
javascriptreact = { 'biome' },
json = { 'biome' },
jsonc = { 'biome' },
graphql = { 'biome', 'prettier' },
handlebars = { 'prettier' },
html = { 'prettier' },
javascript = { 'biome', 'prettier' },
javascriptreact = { 'biome', 'prettier' },
json = { 'biome', 'prettier' },
jsonc = { 'biome', 'prettier' },
lua = { 'stylua' },
less = { 'prettier' },
markdown = { 'prettier' },
['markdown.mdx'] = { 'prettier' },
scss = { 'prettier' },
sh = { 'shfmt' },
typescript = { 'biome' },
typescriptreact = { 'biome' },
vue = { 'biome' },
typescript = { 'biome', 'prettier' },
typescriptreact = { 'biome', 'prettier' },
vue = { 'biome', 'prettier' },
yaml = { 'prettier' },
},
formatters = {
biome = {
require_cwd = true,
},
prettier = {
condition = function(_, ctx)
return MarleyVim.prettier.has_parser(ctx)
and MarleyVim.prettier.has_config(ctx)
end,
},
},
})