Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Use IntelliJ structural search to replace field and its expression with new field

I want to use ButterKnife for Android. I need to annotate some fields based on some expressions which are elsewhere in code. I have code like this

private String myField;
...
public myClassConstructor() {
    ...
    myField = res.getString(R.string.my_string_id);
    ...
}

I want this

@BindString(R.string.my_string_id);
String myField;
...
public myClassConstructor() {
    ...
    ...
}

In the result the expression is gone, and the field is annotated based on the old expression.

Is it possible to do this kind of search and replace in IntelliJ's structural replace? It seems it does not gracefully handle the case when the lines of interest are not adjacent and are in different locations structurally. I tried basing it on class template, and used $Statement$ (0-unbounded occurrences) but it did not work for me.

I realized its actually relatively simple to do with regular expressions, certainly much simpler than getting IntelliJ structural search to play ball, but I like to learn my tools, so I would still like to know if this is possible.

like image 710
arberg Avatar asked Oct 19 '22 17:10

arberg


1 Answers

While Search structurally is somehow working and it's possible to make search query, replace structuraly is kind of tools which was made by "aliens" for "predators". I hope that intelliJ team will revisit this feature and will make it more usable/understandable.

I was trying by myself to make Replace structurally query, but I could only make Search structurally clause.

I have done it with Mockito lib for example.

Structural search dialog

One of the key points here to put for $SomeStatement1$ and $SomeStatement2$ min and max count to {0, Unlimited}

enter image description here

And from this point I've tried to come with replacement clause but It was completely messing out scope of the method/fields declaration/class.

Hope this helps.

like image 162
Igor Konoplyanko Avatar answered Oct 21 '22 06:10

Igor Konoplyanko