1

I am trying to make my life easier with Live Templates in intelliJ I need to increment some param by 1 every-time I use the snippet.

So I tried to develop some groovyScript, and I am close, but my groovy capabilities keeps me back. the number is not incremented by 1, but incremented by 57 for some reason... (UTF-8?)

here is the script:

File file = new File("out.txt");
int code = Integer.parseInt(file.getText('UTF-8'));
code=code+1;
try{
    if(_1){
        code = Integer.parseInt(_1);
    }
} catch(Exception e){}
file.text = code.toString();
return code

So whenever there's param passed to this script (with _1) the initial value is set, and otherwise simply incremented.

this script needs to be passed to the live template param with:

groovyScript("File file = new File(\"out.txt\");int code = Integer.parseInt(file.getText(\'UTF-8\'));code=code+1;String propName = \'_1\';if(this.hasProperty(propName) && this.\"$propName\"){code = Integer.parseInt(_1);};file.text =code.toString();return code", "<optional initial value>") 

here is the way it looks in intelliJ

Noyloy
  • 134
  • 1
  • 6
  • I had to create the out.txt file and explicitly specify the path to it (in the groovy script) to be able to reproduce your example. Can you confirm this? Then I get the same result, sort of... It increments with 15, ha! I did notice that it shows a sort of completion where it does the +1 though. For example, if the old value is 1, it inserts 15 and shows 16 in the completion drop down (which will be inserted when hitting enter). Did you also get that behaviour? Out of curiosity, would you mind sharing a use case? – Abby Jun 03 '20 at 16:39
  • I also don't think that saving your variable to a file would be the way to go, but at the moment I don't see another way to achieve what you want; you'll have to save the variable somewhere/somehow. Hence asking for your use case, there might be a completely different way of achieving your goal :) – Abby Jun 03 '20 at 16:45
  • yes I can share my use case.. I am constructing and maintaining an ongoing xml that contains messages entities that has code value, which needs to be incremented by 1 each time I need to insert new message. I know there are different xml building tools outside intelliJ but I enjoyed the groovy challenge.. :-) – Noyloy Jun 03 '20 at 17:24
  • I'm not entirely sure if I understand what exactly you're going for, but I certainly agree with the fun of playing with these kind of things :) – Abby Jun 03 '20 at 17:59

0 Answers0