From 51075e9b41d1a79f145deb25d2ac5ff0d039256a Mon Sep 17 00:00:00 2001 From: Munif Tanjim Date: Thu, 25 Aug 2022 00:43:41 +0600 Subject: [PATCH] feat: support custom formatter --- lua/prettier/init.lua | 38 +++++++++++++++++++++++++++++++++++++- lua/prettier/null-ls.lua | 4 ++-- 2 files changed, 39 insertions(+), 3 deletions(-) diff --git a/lua/prettier/init.lua b/lua/prettier/init.lua index 7fac31e..3900d91 100644 --- a/lua/prettier/init.lua +++ b/lua/prettier/init.lua @@ -1,7 +1,9 @@ local options = require("prettier.options") local null_ls = require("prettier.null-ls") -local M = {} +local M = { + __ = {}, +} function M.setup(user_options) options.setup(user_options) @@ -14,4 +16,38 @@ function M.format(method) null_ls.format(method) end +function M.create_formatter(opts) + local command = opts.command + + M.__[command] = { + _fn = function(method) + if M.__[command].fn then + return M.__[command].fn(method) + end + end, + cmd = function(range) + if range > 0 then + M.__[command]._fn("textDocument/rangeFormatting") + else + M.__[command]._fn("textDocument/formatting") + end + end, + } + + vim.schedule(function() + local format = null_ls.create_formatter({ + bin = opts.bin, + bin_preference = opts.bin_preference, + cli_options = opts.cli_options, + ["null-ls"] = opts["null-ls"], + }) + + M.__[command].fn = format + + vim.cmd(string.format([[command! -range=%% %s :lua require("prettier").__["%s"].cmd()]], command, command)) + end) + + return M.__[command]._fn +end + return M diff --git a/lua/prettier/null-ls.lua b/lua/prettier/null-ls.lua index 46229da..fab1386 100644 --- a/lua/prettier/null-ls.lua +++ b/lua/prettier/null-ls.lua @@ -71,7 +71,7 @@ local function create_generator(opts) }) end -local function create_formatter(opts) +function M.create_formatter(opts) if not ok then return noop end @@ -161,7 +161,7 @@ local function create_formatter(opts) end function M.setup() - M.format = create_formatter({ + M.format = M.create_formatter({ bin = options.get("bin"), cli_options = options.get("cli_options"), ["null-ls"] = {