2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

Visual StudioのC/C++のコードスニペットをK&Rスタイル風にする

Posted at

Visual StudioでC言語やC++をやっているとifなどを自動補完したときSample1のように展開されます。

Sample1.cpp
int main(void) {
    if (true)
    {
    }
}

これを

Sample2.cpp
int main(void) {
    if (true) {
    }
}

括弧がこのように展開されるように変更してみよう。
という内容です。

手順

1.デフォルトのコードスニペットを任意の場所へコピーする。

Visual Studio 2015の場合
C:\Program Files (x86)\Microsoft Visual Studio 14.0\VC\Snippets\1041\Visual C++
にデフォルトのスニペットがありますのでフォルダ内のファイルを適当な場所へコピーします。
2018-01-09 (1).png
※上記のパスに見当たらない場合はVisual Studioのコードスニペットマネージャーから確認して見て下さい。

今回はこれをマイドキュメントフォルダ
Documents\Visual Studio 2015\Code Snippets\Visual C++\My Code Snippets
にコピーしたものとします。
2018-01-09 (14).png

2.読取り専用属性を外す。

Ctrl+Aなどでファイルをすべて選択し、コピーしたスニペットの読み取り専用を解除します。
2018-01-09 (3).png

3.コードスニペットを編集する。

任意のエディタでコードスニペットすべて編集します。
例としてifのコードスニペットを編集します。
変更前
2018-01-09 (5).png

変更後
2018-01-09 (7).png
このような感じですべてのスニペットを変更して保存して下さい。

4.Visual Studioのコードスニペットマネージャーから設定する。

編集が終わったスニペットをVisual Studioに登録するためコードスニペットマネージャーを開きます。
2018-01-09 (10).png

コピー元のデフォルトのコードスニペットはもう使いませんので削除します。
2018-01-09 (16).png

5.編集したコードスニペットを確認する。

手順の「1.」のフォルダに配置した場合、My Code Snippetsフォルダに編集したコードスニペットが追加されているので展開して確認してみます。
※それ以外のフォルダに配置した場合、追加(A)から追加して下さい。
2018-01-09 (17).png
削除追加が完了したらOKをクリックしてコードスニペットマネージャーを閉じて下さい。

6.動作確認

試しにifと入力して以下のように展開されれば成功です。
2018-01-09 (18).png

7.おまけ

以下のようなスニペットを作りたい場合、スニペットを作成しただけではうまく動作しません。
※catchやdo-whileでも同様です。

ifelse.cpp
int main(void) {
    if (true) {
    } else {
    }
}

スニペットの作成と同時にVisual Studioの以下の設定を変更する必要があります。
ツール(T)→オプション(O)→テキストエディター→C/C++→書式設定→改行→キーワードの位置
2018-01-09 (21).png

これに気づかずにハマった・・・

2
1
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
2
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?