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,33 @@
-- 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,
})

View File

@ -0,0 +1,217 @@
import os
import os.path
import re
from dataclasses import dataclass
from functools import lru_cache
from typing import List
from nvim_doc_tools import (
Vimdoc,
VimdocSection,
dedent,
generate_md_toc,
indent,
parse_directory,
read_nvim_json,
read_section,
render_md_api2,
render_vimdoc_api2,
replace_section,
wrap,
)
HERE = os.path.dirname(__file__)
ROOT = os.path.abspath(os.path.join(HERE, os.path.pardir))
README = os.path.join(ROOT, "README.md")
DOC = os.path.join(ROOT, "doc")
RECIPES = os.path.join(DOC, "recipes.md")
ADVANCED = os.path.join(DOC, "advanced_topics.md")
FORMATTER_OPTIONS = os.path.join(DOC, "formatter_options.md")
VIMDOC = os.path.join(DOC, "conform.txt")
OPTIONS = os.path.join(ROOT, "scripts", "options_doc.lua")
AUTOFORMAT = os.path.join(ROOT, "scripts", "autoformat_doc.lua")
@dataclass
class Formatter:
name: str
description: str
url: str
has_options: bool
deprecated: bool = False
@lru_cache
def get_all_formatters() -> List[Formatter]:
formatters = []
formatter_map = read_nvim_json(
'require("conform.formatters").list_all_formatters()'
)
for name, meta in formatter_map.items():
formatter = Formatter(name, **meta)
if not formatter.deprecated:
formatters.append(formatter)
formatters.sort(key=lambda f: f.name)
return formatters
def update_formatter_list():
formatter_lines = ["\n"]
for formatter in get_all_formatters():
formatter_lines.append(
f"- [{formatter.name}]({formatter.url}) - {formatter.description}\n"
)
replace_section(
README,
r"^<!-- FORMATTERS -->$",
r"^<!-- /FORMATTERS -->$",
formatter_lines,
)
def update_options():
option_lines = ["\n", "```lua\n"]
with open(OPTIONS, "r", encoding="utf-8") as f:
option_lines.extend(f.readlines())
option_lines.extend(["```\n", "\n"])
replace_section(
README,
r"^<!-- OPTIONS -->$",
r"^<!-- /OPTIONS -->$",
option_lines,
)
def update_autocmd_md():
example_lines = ["\n", "```lua\n"]
with open(AUTOFORMAT, "r", encoding="utf-8") as f:
example_lines.extend(f.readlines())
example_lines.extend(["```\n", "\n"])
replace_section(
RECIPES,
r"^<!-- AUTOFORMAT -->$",
r"^<!-- /AUTOFORMAT -->$",
example_lines,
)
def update_formatter_options_md():
lines = ["\n"]
for formatter in get_all_formatters():
if formatter.has_options:
lines.extend([f"## {formatter.name}\n", "\n", "```lua\n", "options = {\n"])
formatter_file = os.path.join(
ROOT, "lua", "conform", "formatters", f"{formatter.name}.lua"
)
code = read_section(formatter_file, r"^ options = {$", r"^ },$")
lines.extend(dedent(code, 2))
lines.extend(["}\n", "```\n", "\n"])
replace_section(
FORMATTER_OPTIONS,
r"^<!-- OPTIONS -->$",
r"^<!-- /OPTIONS -->$",
lines,
)
def add_md_link_path(path: str, lines: List[str]) -> List[str]:
ret = []
for line in lines:
ret.append(re.sub(r"(\(#)", "(" + path + "#", line))
return ret
def update_md_api():
types = parse_directory(os.path.join(ROOT, "lua"))
funcs = types.files["conform/init.lua"].functions
lines = ["\n"] + render_md_api2(funcs, types, 3)[:-1] # trim last newline
replace_section(
README,
r"^<!-- API -->$",
r"^<!-- /API -->$",
lines,
)
def update_readme_toc():
toc = ["\n"] + generate_md_toc(README) + ["\n"]
replace_section(
README,
r"^<!-- TOC -->$",
r"^<!-- /TOC -->$",
toc,
)
def update_recipes_toc():
toc = ["\n"] + generate_md_toc(RECIPES) + ["\n"]
replace_section(RECIPES, r"^<!-- TOC -->$", r"^<!-- /TOC -->$", toc)
subtoc = add_md_link_path("doc/recipes.md", toc)
replace_section(README, r"^<!-- RECIPES -->$", r"^<!-- /RECIPES -->$", subtoc)
def update_advanced_toc():
toc = ["\n"] + generate_md_toc(ADVANCED) + ["\n"]
replace_section(ADVANCED, r"^<!-- TOC -->$", r"^<!-- /TOC -->$", toc)
subtoc = add_md_link_path("doc/advanced_topics.md", toc)
replace_section(README, r"^<!-- ADVANCED -->$", r"^<!-- /ADVANCED -->$", subtoc)
def update_formatter_options_toc():
toc = ["\n"] + generate_md_toc(FORMATTER_OPTIONS) + ["\n"]
replace_section(FORMATTER_OPTIONS, r"^<!-- TOC -->$", r"^<!-- /TOC -->$", toc)
subtoc = add_md_link_path("doc/formatter_options.md", toc)
replace_section(
README,
r"^<!-- FORMATTER_OPTIONS -->$",
r"^<!-- /FORMATTER_OPTIONS -->$",
subtoc,
)
def gen_options_vimdoc() -> VimdocSection:
section = VimdocSection("Options", "conform-options", ["\n", ">lua\n"])
with open(OPTIONS, "r", encoding="utf-8") as f:
section.body.extend(indent(f.readlines(), 4))
section.body.append("<\n")
return section
def gen_formatter_vimdoc() -> VimdocSection:
section = VimdocSection("Formatters", "conform-formatters", ["\n"])
for formatter in get_all_formatters():
line = f"`{formatter.name}` - {formatter.description}\n"
section.body.extend(wrap(line, sub_indent=len(formatter.name) + 3))
return section
def generate_vimdoc():
doc = Vimdoc("conform.txt", "conform")
types = parse_directory(os.path.join(ROOT, "lua"))
funcs = types.files["conform/init.lua"].functions
doc.sections.extend(
[
gen_options_vimdoc(),
VimdocSection(
"API", "conform-api", render_vimdoc_api2("conform", funcs, types)
),
gen_formatter_vimdoc(),
]
)
with open(VIMDOC, "w", encoding="utf-8") as ofile:
ofile.writelines(doc.render())
def main() -> None:
"""Update the README"""
update_formatter_list()
update_options()
update_autocmd_md()
update_formatter_options_md()
update_md_api()
update_recipes_toc()
update_advanced_toc()
update_formatter_options_toc()
update_readme_toc()
generate_vimdoc()

View File

@ -0,0 +1,31 @@
#!/usr/bin/env python
import argparse
import os
import sys
HERE = os.path.dirname(__file__)
ROOT = os.path.abspath(os.path.join(HERE, os.path.pardir))
DOC = os.path.join(ROOT, "doc")
def main() -> None:
"""Generate docs"""
sys.path.append(HERE)
parser = argparse.ArgumentParser(description=main.__doc__)
parser.add_argument("command", choices=["generate", "lint"])
args = parser.parse_args()
if args.command == "generate":
import generate
generate.main()
elif args.command == "lint":
from nvim_doc_tools import lint_md_links
files = [os.path.join(ROOT, "README.md")] + [
os.path.join(DOC, file) for file in os.listdir(DOC) if file.endswith(".md")
]
lint_md_links.main(ROOT, files)
if __name__ == "__main__":
main()

View File

@ -0,0 +1,93 @@
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",
}