问题
I want to programmatically jump to a position in the text editor and highlight code.
回答1:
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);
回答2:
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.
来源:https://stackoverflow.com/questions/8775630/eclipse-plugin-how-to-programmatically-select-text-in-editor