4

Is it possible to get the full path of the current file within a live template in IntelliJ? I've tried using groovyScript("new File('.').absolutePath") function, but that returns /Applications/IntelliJ IDEA.app/Contents/bin/. and not the file path as I was hoping for.

Thanks!

Adunahay
  • 1,551
  • 1
  • 13
  • 20

2 Answers2

12

According to the docs (emphasis mine):

You can use groovyScript macro with multiple arguments. The first argument is a script text that is executed or a path to the file that contains a script. The next arguments are bound to _1, _2, _3, ..._n variables that are available inside your script. Also, _editor variable is available inside the script. This variable is bound to the current editor.

The _editor is an instance of EditorImpl which holds a reference to the VirtualFile that represents the currently opened file.

Therefore, the following script gets the full path of currently opened file.

groovyScript("_editor.getVirtualFile().getPath()")

Or if you want to get the path relative to the project's root:

groovyScript("_editor.getVirtualFile().getPath().replace(_editor.getProject().getBaseDir().getPath(), \"\")")
fracz
  • 20,536
  • 18
  • 103
  • 149
0

Since IntelliJ IDEA 2019.3 the Live Template macros filePath() and fileRelativePath() are available. A complicated Groovy script macro is no longer required.

Bas Leijdekkers
  • 23,709
  • 4
  • 70
  • 68