【问题标题】:How to get text from active editor in Eclipse PDE如何从 Eclipse PDE 中的活动编辑器中获取文本
【发布时间】:2013-02-15 15:29:46
【问题描述】:

我有一个处理程序,我想从工作台中的活动编辑器中获取文本。从下面的屏幕截图中,我想获取 Test.java 中的所有内容(“public class Test...”)。

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

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

【问题讨论】:

标签: eclipse eclipse-plugin


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-10-07
      • 2012-03-10
      • 1970-01-01
      • 2015-10-23
      • 1970-01-01
      • 2011-01-24
      • 2015-06-14
      • 2014-08-24
      相关资源
      最近更新 更多