From 797de8f79055334104cf77893cd93fe3fc2ac154 Mon Sep 17 00:00:00 2001 From: Steven Arcangeli Date: Fri, 19 Jul 2024 09:11:01 -0700 Subject: doc: recipe for running first available formatter and then others --- README.md | 1 + doc/recipes.md | 32 ++++++++++++++++++++++++++++++++ 2 files changed, 33 insertions(+) diff --git a/README.md b/README.md index e7860de..00abfa4 100644 --- a/README.md +++ b/README.md @@ -434,6 +434,7 @@ require("conform").formatters.shfmt = { - [Automatically run slow formatters async](doc/recipes.md#automatically-run-slow-formatters-async) - [Lazy loading with lazy.nvim](doc/recipes.md#lazy-loading-with-lazynvim) - [Leave visual mode after range format](doc/recipes.md#leave-visual-mode-after-range-format) +- [Run the first available formatter followed by more formatters](doc/recipes.md#run-the-first-available-formatter-followed-by-more-formatters) diff --git a/doc/recipes.md b/doc/recipes.md index 0c085f2..3c230b3 100644 --- a/doc/recipes.md +++ b/doc/recipes.md @@ -8,6 +8,7 @@ - [Automatically run slow formatters async](#automatically-run-slow-formatters-async) - [Lazy loading with lazy.nvim](#lazy-loading-with-lazynvim) - [Leave visual mode after range format](#leave-visual-mode-after-range-format) +- [Run the first available formatter followed by more formatters](#run-the-first-available-formatter-followed-by-more-formatters) @@ -202,3 +203,34 @@ vim.keymap.set("", "f", function() end) end, { desc = "Format code" }) ``` + +## Run the first available formatter followed by more formatters + +With the refactor in [#491](https://github.com/stevearc/conform.nvim/pull/491) it is now easy to +just run the first available formatter in a list, but more difficult to do that _and then_ run +another formatter. For example, "format first with either `prettierd` or `prettier`, _then_ use the +`injected` formatter". Here is how you can easily do that: + +```lua +---@param bufnr integer +---@param ... string +---@return string +local function first(bufnr, ...) + local conform = require("conform") + for i = 1, select("#", ...) do + local formatter = select(i, ...) + if conform.get_formatter_info(formatter, bufnr).available then + return formatter + end + end + return select(1, ...) +end + +require("conform").setup({ + formatters_by_ft = { + markdown = function(bufnr) + return { first(bufnr, "prettierd", "prettier"), "injected" } + end, + }, +}) +``` -- cgit v1.2.3-70-g09d2