LoginSignup
52
24

More than 3 years have passed since last update.

Visual Studio CodeでC言語を行頭かっこじゃないようにオートフォーマットする

Last updated at Posted at 2020-03-02

やりたいこと

Cのコードをこのスタイルにフォーマットしたい。開始かっこの改行なし、タブサイズは4。

#include <stdio.h>

int main(void) {
    printf("hello, world\n");
    return 0;
}

結論

settings.jsonに以下を追記して解決。

"C_Cpp.clang_format_style": "{BasedOnStyle: Google, IndentWidth: 4}"

参考:https://stackoverflow.com/questions/45823734/vs-code-formatting-for

Visual Studio Codeの自動整形について

C/C++用のextension(C/C++)を入れると、「Shift+Option+F(Mac)」で自動整形されるようになる。
またはテキストエリア上で「右クリック」→「Format Document」でも可能。

試行錯誤のログ

C/C++のデフォルトでは、自動フォーマットは開始かっこ { が新しい行に来る。
でも{ の前は改行されないスタイルの方が好みなんだ…!
Googleのスタイルガイドだとこの形式らしい。C++用っぽいけれど。
https://google.github.io/styleguide/cppguide.html

settings.jsonに以下を書けば適用される。
Cmd+,で環境設定を開いてから、画面右上の スクリーンショット 2020-03-01 17.35.14.png (Open Settings (JSON))をクリックして開く。

"C_Cpp.clang_format_style": "Google"

ただしこれだとタブサイズが2。タブは4がいい…。

ので、ここだけ上書きする設定をする。
失敗:言語ごとの設定として、以下のように書いてもtabSize: 4は全然効かなかった。ずっと2でフォーマットされた。

{
    "C_Cpp.clang_format_style": "Google",
    "[c]": {
        "editor.tabSize": 4
    }
}

こちらが正解。(再掲)

"C_Cpp.clang_format_style": "{BasedOnStyle: Google, IndentWidth: 4}"

ついでに

ファイル保存時に自動でフォーマッタが動くように設定追加。

{
    "editor.formatOnType": true,
    "editor.formatOnSave": true,
    "C_Cpp.clang_format_style": "{BasedOnStyle: Google, IndentWidth: 4}"
}
52
24
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
52
24