代码格式化工具
按语言分类
Python
Formatter:
Linter: Flake8
安装
pipx 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
)/
'''
CMake
Formatter: cmake-format
安装
pipx install cmake-format --include-deps
使用
cmake-format <file>
XML
Formatter: XmlLint
安装
-
macOS:
brew install libxml2
-
Ubuntu:
sudo apt install libxml2-utils
使用
xmllint --format input.xml -o output.xml
TOML
按工具分类
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
参考:
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