Selecting strings is a common thing especially if you want to (a) extract a constant representing it, (b) replace the string with a message bundle key or (c) use it as a search term to look for the same string across the codebase. When refactoring, you’ll sometimes want to delete a method or move it around, requiring you to select the entire method.

The problem is that selecting these can be slow. To select a string you’ll typically move the cursor to the start of the string then select the string using the arrow keys or Ctrl+Shift+Right (select next word) repeatedly until you reach the end of the string which can be slow depending on the number of words in the string. The strategy for methods is similar, move to the start and select but using .

Eclipse has a keyboard shortcut called Select Enclosing Element to make this faster. It allows you to select entire strings from anywhere within the string and methods from anywhere within the method. A bonus is that you do the same thing no matter how big the string/method is.


How to select an entire string

To select an entire string, do the following:

Position the cursor anywhere inside the string or before or after the quotes. Press Alt+Shift+Up. This will select the entire string, regardless of how many words there are.

If the string spans multiple lines, press Alt+Shift+Up once more to select the string across lines.

See the video below for an example of how this works.

How to select an entire method

To select an entire method, do the following:

Position the cursor anywhere inside or at the start/end of the method. Press Alt+Shift+Up several times until the method is selected. Each time you press this key, Eclipse will select the enclosing element of the current selection. Often 4-5 times would be enough but sometimes you’ll need up to 7. Not quite a single keystroke, but close enough since you’re just repeating the same keystroke. If you’ve gone too far with the selection (ie. selected too much), you can press Alt+Shift+Down to take the selection one element back.

Here’s a video with an example of both string and method selection. I select the string to extract a constant and select the method to move it down.

How does this make me work faster?

There is no doubt that selecting strings is faster than the old way (watch the video and see what I mean).

But you might ask how selecting methods is faster than the old way, considering that you have to press the key multiple times. Well, using the Select Enclosing Element technique, you always do one action repeatedly whereas the old method requires different actions depending on the context, eg. where you are in the method, how big the method is, where does it end (did you page down too far?). 90% of the time the former is faster than the latter.




Related Tips