3 Awesome Ways to Use Pycharm/IntelliJ/Webstorm Live Templates

The IntellIJ family of IDEs (IntelliJ IDEA, WebStorm, RubyMine, PyCharm etc) all support Live Templates, which I find extremely helpful to my work. In JetBrains’ own words:

Live templates let you insert frequently-used or custom code constructs into your source code file quickly, efficiently, and accurately.

In summary: you type a shortcut, you press your “expansion key” (usually tab), and the template expands. Here are three ways I use Live Templates to boost my productivity.

Conforming to coding standards

My team prefers our mocha test cases be written in a “should… when” style, ie it('should X when Y', function() { /* stuff goes here */ } ). I’ve been rumbled in code review a few times on this, so I made a Live Template that helps me adhere to the standard. Here’s how it looks:

it('should $SHOULD$ when $WHEN$', function() {

I’ve abbreviated this block so that whenever I’m in a JS file and I type it followed by tab, it expands as follows:

Notice that when I hit tab, it goes to the next placeholder in the template. Easy!

Fast, sloppy debugging

Before I discovered this next technique, I would pepper my serverside code with debug statements like var_dump('here'); or var_dump('foo'); while trying to diagnose an issue. Coming up with unique dumb strings for var_dump gets tricky after the first ten, so I decided to let IntelliJ name them for me.

In this next example, I take advantage of IntelliJ’s ability to run Groovy code in Live Templates. I don’t know Groovy at all, but it’s a JVM language, so you can use the standard Java library. The template, which I have abbreviated to vvaarr, looks like:


In the “Edit Variables” pane, I’ve set the $RANDO$ variable as follows:

groovyScript("String.format('%X', new Random().nextLong())")

This generates a random number and formats it as a hex string. The result looks something like var_dump("E41C2F2794389D6B"); Here’s how it looks in practice:

Now I don’t need to think about the strings to put in my debug statements. I can hit vvaarr-tab all over my code, look at the program output, and immediately connect the breakage to a location in the code.

(yes, I know I should set up a PHP debugger…)

Surrounding code

This technique takes advantage of Live Templates’ reserved $SELECTION$ variable, which represents whatever is currently selected in the editor. Sometimes when I write JavaScript I want to wrap a block of code in a function, so I can reuse it elsewhere. This is super easy with Live Templates. Here’s what the template looks like:

function $FN_NAME$ () {

In action:

Don’t forget to set “Reformat according to style”, so that the block is indented per your settings.

In conclusion

I hope this post has given you some inspiration on how you can use IntelliJ Live Templates to make your coding life more productive. Enjoy!