代码格式化工具

按语言分类

Python

Formatter:

Linter: Flake8

安装

pip install black

isort 用法和 black 类似。

使用

black <file>          # 格式化单个文件
black <dir>           # 格式化整个目录
black --check <file>  # 检查文件格式(不修改)
black --diff <file>   # 显示差异而不修改文件

配置

可以在 pyproject.toml 文件中配置 black:

[tool.black]
line-length = 120
target-version = ['py36', 'py37', 'py38']
include = '\.pyi?$'
exclude = '''
/(
    \.git
  | \.hg
  | \.mypy_cache
  | \.tox
  | \.venv
  | _build
  | buck-out
  | build
  | dist
)/
'''

Java

Formatter: google-java-format
Plugin: spotless-maven-plugin

安装

<!-- project > build > plugins -->
<plugin>
  <groupId>com.diffplug.spotless</groupId>
  <artifactId>spotless-maven-plugin</artifactId>
  <version>2.44.5</version>
  <executions>
    <execution>
      <goals>
        <goal>check</goal>
        <goal>apply</goal>
      </goals>
    </execution>
  </executions>
  <configuration>
    <java>
      <googleJavaFormat>
        <style>GOOGLE</style>
        <reflowLongStrings>true</reflowLongStrings>
        <formatJavadoc>false</formatJavadoc>
      </googleJavaFormat>
    </java>
  </configuration>
</plugin>
mvn spotless:check  # 检查格式
mvn spotless:apply  # 应用格式化

CMake

Formatter: cmake-format

安装

pip install cmakelang

使用

cmake-format <file>

XML

Formatter: XmlLint

安装

# macOS
brew install libxml2
# Ubuntu
sudo apt install libxml2-utils

使用

xmllint --format input.xml -o output.xml

YAML

Linter: yamllint
Formatter:

yamllint

# APT
sudo apt install yamllint
# Homebrew
brew install yamllint
# Pip
pip install --user yamllint
yamllint config.yaml  # 检查 yaml 文件

yamlfmt

yamlfmt file.yaml  # 格式化 yaml 文件
yamlfmt .          # 格式化目录

TOML

Formatter: Taplo

安装

# macOS
brew install taplo
# Cargo
cargo install taplo-cli --locked

使用

taplo fmt foo.toml

LaTeX

Formatter:

latexindent 是 TeX Live 自带的代码格式化工具。

latexindent -w main.tex  # 原地修改

tex-fmt 是使用 Rust 编写的高效格式化工具。

tex-fmt file.tex

参见:latexindent.pl documentation

BiBTeX

Formatter: bibtex-tidy

bibtex-tidy main.bib

按工具分类

Prettier

项目地址

支持语言

  • Markdown
  • HTML
  • CSS
  • SCSS
  • JavaScript
  • TypeScript
  • JSON
  • GraphQL
  • YAML
  • Vue
  • Angular
  • Less
  • Flow
  • JSX

使用

npx prettier <file> --write  # Prettier 将根据文件后缀名确认文件类型

配置

可以在项目根目录下创建 .prettierrc 文件来自定义格式化风格:

{
  "semi": false,
  "singleQuote": true,
  "tabWidth": 4,
  "trailingComma": "es5"
}

参见:How To Format Code with Prettier in Visual Studio Code | DigitalOcean

ClangFormat

支持语言

  • C/C++
  • Java
  • JavaScript
  • JSON
  • Objective-C
  • Protobuf
  • C#

安装

# macOS
brew install clang-format
# Ubuntu
sudo apt install clang-format

使用

clang-format --style=<style> -i <file>
  • style 选项:LLVM, GNU, Google, Chromium, Microsoft, Mozilla, WebKit, file

我个人最喜欢 Google 风格。

配置

可以在项目根目录下创建 .clang-format 文件来自定义格式化风格:

BasedOnStyle: Google
IndentWidth: 4
ColumnLimit: 100

参考:

posted @ 2024-07-09 17:47  Undefined443  阅读(91)  评论(0)    收藏  举报