What Are IntelliJ IDEA Code Snippets (Live Templates)?
IntelliJ IDEA code snippets, officially called Live Templates, are predefined or custom code fragments that expand automatically when you type a short abbreviation and press Tab (or the configured expansion key). Think of them as intelligent boilerplate generators that insert commonly used code patterns, complete with dynamic placeholders, variable references, and context-aware transformations — all in a single keystroke.
Unlike static text expansions found in simpler editors, IntelliJ's Live Templates are deeply integrated with the IDE's code intelligence. They understand the surrounding context, infer types, suggest variable names, and can even prompt you with expression choices at expansion time. This makes them vastly more powerful than copy-paste or plain snippet tools.
Why Live Templates Matter
🚀 Deploy your AI agent in 10 minutes
Managed Hermes hosting. Zero DevOps. 100M tokens/mo included.
Try it free →Every developer writes repetitive code: getters and setters, loops, try-catch blocks, test method stubs, logging statements, and framework-specific boilerplate. Manually typing these patterns costs time, introduces typos, and breaks flow. Live Templates address all three problems:
- Speed: Type
psvm+ Tab and you instantly getpublic static void main(String[] args)— a five-character abbreviation replacing a 40-character method signature. - Consistency: Team-shared templates ensure everyone uses identical code patterns, reducing merge conflicts and code review noise.
- Accuracy: Template variables with expression functions automatically insert the correct type, method name, or expected value, eliminating manual mistakes.
- Flow preservation: After expansion, the cursor lands on the first editable variable; subsequent Tab presses cycle through remaining placeholders, keeping your hands on the keyboard.
Built-In Live Templates
IntelliJ IDEA ships with dozens of ready-to-use templates organized by scope. Here are the most essential ones every Java developer should know:
Java Core Templates
Main method:
// Abbreviation: psvm
// Expansion:
public static void main(String[] args) {
$END$
}
For-each loop:
// Abbreviation: iter
// Expansion:
for (String $VAR$ : $ITERABLE$) {
$END$
}
For-i loop:
// Abbreviation: fori
// Expansion:
for (int $INDEX$ = 0; $INDEX$ < $LIMIT$; $INDEX$++) {
$END$
}
If statement:
// Abbreviation: ifn (if null)
// Expansion:
if ($VAR$ == null) {
$END$
}
Try-catch:
// Abbreviation: tryc
// Expansion:
try {
$CODE$
} catch ($EXCEPTION$ $CATCH_VAR$) {
$END$
}
Logging Templates
Log statement with SLF4J/Log4j:
// Abbreviation: logr (log error)
// Expansion:
LOGGER.error("$MESSAGE$", $THROWABLE$);
Testing Templates (JUnit)
Test method:
// Abbreviation: test
// Expansion:
@Test
public void $METHOD_NAME$() {
// given
$GIVEN$
// when
$WHEN$
// then
$THEN$
$END$
}
How to Use Live Templates
Using a built-in template is straightforward:
- Place the cursor where you want the code to appear.
- Type the abbreviation (e.g.,
psvm,iter,sout). - Press Tab (or Ctrl+J / Cmd+J if Tab is remapped).
- If the template contains variables, the first one is highlighted. Type its value or accept the suggestion.
- Press Tab or Enter to move to the next variable; press Shift+Tab to move back.
- Press Esc or finish editing to exit the template session and land at
$END$.
You can also invoke the full list via Ctrl+J (Cmd+J on macOS), which displays a popup of all templates available in the current context:
// Press Ctrl+J (Cmd+J) anywhere in a Java file
// A popup appears listing all available templates
// Start typing to filter, then press Enter on the desired one
Creating Custom Live Templates
The real power comes from creating your own templates tailored to your project's patterns. Here's the complete step-by-step process:
Step 1: Open the Settings
Navigate to File → Settings → Editor → Live Templates (on macOS: IntelliJ IDEA → Preferences → Editor → Live Templates).
Step 2: Choose or Create a Template Group
Templates are organized into groups (like "Java", "Kotlin", "Groovy"). You can add your templates to existing groups or create a new group for your project-specific snippets. Click the + button and select Template Group..., then name it (e.g., "MyProject").
Step 3: Add a New Live Template
Select your group, click + again, and choose Live Template. Fill in:
- Abbreviation: The short text you'll type to trigger expansion (e.g.,
jdbfor a JDB template). - Description: Optional but helpful text shown in the popup list.
- Template text: The actual code with variables (see next section).
- Expand with: Usually Tab, but can be Space, Enter, or a custom key.
Step 4: Set the Applicable Context
Click Define (or Change) at the bottom and select the language/file types where this template should be available. For Java templates, check Java → Declaration, Expression, Statement etc. You must select at least one context, or the template will never appear.
Practical Example: Custom Builder Pattern Template
Let's create a template for a common builder pattern setter method:
// Template abbreviation: bldr
// Template text:
public $CLASS_NAME$ $SETTER_NAME$($TYPE$ $PARAM$) {
this.$FIELD$ = $PARAM$;
return this;
$END$
}
After defining this, typing bldr + Tab in a class body expands to a complete builder setter with return, and lets you tab through CLASS_NAME, SETTER_NAME, TYPE, PARAM, and FIELD.
Template Variables and Expression Functions
Variables are the heart of Live Templates. They appear as $VARIABLE_NAME$ in the template text. When the template expands, variables become interactive placeholders. You can define their behavior in the Edit Template Variables dialog (click the "Edit variables" button in the template editor).
Built-in Expression Functions
Each variable can have an expression function that determines its default value. Here are the most powerful ones:
// snippet() — Reuse another template's expansion
$METHOD_BODY$ expression: snippet("methodBody")
// className() — Returns the enclosing class name
$CLASS$ expression: className()
// methodName() — Returns the enclosing method name
$METHOD$ expression: methodName()
// variableOfType("type") — Suggests variables matching the type
$LIST$ expression: variableOfType("java.util.List")
// suggestVariableName() — Infers a good variable name
$VAR$ expression: suggestVariableName()
// groovyScript("...") — Execute custom Groovy logic
$CONVERTED$ expression: groovyScript("_1.toLowerCase()", VARIABLE)
Practical Example: Logger Declaration Template
This template automatically inserts the correct class name into the logger declaration:
// Abbreviation: logc (log class)
// Template text:
private static final Logger LOGGER = LoggerFactory.getLogger($CLASS$.class);
// Variable definition:
// $CLASS$ → expression: className()
When you type logc + Tab inside any class, it expands to:
private static final Logger LOGGER = LoggerFactory.getLogger(MyActualClass.class);
No typing required — className() resolves the enclosing class automatically.
Advanced: Groovy Script Expressions
For complex transformations, use groovyScript() to run arbitrary Groovy code:
// Template: Generate a constant from a string
// Abbreviation: const
// Template text:
public static final String $CONST_NAME$ = "$VALUE$";
// Variables:
// $VALUE$ → default: "input value"
// $CONST_NAME$ → expression: groovyScript("_1.replaceAll(' ', '_').toUpperCase()", VALUE)
If you enter "max retry count" for $VALUE$, $CONST_NAME$ becomes MAX_RETRY_COUNT.
Postfix Completion — Templates in Reverse
IntelliJ also offers Postfix Completion, which works like Live Templates but applied after you've typed an expression. Type a dot followed by the postfix keyword and press Tab. For example:
// Type: list.for
// Press Tab, expands to:
for (Object item : list) {
}
// Type: name.nn
// Press Tab, expands to:
if (name != null) {
}
// Type: value.var
// Press Tab, expands to:
Type value = value; // with inferred type
Postfix completions are configured alongside Live Templates in Settings → Editor → General → Postfix Completion. You can enable/disable individual postfixes and see the full list. Common ones include .if, .else, .null, .nn, .for, .fori, .while, .sout, .var, .cast, and .try.
Sharing Templates with Your Team
Live Templates are stored in the IDE configuration and can be shared in several ways:
- Export/Import: In the Live Templates settings, select a group, click the Export button (disk icon), and save as an XML file. Team members import via the Import button. Store the XML in version control.
- Settings Repository: Use IntelliJ's built-in Settings Repository feature (File → Manage IDE Settings → Settings Repository) to sync templates (and all IDE settings) across team members via a Git repo.
- Project-Level Templates: In the Live Templates dialog, you can create templates scoped to the project instead of the IDE. These live in the
.ideadirectory and can be committed to version control, automatically available to anyone who checks out the project.
Export Example Command Line
You can also export templates non-interactively using the IDE's command-line tools:
# Export all live templates to an XML file
idea.exe dumpSharedSettings --output=templates.xml --setting=live_templates
# Import on another machine
idea.exe applySharedSettings --input=templates.xml
Best Practices for Live Templates
1. Keep Abbreviations Short and Mnemonic
Use 3–5 character abbreviations that hint at the expansion. psvm (public static void main) is memorable because it uses first letters. bldr for builder, logc for logger class — pick conventions and stick to them.
2. Use Scopes Precisely
Only assign templates to contexts where they make sense. A JPA repository template should be limited to Java → Declaration, not available inside method bodies. Precise scoping prevents clutter in the completion popup and accidental expansions.
3. Leverage Expression Functions Over Manual Typing
Whenever possible, use className(), methodName(), variableOfType(), and suggestVariableName() rather than leaving variables as plain editable text. This reduces keystrokes and eliminates mistakes.
4. Set Meaningful Default Values
For variables without expression functions, set sensible defaults in the "Default value" column. For example, in a loop template, default $LIMIT$ to 10 or array.length. Users can override, but a good default means the template often works with just Tab presses.
5. Nest Templates with snippet()
The snippet() expression function lets you compose larger templates from smaller building blocks. Define atomic templates (like a single field declaration) and combine them into larger patterns (like a full builder class skeleton) without duplicating code.
6. Review and Prune Regularly
Templates accumulate over time. Periodically review your list — remove ones you no longer use, update outdated patterns, and ensure abbreviations don't conflict. A bloated template list makes the Ctrl+J popup harder to navigate.
7. Document Custom Templates for the Team
Maintain a simple README or wiki page listing team-specific templates with their abbreviations, expansions, and intended use cases. This onboarding step prevents the "secret productivity features" problem where only senior devs know about the shortcuts.
8. Test Templates in Isolation
When creating complex templates with Groovy scripts or multiple snippet() calls, test them in a scratch file (File → New → Scratch File) before adding to your production template set. Verify the expansion works in all expected contexts.
Surround Templates
IntelliJ also offers Surround Templates — a related feature where you select existing code and wrap it with a template. Access these via Ctrl+Alt+T (Cmd+Opt+T on macOS) or Code → Surround With. Built-in surrounds include:
// Select a block of code, press Ctrl+Alt+T, choose:
// Surround with try-catch
// Surround with if/while/for
// Surround with synchronized
// Surround with Runnable/Callable
You can create custom surround templates in the same Live Templates settings by selecting Surround Template instead of Live Template when adding. The template text uses $SELECTION$ as the placeholder for the wrapped code.
// Custom surround template example
// Abbreviation: lock
// Template text:
synchronized ($LOCK$) {
$SELECTION$
}
// After selecting code and pressing Ctrl+Alt+T, choose 'lock'
// The selected code gets wrapped in a synchronized block
Troubleshooting Common Issues
Template Doesn't Expand
- Check context scopes: The template may not be enabled for the current file type. Go to Settings → Live Templates, select the template, and verify the applicable contexts.
- Check expansion key: If you've remapped Tab, try Ctrl+J (Cmd+J) instead, or use Code → Insert Live Template from the menu.
- Check abbreviation conflicts: Another completion (like a class name) may take priority. Adjust the template's "Expand with" key or rename the abbreviation.
Variables Not Being Replaced
- Ensure correct syntax: Variables must use
$NAME$format with matching dollar signs. Missing the closing$causes the literal text to remain. - Check variable definitions: Open "Edit variables" and confirm each variable has either an expression or a default value, and that the expression function name is spelled correctly.
Groovy Script Not Working
- Validate the script: Test the Groovy expression in IntelliJ's Groovy console (Tools → Groovy Console). The implicit variables
_1,_2, etc., correspond to the referenced template variables. - Check dependencies: Some Groovy operations require specific imports; include them in the script if needed.
Conclusion
IntelliJ IDEA's Live Templates system transforms repetitive coding from a manual chore into an automated, keystroke-efficient workflow. By mastering built-in templates, creating project-specific custom ones, and leveraging expression functions like className() and groovyScript(), you eliminate boilerplate typing, reduce errors, and maintain consistent code patterns across your codebase. The combination of Live Templates, Postfix Completion, and Surround Templates gives you a complete toolkit for code generation that adapts to your specific frameworks and conventions. Start by learning the built-in abbreviations, then gradually build your own template library — the time invested pays for itself within days of consistent use.