Skip to content

Commit

Permalink
feat(prettier): add options for configuring prettier parser based o…
Browse files Browse the repository at this point in the history
…n filetype and extension (#241)
  • Loading branch information
mehalter authored Dec 10, 2023
1 parent 48bc999 commit 8df1bed
Showing 1 changed file with 49 additions and 2 deletions.
51 changes: 49 additions & 2 deletions lua/conform/formatters/prettier.lua
Original file line number Diff line number Diff line change
@@ -1,15 +1,62 @@
local util = require("conform.util")

--- Helper function to parse options to into a parser if available
---@param self conform.JobFormatterConfig
---@param ctx conform.Context|conform.RangeContext
---@return string[]|nil args the arguments for setting a `prettier` parser if they exist in the options, nil otherwise
local function eval_parser(self, ctx)
local ft = vim.bo[ctx.buf].filetype
local ext = vim.fn.fnamemodify(ctx.filename, ":e")
local options = self.options
local parser = options
and (
(options.ft_parsers and options.ft_parsers[ft])
or (options.ext_parsers and options.ext_parsers[ext])
)
if parser then
return { "--parser", parser }
end
end

---@type conform.FileFormatterConfig
return {
meta = {
url = "https://github.com/prettier/prettier",
description = [[Prettier is an opinionated code formatter. It enforces a consistent style by parsing your code and re-printing it with its own rules that take the maximum line length into account, wrapping code when necessary.]],
},
options = {
-- add parsers for different filetypes
ft_parsers = {
-- javascript = "babel",
-- javascriptreact = "babel",
-- typescript = "typescript",
-- typescriptreact = "typescript",
-- vue = "vue",
-- css = "css",
-- scss = "scss",
-- less = "less",
-- html = "html",
-- json = "json",
-- jsonc = "json",
-- yaml = "yaml",
-- markdown = "markdown",
-- ["markdown.mdx"] = "mdx",
-- graphql = "graphql",
-- handlebars = "glimmer",
},
-- add parsers for different extensions
ext_parsers = {
-- qmd = "markdown",
},
},
command = util.from_node_modules("prettier"),
args = { "--stdin-filepath", "$FILENAME" },
args = function(self, ctx)
return eval_parser(self, ctx) or { "--stdin-filepath", "$FILENAME" }
end,
range_args = function(self, ctx)
local start_offset, end_offset = util.get_offsets_from_range(ctx.buf, ctx.range)
return { "$FILENAME", "--range-start=" .. start_offset, "--range-end=" .. end_offset }
local args = eval_parser(self, ctx) or { "$FILENAME" }
return vim.list_extend(args, { "--range-start=" .. start_offset, "--range-end=" .. end_offset })
end,
cwd = util.root_file({
-- https://prettier.io/docs/en/configuration.html
Expand Down

0 comments on commit 8df1bed

Please sign in to comment.