LoginSignup
57
42

More than 5 years have passed since last update.

Visual Studio Codeでの行頭カッコを何とかしたい

Posted at

Visual Studio Codeのフォーマッタ

いつも自分は、コードが汚くなりがちなので、設定を

settings.json
"editor.formatOnSave": true,
"editor.formatOnType": true,

というふうにして改行するごと、保存するごとに自動的にフォーマッタを走らせるようにしている。
この機能は結構使えるのでおすすめ!

問題

VSCodeのフォーマッタはデフォルトで

main.cpp
#include <iostream>
int main() {
    std::cout << "Hello World" << std::endl;
    return 0;
}

を保存すると自動的に

main.cpp
#include <iostream>
int main()
{
    std::cout << "Hello World" << std::endl;
    return 0;
}

となってしまう!!!!

行末派なのでこれは宗教上どうしても受け入れることができない...

解決策

VSCodeの公式ドキュメントによると、デフォルトでの動作では、作業フォルダに.clang-formatというファイルがあるとそれを見に行ってそれに従ってフォーマットする。
ない場合は

.clang-format
UseTab: (VS Code current setting)
IndentWidth: (VS Code current setting)
BreakBeforeBraces: AllMan
AllowShortIfStatementsOnASingleLine: false
IndentCaseLabels: false
ColumnLimit: 0

とかいうVisual Studioというプリセットが使用されるらしい、これだと行頭にカッコが来る。
でもいちいちフォルダ毎に設定ファイルを設置するのは面倒なので、
"C_Cpp.clang_format_style"
GoogleとかLLVMとかChromiumとか色々指定できるらしく、とりあえず天下のGoogle様のを使うことにした、Google様のフォーマッタは行末にカッコを持ってきてくれる。
でもTabは4spaceが良いので別途設定した。

結論

settings.json
{
    "C_Cpp.clang_format_style": "Google",
    "editor.formatOnSave": true,
    "editor.formatOnType": true,
    "[cpp]": {
        "editor.tabSize": 4,
    },
}
57
42
1

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
57
42