Eclipse plugin: how to programmatically select text in an editor?

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

+3
source share
2 answers

I was unable to get Andrew answer to work in Eclipse 3.7. The compiler gave this error:

  The method getSourceViewer () from the type AbstractTextEditor is not visible. 

However, I managed 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); 
+5
source

If you already have a handle to the current editor, you can do:

 editor.getSourceViewer().setSelectedRange(offset, length); 

If you do not have a handle to the current editor, you need to do some work to get there (subject to a text editor):

 TextEditor editor = (TextEditor) PlatformUI.getWorkbench().getActiveWorkbenchWindow() .getActivePage().getActiveEditor(); 

Although this will work, I have simplified a few things.

  • You need to make sure that the active editor is really a TextEditor , so you want to make an instance of test
  • Sometimes the different parts of the long phrase above can be null (for example, at startup or shutdown). I tend to just wrap the expression in a try-catch block (NPE) and assume that if the NPE is thrown, then the editor is not available.
0
source

Source: https://habr.com/ru/post/924491/


All Articles