I want to programmatically jump to a position in the text editor and highlight code.
Asked
Active
Viewed 3,245 times
4
-
1The Eclipse API is a maze. I could find plenty of google hits on how to "get" the current selection, but not to "set" the selection. – kostmo Jan 08 '12 at 05:40
-
found this via googleling (not directly on-topic) ... if you want to mark a block of code semi-automatically (e.g. some `sql` block/query inside some `plsql` function) for execution (e.g. in `SQL File Editor`) you could use the pretty generic *Nodeclipse Editor Plugin* with `ALT+Z` on the currrently hovered/marked block: https://github.com/Nodeclipse/EditBox – Andreas Covidiot May 16 '18 at 09:10
2 Answers
6
I wasn't able to get Andrew's answer to work in Eclipse 3.7. The compiler gave this error:
The method getSourceViewer() from the type AbstractTextEditor is not visible.
However, I was able to get it to work with the selectAndReveal()
method:
IFile myfile = ...
IWorkbenchPage page = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage();
ITextEditor editor = (ITextEditor) IDE.openEditor(page, myfile);
editor.selectAndReveal(offset, length);
1
If you already have a handle on the current editor, then you can do:
editor.getSourceViewer().setSelectedRange(offset, length);
If you don't have a handle on the current editor, then you need to do some work to get there (assuming a text editor):
TextEditor editor = (TextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow()
.getActivePage().getActiveEditor();
Although this will work, I've simplified a few things.
- You need to make sure that the active editor really is a
TextEditor
, so you are going to want to do an instanceof test - Sometimes various parts of the long phrase above can be null (eg- during startup or shutdown). I tend to just wrap the expression in a try-catch(NPE) block and assume that if an NPE is thrown, then the editor is not available.

Andrew Eisenberg
- 28,387
- 9
- 92
- 148