1

Regenerate nvim config

This commit is contained in:
2024-06-02 03:29:20 +02:00
parent 75eea0c030
commit ef2e28883d
5576 changed files with 604886 additions and 503 deletions

View File

@ -0,0 +1,31 @@
# Advanced topics
<!-- TOC -->
- [Minimal format diffs](#minimal-format-diffs)
- [Range formatting](#range-formatting)
- [Injected language formatting (code blocks)](#injected-language-formatting-code-blocks)
<!-- /TOC -->
## Minimal format diffs
To understand why this is important and why conform.nvim is different we need a bit of historical context. Formatting tools work by taking in the current state of the file and outputting the same contents, with formatting applied. The way most formatting plugins work is they take the new content and replace the entire buffer. The benefit of this approach is that it's very simple. It's easy to code, it's easy to reason about, and it's easy to debug.
What conform does differently is it leverages `:help vim.diff`, Neovim's lua bindings for xdiff. We use this to compare the formatted lines to the original content and calculate minimal chunks where changes need to be applied. From there, we convert these chunks into LSP TextEdit objects and use `vim.lsp.util.apply_text_edits()` to actually apply the changes. Since we're using the built-in LSP utility, we get the benefits of all the work that was put into improving the LSP formatting experience, such as the preservation of extmarks. The piecewise update also does a better job of preserving cursor position, folds, viewport position, etc.
## Range formatting
When a formatting tool doesn't have built-in support for range formatting, conform will attempt to "fake it" when requested. This is necessarily a **best effort** operation and is **not** guaranteed to be correct or error-free, however in _most_ cases it should produce acceptable results.
The way this "aftermarket" range formatting works is conform will format the entire buffer as per usual, but during the diff process it will discard diffs that fall outside of the selected range. This usually approximates a correct result, but as you can guess it's possible for the formatting to exceed the range (if the diff covering the range is large) or for the results to be incorrect (if the formatting changes require two diffs in different locations to be semantically correct).
## Injected language formatting (code blocks)
Requires: Neovim 0.9+
Sometimes you may have a file that contains small chunks of code in another language. This is most common for markup formats like markdown and neorg, but can theoretically be present in any filetype (for example, embedded SQL queries in a host language). For files like this, it would be nice to be able to format these code chunks using their language-specific formatters.
The way that conform supports this is via the `injected` formatter. If you run this formatter on a file, it will use treesitter to parse out the blocks in the file that have different languages and runs the formatters for that filetype (configured with `formatters_by_ft`). The formatters are run in parallel, one job for each language block.
This formatter is experimental; the behavior and configuration options are still subject to change. The current list of configuration options can be found at [formatter options](formatter_options.md#injected)

View File

@ -0,0 +1,413 @@
*conform.txt*
*Conform* *conform* *conform.nvim*
--------------------------------------------------------------------------------
CONTENTS *conform-contents*
1. Options |conform-options|
2. Api |conform-api|
3. Formatters |conform-formatters|
--------------------------------------------------------------------------------
OPTIONS *conform-options*
>lua
require("conform").setup({
-- Map of filetype to formatters
formatters_by_ft = {
lua = { "stylua" },
-- Conform will run multiple formatters sequentially
go = { "goimports", "gofmt" },
-- Use a sub-list to run only the first available formatter
javascript = { { "prettierd", "prettier" } },
-- You can use a function here to determine the formatters dynamically
python = function(bufnr)
if require("conform").get_formatter_info("ruff_format", bufnr).available then
return { "ruff_format" }
else
return { "isort", "black" }
end
end,
-- Use the "*" filetype to run formatters on all filetypes.
["*"] = { "codespell" },
-- Use the "_" filetype to run formatters on filetypes that don't
-- have other formatters configured.
["_"] = { "trim_whitespace" },
},
-- If this is set, Conform will run the formatter on save.
-- It will pass the table to conform.format().
-- This can also be a function that returns the table.
format_on_save = {
-- I recommend these options. See :help conform.format for details.
lsp_fallback = true,
timeout_ms = 500,
},
-- If this is set, Conform will run the formatter asynchronously after save.
-- It will pass the table to conform.format().
-- This can also be a function that returns the table.
format_after_save = {
lsp_fallback = true,
},
-- Set the log level. Use `:ConformInfo` to see the location of the log file.
log_level = vim.log.levels.ERROR,
-- Conform will notify you when a formatter errors
notify_on_error = true,
-- Custom formatters and overrides for built-in formatters
formatters = {
my_formatter = {
-- This can be a string or a function that returns a string.
-- When defining a new formatter, this is the only field that is required
command = "my_cmd",
-- A list of strings, or a function that returns a list of strings
-- Return a single string instead of a list to run the command in a shell
args = { "--stdin-from-filename", "$FILENAME" },
-- If the formatter supports range formatting, create the range arguments here
range_args = function(self, ctx)
return { "--line-start", ctx.range.start[1], "--line-end", ctx.range["end"][1] }
end,
-- Send file contents to stdin, read new contents from stdout (default true)
-- When false, will create a temp file (will appear in "$FILENAME" args). The temp
-- file is assumed to be modified in-place by the format command.
stdin = true,
-- A function that calculates the directory to run the command in
cwd = require("conform.util").root_file({ ".editorconfig", "package.json" }),
-- When cwd is not found, don't run the formatter (default false)
require_cwd = true,
-- When stdin=false, use this template to generate the temporary file that gets formatted
tmpfile_format = ".conform.$RANDOM.$FILENAME",
-- When returns false, the formatter will not be used
condition = function(self, ctx)
return vim.fs.basename(ctx.filename) ~= "README.md"
end,
-- Exit codes that indicate success (default { 0 })
exit_codes = { 0, 1 },
-- Environment variables. This can also be a function that returns a table.
env = {
VAR = "value",
},
-- Set to false to disable merging the config with the base definition
inherit = true,
-- When inherit = true, add these additional arguments to the command.
-- This can also be a function, like args
prepend_args = { "--use-tabs" },
},
-- These can also be a function that returns the formatter
other_formatter = function(bufnr)
return {
command = "my_cmd",
}
end,
},
})
-- You can set formatters_by_ft and formatters directly
require("conform").formatters_by_ft.lua = { "stylua" }
require("conform").formatters.my_formatter = {
command = "my_cmd",
}
<
--------------------------------------------------------------------------------
API *conform-api*
setup({opts}) *conform.setup*
Parameters:
{opts} `nil|conform.setupOpts`
{formatters_by_ft} `nil|table<string, conform.FiletypeFormatter>` Map
of filetype to formatters
{format_on_save} `nil|conform.FormatOpts|fun(bufnr: integer): conform.FormatOpts` I
f this is set, Conform will run the formatter on
save. It will pass the table to conform.format().
This can also be a function that returns the table.
{format_after_save} `nil|conform.FormatOpts|fun(bufnr: integer): conform.FormatOpts` I
f this is set, Conform will run the formatter
asynchronously after save. It will pass the table
to conform.format(). This can also be a function
that returns the table.
{log_level} `nil|integer` Set the log level (e.g.
`vim.log.levels.DEBUG`). Use `:ConformInfo` to see
the location of the log file.
{notify_on_error} `nil|boolean` Conform will notify you when a
formatter errors (default true).
{formatters} `nil|table<string, conform.FormatterConfigOverride|fun(bufnr: integer): nil|conform.FormatterConfigOverride>` C
ustom formatters and overrides for built-in
formatters.
format({opts}, {callback}): boolean *conform.format*
Format a buffer
Parameters:
{opts} `nil|conform.FormatOpts`
{timeout_ms} `nil|integer` Time in milliseconds to block for
formatting. Defaults to 1000. No effect if async =
true.
{bufnr} `nil|integer` Format this buffer (default 0)
{async} `nil|boolean` If true the method won't block. Defaults
to false. If the buffer is modified before the
formatter completes, the formatting will be discarded.
{dry_run} `nil|boolean` If true don't apply formatting changes to
the buffer
{formatters} `nil|string[]` List of formatters to run. Defaults to
all formatters for the buffer filetype.
{lsp_fallback} `nil|boolean|"always"` Attempt LSP formatting if no
formatters are available. Defaults to false. If
"always", will attempt LSP formatting even if
formatters are available.
{quiet} `nil|boolean` Don't show any notifications for warnings
or failures. Defaults to false.
{range} `nil|table` Range to format. Table must contain `start`
and `end` keys with {row, col} tuples using (1,0)
indexing. Defaults to current selection in visual mode
{id} `nil|integer` Passed to |vim.lsp.buf.format| when
lsp_fallback = true
{name} `nil|string` Passed to |vim.lsp.buf.format| when
lsp_fallback = true
{filter} `nil|fun(client: table): boolean` Passed to
|vim.lsp.buf.format| when lsp_fallback = true
{callback} `nil|fun(err: nil|string, did_edit: nil|boolean)` Called once
formatting has completed
Returns:
`boolean` True if any formatters were attempted
list_formatters({bufnr}): conform.FormatterInfo[] *conform.list_formatters*
Retrieve the available formatters for a buffer
Parameters:
{bufnr} `nil|integer`
list_all_formatters(): conform.FormatterInfo[] *conform.list_all_formatters*
List information about all filetype-configured formatters
get_formatter_info({formatter}, {bufnr}): conform.FormatterInfo *conform.get_formatter_info*
Get information about a formatter (including availability)
Parameters:
{formatter} `string` The name of the formatter
{bufnr} `nil|integer`
will_fallback_lsp({options}): boolean *conform.will_fallback_lsp*
Check if the buffer will use LSP formatting when lsp_fallback = true
Parameters:
{options} `nil|table` Options passed to |vim.lsp.buf.format|
--------------------------------------------------------------------------------
FORMATTERS *conform-formatters*
`alejandra` - The Uncompromising Nix Code Formatter.
`asmfmt` - Go Assembler Formatter
`ast-grep` - A CLI tool for code structural search, lint and rewriting. Written
in Rust.
`astyle` - A Free, Fast, and Small Automatic Formatter for C, C++, C++/CLI,
Objective-C, C#, and Java Source Code.
`auto_optional` - Adds the Optional type-hint to arguments where the default
value is None.
`autocorrect` - A linter and formatter to help you to improve copywriting,
correct spaces, words, and punctuations between CJK.
`autoflake` - Removes unused imports and unused variables as reported by
pyflakes.
`autopep8` - A tool that automatically formats Python code to conform to the PEP
8 style guide.
`awk` - Format awk programs with awk
`bean-format` - Reformat Beancount files to right-align all the numbers at the
same, minimal column.
`beautysh` - A Bash beautifier for the masses.
`bibtex-tidy` - Cleaner and Formatter for BibTeX files.
`bicep` - Bicep is a Domain Specific Language (DSL) for deploying Azure
resources declaratively.
`biome` - A toolchain for web projects, aimed to provide functionalities to
maintain them.
`biome-check` - A toolchain for web projects, aimed to provide functionalities
to maintain them.
`black` - The uncompromising Python code formatter.
`blade-formatter` - An opinionated blade template formatter for Laravel that
respects readability.
`blue` - The slightly less uncompromising Python code formatter.
`bpfmt` - Android Blueprint file formatter.
`buf` - A new way of working with Protocol Buffers.
`buildifier` - buildifier is a tool for formatting bazel BUILD and .bzl files
with a standard convention.
`cabal_fmt` - Format cabal files with cabal-fmt
`cbfmt` - A tool to format codeblocks inside markdown and org documents.
`clang-format` - Tool to format C/C++/… code according to a set of rules and
heuristics.
`cljstyle` - Formatter for Clojure code.
`cmake_format` - Parse cmake listfiles and format them nicely.
`codespell` - Check code for common misspellings.
`crystal` - Format Crystal code.
`csharpier` - The opinionated C# code formatter.
`cue_fmt` - Format CUE files using `cue fmt` command.
`darker` - Run black only on changed lines.
`dart_format` - Replace the whitespace in your program with formatting that
follows Dart guidelines.
`deno_fmt` - Use [Deno](https://deno.land/) to format TypeScript,
JavaScript/JSON and markdown.
`dfmt` - Formatter for D source code.
`djlint` - ✨ HTML Template Linter and Formatter. Django - Jinja - Nunjucks -
Handlebars - GoLang.
`dprint` - Pluggable and configurable code formatting platform written in Rust.
`easy-coding-standard` - ecs - Use Coding Standard with 0-knowledge of PHP-CS-
Fixer and PHP_CodeSniffer.
`elm_format` - elm-format formats Elm source code according to a standard set of
rules based on the official [Elm Style Guide](https://elm-
lang.org/docs/style-guide).
`erb_format` - Format ERB files with speed and precision.
`eslint_d` - Like ESLint, but faster.
`fantomas` - F# source code formatter.
`fish_indent` - Indent or otherwise prettify a piece of fish code.
`fixjson` - JSON Fixer for Humans using (relaxed) JSON5.
`fnlfmt` - A formatter for Fennel code.
`forge_fmt` - Forge is a command-line tool that ships with Foundry. Forge tests,
builds, and deploys your smart contracts.
`fourmolu` - A fork of ormolu that uses four space indentation and allows
arbitrary configuration.
`gci` - GCI, a tool that controls Go package import order and makes it always
deterministic.
`gdformat` - A formatter for Godot's gdscript.
`gersemi` - A formatter to make your CMake code the real treasure.
`gleam` - ⭐️ A friendly language for building type-safe, scalable systems!
`gn` - gn build system.
`gofmt` - Formats go programs.
`gofumpt` - Enforce a stricter format than gofmt, while being backwards
compatible. That is, gofumpt is happy with a subset of the formats
that gofmt is happy with.
`goimports` - Updates your Go import lines, adding missing ones and removing
unreferenced ones.
`goimports-reviser` - Right imports sorting & code formatting tool (goimports
alternative).
`golines` - A golang formatter that fixes long lines.
`google-java-format` - Reformats Java source code according to Google Java
Style.
`hcl` - A formatter for HCL files.
`htmlbeautifier` - A normaliser/beautifier for HTML that also understands
embedded Ruby. Ideal for tidying up Rails templates.
`indent` - GNU Indent.
`injected` - Format treesitter injected languages.
`inko` - A language for building concurrent software with confidence
`isort` - Python utility / library to sort imports alphabetically and
automatically separate them into sections and by type.
`joker` - Small Clojure interpreter, linter and formatter.
`jq` - Command-line JSON processor.
`jsonnetfmt` - jsonnetfmt is a command line tool to format jsonnet files.
`just` - Format Justfile.
`ktfmt` - Reformats Kotlin source code to comply with the common community
standard conventions.
`ktlint` - An anti-bikeshedding Kotlin linter with built-in formatter.
`latexindent` - A perl script for formatting LaTeX files that is generally
included in major TeX distributions.
`leptosfmt` - A formatter for the Leptos view! macro.
`liquidsoap-prettier` - A binary to format Liquidsoap scripts
`markdown-toc` - API and CLI for generating a markdown TOC (table of contents)
for a README or any markdown files.
`markdownlint` - A Node.js style checker and lint tool for Markdown/CommonMark
files.
`markdownlint-cli2` - A fast, flexible, configuration-based command-line
interface for linting Markdown/CommonMark files with the
markdownlint library.
`mdformat` - An opinionated Markdown formatter.
`mdsf` - Format markdown code blocks using your favorite code formatters.
`mdslw` - Prepare your markdown for easy diff'ing by adding line breaks after
every sentence.
`mix` - Format Elixir files using the mix format command.
`nimpretty` - nimpretty is a Nim source code beautifier that follows the
official style guide.
`nixfmt` - nixfmt is a formatter for Nix code, intended to apply a uniform
style.
`nixpkgs_fmt` - nixpkgs-fmt is a Nix code formatter for nixpkgs.
`ocamlformat` - Auto-formatter for OCaml code.
`ocp-indent` - Automatic indentation of OCaml source files.
`opa_fmt` - Format Rego files using `opa fmt` command.
`ormolu` - A formatter for Haskell source code.
`packer_fmt` - The packer fmt Packer command is used to format HCL2
configuration files to a canonical format and style.
`pangu` - Insert whitespace between CJK and half-width characters.
`perlimports` - Make implicit Perl imports explicit.
`perltidy` - Perl::Tidy, a source code formatter for Perl.
`pg_format` - PostgreSQL SQL syntax beautifier.
`php_cs_fixer` - The PHP Coding Standards Fixer.
`phpcbf` - PHP Code Beautifier and Fixer fixes violations of a defined coding
standard.
`phpinsights` - The perfect starting point to analyze the code quality of your
PHP projects.
`pint` - Laravel Pint is an opinionated PHP code style fixer for minimalists.
`prettier` - 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.
`prettierd` - prettier, as a daemon, for ludicrous formatting speed.
`pretty-php` - The opinionated PHP code formatter.
`puppet-lint` - Check that your Puppet manifests conform to the style guide.
`purs-tidy` - A syntax tidy-upper for PureScript.
`reorder-python-imports` - Rewrites source to reorder python imports
`rescript-format` - The built-in ReScript formatter.
`roc` - A fast, friendly, functional language.
`rubocop` - Ruby static code analyzer and formatter, based on the community Ruby
style guide.
`rubyfmt` - Ruby Autoformatter! (Written in Rust)
`ruff_fix` - An extremely fast Python linter, written in Rust. Fix lint errors.
`ruff_format` - An extremely fast Python linter, written in Rust. Formatter
subcommand.
`ruff_organize_imports` - An extremely fast Python linter, written in Rust.
Organize imports.
`rufo` - Rufo is an opinionated ruby formatter.
`rustfmt` - A tool for formatting rust code according to style guidelines.
`rustywind` - A tool for formatting Tailwind CSS classes.
`scalafmt` - Code formatter for Scala.
`shellcheck` - A static analysis tool for shell scripts.
`shellharden` - The corrective bash syntax highlighter.
`shfmt` - A shell parser, formatter, and interpreter with `bash` support.
`smlfmt` - A custom parser and code formatter for Standard ML.
`snakefmt` - a formatting tool for Snakemake files following the design of
Black.
`sql_formatter` - A whitespace formatter for different query languages.
`sqlfluff` - A modular SQL linter and auto-formatter with support for multiple
dialects and templated code.
`sqlfmt` - sqlfmt formats your dbt SQL files so you don't have to. It is similar
in nature to Black, gofmt, and rustfmt (but for SQL)
`squeeze_blanks` - Squeeze repeated blank lines into a single blank line via
`cat -s`.
`standardjs` - JavaScript Standard style guide, linter, and formatter.
`standardrb` - Ruby's bikeshed-proof linter and formatter.
`stylelint` - A mighty CSS linter that helps you avoid errors and enforce
conventions.
`styler` - R formatter and linter.
`stylua` - An opinionated code formatter for Lua.
`swift_format` - Swift formatter from apple. Requires building from source with
`swift build`.
`swiftformat` - SwiftFormat is a code library and command-line tool for
reformatting `swift` code on macOS or Linux.
`taplo` - A TOML toolkit written in Rust.
`templ` - Formats templ template files.
`terraform_fmt` - The terraform-fmt command rewrites `terraform` configuration
files to a canonical format and style.
`terragrunt_hclfmt` - Format hcl files into a canonical format.
`tlint` - Tighten linter for Laravel conventions with support for auto-
formatting.
`tofu_fmt` - The tofu-fmt command rewrites OpenTofu configuration files to a
canonical format and style.
`trim_newlines` - Trim new lines with awk.
`trim_whitespace` - Trim whitespaces with awk.
`twig-cs-fixer` - Automatically fix Twig Coding Standards issues
`typos` - Source code spell checker
`typstfmt` - Basic formatter for the Typst language with a future!
`typstyle` - Beautiful and reliable typst code formatter.
`uncrustify` - A source code beautifier for C, C++, C#, ObjectiveC, D, Java,
Pawn and Vala.
`usort` - Safe, minimal import sorting for Python projects.
`verible` - The SystemVerilog formatter.
`xmlformat` - xmlformatter is an Open Source Python package, which provides
formatting of XML documents.
`xmllint` - Despite the name, xmllint can be used to format XML files as well as
lint them.
`yamlfix` - A configurable YAML formatter that keeps comments.
`yamlfmt` - yamlfmt is an extensible command line tool or library to format yaml
files.
`yapf` - Yet Another Python Formatter.
`yew-fmt` - Code formatter for the Yew framework.
`yq` - YAML/JSON processor
`zigfmt` - Reformat Zig source into canonical form.
`zprint` - Formatter for Clojure and EDN.
================================================================================
vim:tw=80:ts=2:ft=help:norl:syntax=help:

View File

@ -0,0 +1,108 @@
# Formatter Options
<!-- TOC -->
- [injected](#injected)
- [prettier](#prettier)
- [rustfmt](#rustfmt)
- [yew-fmt](#yew-fmt)
<!-- /TOC -->
All formatters can be customized by directly changing the command, args, or other values (see [customizing formatters](../README.md#customizing-formatters)). Some formatters have a bit more advanced logic built in to those functions and expose additional configuration options. You can pass these values in like so:
```lua
-- Customize the "injected" formatter
require("conform").formatters.injected = {
-- Set the options field
options = {
-- Set individual option values
ignore_errors = true,
lang_to_formatters = {
json = { "jq" },
},
},
}
```
<!-- OPTIONS -->
## injected
```lua
options = {
-- Set to true to ignore errors
ignore_errors = false,
-- Map of treesitter language to file extension
-- A temporary file name with this extension will be generated during formatting
-- because some formatters care about the filename.
lang_to_ext = {
bash = "sh",
c_sharp = "cs",
elixir = "exs",
javascript = "js",
julia = "jl",
latex = "tex",
markdown = "md",
python = "py",
ruby = "rb",
rust = "rs",
teal = "tl",
typescript = "ts",
},
-- Map of treesitter language to formatters to use
-- (defaults to the value from formatters_by_ft)
lang_to_formatters = {},
}
```
## prettier
```lua
options = {
-- Use a specific prettier parser for a filetype
-- Otherwise, prettier will try to infer the parser from the file name
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",
},
-- Use a specific prettier parser for a file extension
ext_parsers = {
-- qmd = "markdown",
},
}
```
## rustfmt
```lua
options = {
-- The default edition of Rust to use when no Cargo.toml file is found
default_edition = "2021",
}
```
## yew-fmt
```lua
options = {
-- The default edition of Rust to use when no Cargo.toml file is found
default_edition = "2021",
}
```
<!-- /OPTIONS -->

View File

@ -0,0 +1,180 @@
# Recipes
<!-- TOC -->
- [Format command](#format-command)
- [Autoformat with extra features](#autoformat-with-extra-features)
- [Command to toggle format-on-save](#command-to-toggle-format-on-save)
- [Automatically run slow formatters async](#automatically-run-slow-formatters-async)
- [Lazy loading with lazy.nvim](#lazy-loading-with-lazynvim)
<!-- /TOC -->
## Format command
Define a command to run async formatting
```lua
vim.api.nvim_create_user_command("Format", function(args)
local range = nil
if args.count ~= -1 then
local end_line = vim.api.nvim_buf_get_lines(0, args.line2 - 1, args.line2, true)[1]
range = {
start = { args.line1, 0 },
["end"] = { args.line2, end_line:len() },
}
end
require("conform").format({ async = true, lsp_fallback = true, range = range })
end, { range = true })
```
## Autoformat with extra features
If you want more complex logic than the basic `format_on_save` option allows, you can use a function instead.
<!-- AUTOFORMAT -->
```lua
-- if format_on_save is a function, it will be called during BufWritePre
require("conform").setup({
format_on_save = function(bufnr)
-- Disable autoformat on certain filetypes
local ignore_filetypes = { "sql", "java" }
if vim.tbl_contains(ignore_filetypes, vim.bo[bufnr].filetype) then
return
end
-- Disable with a global or buffer-local variable
if vim.g.disable_autoformat or vim.b[bufnr].disable_autoformat then
return
end
-- Disable autoformat for files in a certain path
local bufname = vim.api.nvim_buf_get_name(bufnr)
if bufname:match("/node_modules/") then
return
end
-- ...additional logic...
return { timeout_ms = 500, lsp_fallback = true }
end,
})
-- There is a similar affordance for format_after_save, which uses BufWritePost.
-- This is good for formatters that are too slow to run synchronously.
require("conform").setup({
format_after_save = function(bufnr)
if vim.g.disable_autoformat or vim.b[bufnr].disable_autoformat then
return
end
-- ...additional logic...
return { lsp_fallback = true }
end,
})
```
<!-- /AUTOFORMAT -->
## Command to toggle format-on-save
Create user commands to quickly enable/disable autoformatting
```lua
require("conform").setup({
format_on_save = function(bufnr)
-- Disable with a global or buffer-local variable
if vim.g.disable_autoformat or vim.b[bufnr].disable_autoformat then
return
end
return { timeout_ms = 500, lsp_fallback = true }
end,
})
vim.api.nvim_create_user_command("FormatDisable", function(args)
if args.bang then
-- FormatDisable! will disable formatting just for this buffer
vim.b.disable_autoformat = true
else
vim.g.disable_autoformat = true
end
end, {
desc = "Disable autoformat-on-save",
bang = true,
})
vim.api.nvim_create_user_command("FormatEnable", function()
vim.b.disable_autoformat = false
vim.g.disable_autoformat = false
end, {
desc = "Re-enable autoformat-on-save",
})
```
## Automatically run slow formatters async
This snippet will automatically detect which formatters take too long to run synchronously and will run them async on save instead.
```lua
local slow_format_filetypes = {}
require("conform").setup({
format_on_save = function(bufnr)
if slow_format_filetypes[vim.bo[bufnr].filetype] then
return
end
local function on_format(err)
if err and err:match("timeout$") then
slow_format_filetypes[vim.bo[bufnr].filetype] = true
end
end
return { timeout_ms = 200, lsp_fallback = true }, on_format
end,
format_after_save = function(bufnr)
if not slow_format_filetypes[vim.bo[bufnr].filetype] then
return
end
return { lsp_fallback = true }
end,
})
```
## Lazy loading with lazy.nvim
Here is the recommended config for lazy-loading using lazy.nvim
```lua
return {
"stevearc/conform.nvim",
event = { "BufWritePre" },
cmd = { "ConformInfo" },
keys = {
{
-- Customize or remove this keymap to your liking
"<leader>f",
function()
require("conform").format({ async = true, lsp_fallback = true })
end,
mode = "",
desc = "Format buffer",
},
},
-- Everything in opts will be passed to setup()
opts = {
-- Define your formatters
formatters_by_ft = {
lua = { "stylua" },
python = { "isort", "black" },
javascript = { { "prettierd", "prettier" } },
},
-- Set up format-on-save
format_on_save = { timeout_ms = 500, lsp_fallback = true },
-- Customize formatters
formatters = {
shfmt = {
prepend_args = { "-i", "2" },
},
},
},
init = function()
-- If you want the formatexpr, here is the place to set it
vim.o.formatexpr = "v:lua.require'conform'.formatexpr()"
end,
}
```