Zack Macomber
Zack Macomber

Reputation: 6905

How to get text from active editor in Eclipse PDE

I have a handler in which I would like to get the text from the active editor in my workbench. From the screenshot below, I would like to get everything inside of Test.java ("public class Test...").

Test class screenshot

I've added a new command under the "Source" menu successfully. Just not sure where to get the text from the active editor now. Here's what I have so far in my attempt to get the text (it's just displaying the file name in a popup):

package generatebuilderproject.handlers;

import org.eclipse.core.commands.AbstractHandler;
import org.eclipse.core.commands.ExecutionEvent;
import org.eclipse.core.commands.ExecutionException;
import org.eclipse.ui.IEditorPart;
import org.eclipse.ui.IWorkbenchWindow;
import org.eclipse.ui.handlers.HandlerUtil;
import org.eclipse.jface.dialogs.MessageDialog;

public class GenerateBuilderHandler extends AbstractHandler {

    public GenerateBuilderHandler() {
    }

    public Object execute(ExecutionEvent event) throws ExecutionException {
        IWorkbenchWindow window = HandlerUtil.getActiveWorkbenchWindowChecked(event);
        IEditorPart editorPart = HandlerUtil.getActiveEditor(event);

        MessageDialog.openInformation(
                window.getShell(),
                "GenerateBuilderProject",
                editorPart.getEditorInput().getName());
        return null;
    }
}

Upvotes: 2

Views: 3158

Answers (2)

Developer
Developer

Reputation: 483

Or from here

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

if (editor instanceof ITextEditor)
 {
   ITextEditor textEditor = (ITextEditor)editor;

   IDocumentProvider provider = textEditor.getDocumentProvider();

   IEditorInput input = editor.getEditorInput();

   IDocument document = provider.getDocument(input);

   String text = document.get();

   ...
 }

Upvotes: 2

tobias_k
tobias_k

Reputation: 82889

Once you have the IEditorPart, you can try the following:

IEditorInput input = editorPart.getEditorInput();
if (input instanceof FileEditorInput) {
    IFile file = ((FileEditorInput) input).getFile();
    InputStream is = file.getContents();
    // TODO get contents from InputStream
}

Upvotes: 3

Related Questions