コンテンツにスキップ

フォーマッタ

OpenCode は言語固有のフォーマッタを使用します。

OpenCode は、言語固有のフォーマッタを使用してファイルを作成または編集した後、ファイルを自動的にフォーマットします。これにより、生成されるコードがプロジェクトのコード スタイルに従っていることが保証されます。


内蔵

OpenCode には、一般的な言語およびフレームワーク用のいくつかの組み込みフォーマッタが付属しています。以下は、フォーマッタ、サポートされているファイル拡張子、および必要なコマンドまたは構成オプションのリストです。

FormatterExtensionsRequirements
gofmt.gogofmt command available
mix.ex, .exs, .eex, .heex, .leex, .neex, .sfacemix command available
prettier.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and moreprettier dependency in package.json
biome.js, .jsx, .ts, .tsx, .html, .css, .md, .json, .yaml, and morebiome.json(c) config file
zig.zig, .zonzig command available
clang-format.c, .cpp, .h, .hpp, .ino, and more.clang-format config file
ktlint.kt, .ktsktlint command available
ruff.py, .pyiruff command available with config
rustfmt.rsrustfmt command available
cargofmt.rscargo fmt command available
uv.py, .pyiuv command available
rubocop.rb, .rake, .gemspec, .rurubocop command available
standardrb.rb, .rake, .gemspec, .rustandardrb command available
htmlbeautifier.erb, .html.erbhtmlbeautifier command available
air.Rair command available
dart.dartdart command available
ocamlformat.ml, .mliocamlformat command available and .ocamlformat config file
terraform.tf, .tfvarsterraform command available
gleam.gleamgleam command available
nixfmt.nixnixfmt command available
shfmt.sh, .bashshfmt command available
pint.phplaravel/pint dependency in composer.json
oxfmt (Experimental).js, .jsx, .ts, .tsxoxfmt dependency in package.json and an experimental env variable flag
ormolu.hsormolu command available

したがって、プロジェクトの prettierpackage.json が含まれている場合、OpenCode は自動的にそれを使用します。


仕組み

OpenCode がファイルを書き込んだり編集したりすると、次のことが行われます。

  1. 有効なすべてのフォーマッタに対してファイル拡張子をチェックします。
  2. ファイルに対して適切なフォーマッタ コマンドを実行します。
  3. 書式の変更を自動的に適用します。

このプロセスはバックグラウンドで実行されるため、手動の手順を行わなくてもコード スタイルが維持されます。


設定する

OpenCode 構成の formatter セクションを通じてフォーマッタをカスタマイズできます。

opencode.json
{
"$schema": "https://opencode.ai/config.json",
"formatter": {}
}

各フォーマッタ設定は以下をサポートします。

プロパティタイプ説明
disabledブール値フォーマッタを無効にするには、これを true に設定します。
command文字列[]フォーマットのために実行するコマンド
environmentオブジェクトフォーマッタの実行時に設定する環境変数
extensions文字列[]このフォーマッタが処理するファイル拡張子

いくつかの例を見てみましょう。


フォーマッタの無効化

すべてのフォーマッタをグローバルに無効にするには、formatterfalse に設定します。

opencode.json
{
"$schema": "https://opencode.ai/config.json",
"formatter": false
}

特定のフォーマッタを無効にするには、disabledtrue に設定します。

opencode.json
{
"$schema": "https://opencode.ai/config.json",
"formatter": {
"prettier": {
"disabled": true
}
}
}

カスタムフォーマッタ

コマンド、環境変数、ファイル拡張子を指定することで、組み込みフォーマッタをオーバーライドしたり、新しいフォーマッタを追加したりできます。

opencode.json
{
"$schema": "https://opencode.ai/config.json",
"formatter": {
"prettier": {
"command": ["npx", "prettier", "--write", "$FILE"],
"environment": {
"NODE_ENV": "development"
},
"extensions": [".js", ".ts", ".jsx", ".tsx"]
},
"custom-markdown-formatter": {
"command": ["deno", "fmt", "$FILE"],
"extensions": [".md"]
}
}
}

コマンド内の $FILE プレースホルダー は、フォーマットされるファイルへのパスに置き換えられます。