aboutsummaryrefslogtreecommitdiffstats
diff options
context:
space:
mode:
authorSteven Arcangeli <stevearc@stevearc.com>2024-07-19 09:11:01 -0700
committerSteven Arcangeli <stevearc@stevearc.com>2024-07-19 09:11:21 -0700
commit797de8f79055334104cf77893cd93fe3fc2ac154 (patch)
tree7e5fcbc8ddc593ebd0b84ad9d3dc97cf5322daa3
parentd60d41c34c9eacf8131685f28532e72f12f21482 (diff)
doc: recipe for running first available formatter and then others
-rw-r--r--README.md1
-rw-r--r--doc/recipes.md32
2 files changed, 33 insertions, 0 deletions
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)
<!-- /RECIPES -->
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)
<!-- /TOC -->
@@ -202,3 +203,34 @@ vim.keymap.set("", "<leader>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,
+ },
+})
+```