Search code examples
intellij-idealive-templates

How do I transform a string with IDEA Live Template?


Given something like:

org.jboss:jboss-remote-naming

...it would be useful to be able to transform it to:

exclude group: "org.jboss", module: "jboss-remote-naming"

Use case is exclusions for Gradle dependencies. Have no idea how to do this though. Could use some tips. I've been to the documentation often enough to know this probably isn't in there, but I will double check.

"exclude group: \""+ "org.jboss.logging:jboss-logging".replaceAll(':','\", module: \"') +"\""

...OK I've figured that you can do the above in the Groovy shell which results in the below:

groovy:000> "exclude group: \""+ "org.jboss.logging:jboss-logging".replaceAll(':','\", module: \"') +"\""
    ===> exclude group: "org.jboss.logging", module: "jboss-logging"

Now, how to get IDEA to use it?


Solution

  • Well, nobody has responded and I've found the answer anyway.

    So the problem is that I've got strings like this on my clip board:

    org.jboss.logging:jboss-logging
    

    I'm using Gradle and IntelliJ IDEA. What I'm doing is fixing a big bunch of dependencies and I want to be able to paste exclusions in in the right form which is:

    exclude group: "org.jboss.logging", module: "jboss-logging"
    

    What I did was:

    1. CTRL+ALT+S | Edit | Live Templates. Note that I've previously created a "User" group herein to put my personal Live Templates. I click "+" to add a new one to the User group.
    2. Set Template Text to: $VAR$$END$
    3. Select the Edit Variables button and set the Expression field to:

      groovyScript("'exclude group: \"'+ _1.replaceAll(':','\", module: \"') +'\"'",clipboard())

    4. Set the Abbreviation field to 'xld'.

    Note the following regarding the text above:

    A. groovyScript executes a short one line Groovy script (or Groovy file for a bigger script). See the docs here: Predefined Functions

    B. Everything is wrapped in "" and then inside those double quotes, every time you want to use a double quote like so: ", you have to escape it with a \. The output has double quotes but aside from that I tried to stick to single quotes.

    C. _1 is a string that represents the result returned by the clipboard() method.

    How to use it: Copy any dependency of the form "org.jboss:jboss-remote-naming" then at the appropriate location in IntelliJ IDEA type xld and then [TAB]. It should expand using the proper syntax for a Gradle exclusion.