如何从Eclipse PDE中的活动编辑器获取文本

时间:2013-02-15 15:29:46

标签: eclipse eclipse-plugin

我有一个处理程序,我希望在工作台中从活动编辑器中获取文本。从下面的屏幕截图中,我想了解Test.java中的所有内容("公共类测试......")。

Test class screenshot

我在" Source"下添加了一个新命令。菜单成功。只是不确定从哪里获取活动编辑器中的文本。这是我到目前为止尝试获取文本的内容(它只是在弹出窗口中显示文件名):

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;
    }
}

2 个答案:

答案 0 :(得分:2)

获得IEditorPart后,您可以尝试以下操作:

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

答案 1 :(得分:0)

或者来自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();

   ...
 }