intellij structural replace
Dec 9, 2015 · 2 minute readcode
android
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.e
, 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 Replace Structurally
.
we’ll get a dialog that we’ll fill out like this:
so to do this, set the search template to:
android.util.Log.$something$($tag$, $params$);
set the replacement template to:
timber.log.Timber.$something$($params$);
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.
finally, choose 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
android.util.Log.d
withLog.d
. - 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.