Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Grab selected text from Eclipse Java editor

I'm developing an Eclipse plug-in where upon pressing a button, the plug-in takes the selected text in the Java editor and puts in a text box which appears.

My code looks like this: I got it from here: http://dev.eclipse.org/newslists/news.eclipse.newcomer/msg02200.html

private ITextSelection getSelection(ITextEditor editor) {
     ISelection selection = editor.getSelectionProvider()
            .getSelection();
     return (ITextSelection) selection;
}

private String getSelectedText(ITextEditor editor) {
     return getSelection(editor).getText();
}

The problem is how will I get the ITextEditor of the Java editor being displayed. Coincidentally it's the next question in the thread in the link I posted but it's unanswered :(

like image 266
Krt_Malta Avatar asked Mar 07 '10 10:03

Krt_Malta


1 Answers

You could ask for the ActiveEditor, as in this thread:

IEditorPart part;

part =
PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().get
ActiveEditor();

if(part instanceof ITextEditor){
    ITextEditor editor = (ITextEditor)part;
    IDocumentProvider provider = editor.getDocumentProvider();
    IDocument document = provider.getDocument(editor.getEditorInput());

The OP Krt_Malta mentions this blog entry "Programmatically query current text selection", which is similar to this other SO answer (written before the blog entry) "Replace selected code from eclipse editor through plugin command".

like image 146
VonC Avatar answered Oct 04 '22 03:10

VonC