eclipse plugin: How to programmatically select text in editor?

◇◆丶佛笑我妖孽 提交于 2020-01-01 15:06:55

问题


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.

  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.


来源:https://stackoverflow.com/questions/8775630/eclipse-plugin-how-to-programmatically-select-text-in-editor

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!