Surround With…July 25th, 2006 by etienne
IntelliJ IDEA makes it very easy to surround a code block with if, while, for and other statements or to make a code block become part of such statments as try/catch or synchronized. Simply select the code block to surround (don’t forget to use Ctrl + W to increase the current selection) and then press Ctrl + Alt + T (or right-click the selection and select Surround with… from the menu). IntelliJ IDEA will show a list of options to choose from.
Once you have made your choice, IntelliJ IDEA will add the necessary code and put the caret to the position that allows you to complete the surrounding statement, if needed.
After that, you’re done. As you can see, adding such a surrounding if statement does not break the flow of coding at all and there is no need in any additional key stroke or mouse move.
Furthemore, IntelliJ IDEA not simply surrounds the code, but makes it as smart as possible. For example, if you choose to surround a code block with a try/catch statement, IntelliJ IDEA will add all necessary catch statements for all thrown exception types that it is able to determine within the selected code block.
Another useful scenario of using ‘Surround With…’ is when inspecting objects in the debugger’s Expression Evaluation window. Let’s say you want to evaluate a method call on the inspected object where the method is a part of the runtime type but not a part of the declared super type. IntelliJ IDEA helps you with casting the object to the runtime type: just press Ctrl + Alt + T in the expression box, and select Surround With ((RuntimeType) expr) from the list.
You can then invoke any method that is a part of the runtime type of the inspected object. Again, the described operation of casting to the runtime type does not break the flow of coding due to IntelliJ IDEA’s intelligent and unobtrusive assistance.
By the way, the Expression Evaluation view supports code completion, JavaDoc popup, etc. just like the normal Java editor.