68

How to surround code by curly braces in IntelliJ IDEA? Is there any keyboard-shortcut for such operation?

Basil Bourque
  • 303,325
  • 100
  • 852
  • 1,154
Pavel
  • 4,912
  • 7
  • 49
  • 69

8 Answers8

129

Just configure Smart Keys as follow:
IDE Settings > Editor > General > Smart Keys > Surround selection on typing quote or brace.

enter image description here

From the IntelliJ built-in help:

If this check box is selected, the selected text on typing a quote, double-quote or brace, will be surrounded with these characters.

If this check box is not selected, then the typed quotes, double-quotes or braces will replace the selection.

Community
  • 1
  • 1
Ajang R
  • 1,291
  • 2
  • 8
  • 2
  • 1
    Bless you! NB to others: By default, my curly brackets are showing up on the left margin. You may have to play a bit with exactly what you have selected and then use the autoindent feature to make this technique result in code you like the look of. – Anne Gunn Apr 13 '16 at 17:32
  • Saw the option, but I've no idea how to use this. – Ascendant Dec 09 '16 at 20:37
  • me neither... when I select an expression and type "brace" it writes braces and cannot resolve that... – xetra11 May 18 '17 at 13:02
  • 2
    Anyone wondering how to use it : select you text and type curly braces(or double quote) and the selection would be placed inside a curly brace. – Quazi Irfan Mar 15 '18 at 08:07
  • @xetra11 Do not type the word "brace". Type the character for an opening brace: "{" while having a text selected. – Robert May 05 '21 at 08:58
58

Yes, try Ctrl+Alt+T (Surround With), then A (Curly Braces).

Pavel
  • 4,912
  • 7
  • 49
  • 69
zagyi
  • 17,223
  • 4
  • 51
  • 48
6

I had oneline if statement without curly braces and I had to update it with braces in whole file. So I updated code style to always add braces for if/else statement. In Idea go to:

Settings -> Editor -> Code Style -> Java -> Wrapping and Braces (tab)

Find "'If()' Statement"/"Force braces" and change value from "Do not force"(default) to "Always". Press ctrl + alt + L to reformat your file and curly braces would be added. settings

amisiuryk
  • 195
  • 3
  • 12
5

Just click as the below 2 steps

1, CTRL + ALT + T
2, then press ALT + A at the same time.

Hope to help you.

Hunter Zhao
  • 4,589
  • 2
  • 25
  • 39
5

Add "Control flow statement without braces" to inspection settings. Then run inspection, select them in the list and then select "Apply Fix 'Add braces'".

It just saved me a whole days tedious work!

Martin Wickman
  • 19,662
  • 12
  • 82
  • 106
5

The easiest way is, select the code part that you want and press Shift + [

Supun Sandaruwan
  • 1,814
  • 19
  • 19
4

You need to create a live template first. Just go Preferences and add a template to html/xml

enter image description here

goksel
  • 4,450
  • 3
  • 42
  • 51
0

Easy, just follow the arrows in this picture, from left to right: Screenshot with arrows

Yunnosch
  • 26,130
  • 9
  • 42
  • 54