4

I want to programmatically jump to a position in the text editor and highlight code.

2
  • 1
    The 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. Commented Jan 8, 2012 at 5: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: github.com/Nodeclipse/EditBox Commented May 16, 2018 at 9:10

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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.

  1. You need to make sure that the active editor really is a TextEditor, so you are going to want to do an instanceof test
  2. 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.