IntelliJ Postfix Completion
A smart, efficient twist on code completion
I like to learn more efficient ways to use my dev tools, and making good use of the keyboard shortcuts in IntelliJ IDEA is a significant example. When I first saw Postfix Completion in use, I think my reaction was "Oooh… I need to start using that trick!" In this post, I’ll illustrate a few of these special code completion options.
So… what is Postfix Completion?
Postfix code completion lets you add template code around an expression you’ve just typed. A template expands when you type its abbreviation (postfix) after a dot and press the expansion key (Tab by default)
— IntelliJ Documentation
It’s really quite simple once you start to learn the abbreviations. Let’s take a look at some examples.
I make use of the .var template most often. When writing a line of code such as a method call, I tend to focus on the method call first and it often feels more fluid to add a local variable afterward, which is a perfect fit for this postfix completion item.
After typing .var and hitting Tab, you’ll get a suggested variable declaration, as shown below. The variable name is active and selected, so you can immediately start typing if you want something else. You can also hit the left or right arrow key to position your cursor at the start or end of the suggested variable name, to add your own prefix or suffix, so to speak.
When you are satisfied with the variable name, press your Enter key to finalize things and return to standard code editing mode.
When you have an Iterable<T> or an array and need to loop over the elements, this handy postfix completion stubs in the loop for you.
Of course you can rename the loop variable if you like, and then hit Enter to find your cursor positioned within the loop body.
Note that .for is another option providing the same completion template as .iter shown above. For some reason, I picked up .iter first and it has become my habit for this idiom.
If you can’t make use of this one I’d be very surprised. There isn’t a lot to say… wrap your code in a simple if statement.
As usual, hit Enter to complete the if statement and your cursor will be set inside the statement body.
You might also find .else or .not useful. Each of these produces a negated version of the if evaluation.
I don’t tend to use this one as often, but it is a handy way to get the code for a loop over a numeric variable you’re working with. It also works with a literal value rather than a variable name.
You can find all the built-in Postfix Completion templates from the main IntelliJ Settings dialog (Preferences on a Mac) and then under Editor | General | Postfix Completion. And if you don’t see what you need, you can even create your own!