← All articles
Tools1 min read

Live Templates in IntelliJ IDEA

Type a short abbreviation, hit Tab, and expand it into a full code snippet. Live templates eliminate the boilerplate you write over and over.

S

Swapnika Voora

Author

Some code you type hundreds of times: loops, loggers, test scaffolds. Live templates let you expand a short abbreviation into that boilerplate instantly, with editable placeholders for the parts that change.

Built-in templates you already have

IntelliJ ships with many. Type the abbreviation and press Tab.

built-in templates
sout      System.out.println()
fori      for (int i = 0; i < ; i++)
iter      Enhanced for loop over an iterable
psvm      public static void main(String[] args)
ifn       if (x == null)

Create your own

Define custom templates under Settings → Editor → Live Templates. Variables in $NAME$ become tab stops you fill in after expansion.

custom template: 'logf'
private static final Logger log =
    LoggerFactory.getLogger($CLASS$.class);

Set $CLASS$ to the expression className() so it fills in automatically when the template expands.

Surround templates

Surround-with templates wrap an existing selection. Select code, press Ctrl/Cmd + Alt + T, and wrap it in a try/catch, loop, or condition.

surround.java
// select the middle line, surround with try/catch
try {
    riskyCall();
} catch (Exception e) {
    log.error("failed", e);
}

Takeaways

  • Built-in templates like sout and fori cover common boilerplate.
  • Custom templates with $VAR$ tab stops encode your team's patterns.
  • Surround-with templates wrap existing code instead of retyping it.

Export your live templates as a settings file and share them so the whole team writes the same idioms with the same abbreviations.

#intellij#java#productivity

More in Tools