Skip to content

Commit 51075e9

Browse files
committed
feat: support custom formatter
1 parent fca744c commit 51075e9

File tree

2 files changed

+39
-3
lines changed

2 files changed

+39
-3
lines changed

lua/prettier/init.lua

Lines changed: 37 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,9 @@
11
local options = require("prettier.options")
22
local null_ls = require("prettier.null-ls")
33

4-
local M = {}
4+
local M = {
5+
__ = {},
6+
}
57

68
function M.setup(user_options)
79
options.setup(user_options)
@@ -14,4 +16,38 @@ function M.format(method)
1416
null_ls.format(method)
1517
end
1618

19+
function M.create_formatter(opts)
20+
local command = opts.command
21+
22+
M.__[command] = {
23+
_fn = function(method)
24+
if M.__[command].fn then
25+
return M.__[command].fn(method)
26+
end
27+
end,
28+
cmd = function(range)
29+
if range > 0 then
30+
M.__[command]._fn("textDocument/rangeFormatting")
31+
else
32+
M.__[command]._fn("textDocument/formatting")
33+
end
34+
end,
35+
}
36+
37+
vim.schedule(function()
38+
local format = null_ls.create_formatter({
39+
bin = opts.bin,
40+
bin_preference = opts.bin_preference,
41+
cli_options = opts.cli_options,
42+
["null-ls"] = opts["null-ls"],
43+
})
44+
45+
M.__[command].fn = format
46+
47+
vim.cmd(string.format([[command! -range=%% %s :lua require("prettier").__["%s"].cmd(<range>)]], command, command))
48+
end)
49+
50+
return M.__[command]._fn
51+
end
52+
1753
return M

lua/prettier/null-ls.lua

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ local function create_generator(opts)
7171
})
7272
end
7373

74-
local function create_formatter(opts)
74+
function M.create_formatter(opts)
7575
if not ok then
7676
return noop
7777
end
@@ -161,7 +161,7 @@ local function create_formatter(opts)
161161
end
162162

163163
function M.setup()
164-
M.format = create_formatter({
164+
M.format = M.create_formatter({
165165
bin = options.get("bin"),
166166
cli_options = options.get("cli_options"),
167167
["null-ls"] = {

0 commit comments

Comments
 (0)