intellij structural replaceDec 9, 2015 · 2 minute read · Comments
intellij’s structural search and replace is an amazing feature that can save a lot of time. the value of this feature first hit home in the excellent Android Studio for Experts talk during Android Dev Summit 2015 (excellent video if you haven’t already seen it, btw!)
today, i was trying to replace my usages of
android.util.Log.* with Timber. to use Timber, we’d need to manually replace
Log.d(TAG, "message"); with
Timber.d("message");, and the same for
Log.w, and so on. there’s also a version of
Log.* that takes in an exception as a paramter that we have to keep in mind as well.
sounds like a perfect job for structural search - we bring it up by using
⌘ + shift + A to search for actions. type
Structurally, and choose
so to do this, set the search template to:
set the replacement template to:
note that the fully qualified domain name in the replacement ensures that the import is handled for you, as long as shorten fully qualified names is checked.
Edit variables, choose
params on the left, and click the
unlimited box by maximum count. this is so that we match both
Log.d(TAG, "message"); and
Log.d(TAG, "message", exception);.
some notes about the options:
- shorten fully qualified names replaces things like
- reformat according to style will fix the indentation if it’s wrong.
- use static import if possible will prefer
import static- i’ve unchecked this because i’ve found that it did this for many things that i didn’t want it done for.
and there you have it. as always, source control is your friend, so make sure to do this on a branch where you can validate the changes and easily roll back if things aren’t quite right.