如何在Eclipse中获取选定的代码? [英] How can I get the selected code in Eclipse?

查看:138
本文介绍了如何在Eclipse中获取选定的代码?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

对于我的插件,我试图访问CompilationUnitEditor中选定的代码。因此,我添加了对上下文菜单的贡献,并使用以下代码:

For my plugin I'm trying to access the selected code in a CompilationUnitEditor. Therefore I added a contribution to the context menu and use following code:

public class ContextMenuHandler implements IEditorActionDelegate {

    private IEditorPart editorPart;

    @Override
    public void setActiveEditor(IAction action, IEditorPart editorPart) {
        this.editorPart = editorPart;
    }

    @Override
    public void run(IAction action) {
        JavaUI.getEditorInputJavaElement(editorPart.getEditorInput());
    }

    @Override
    public void selectionChanged(IAction action, ISelection selection) {
        if (selection instanceof TextSelection) {
            TextSelection text = (TextSelection) selection;
            System.out.println("Text: " + text.getText());
        } else {
            System.out.println(selection);
        }
    }

}

现在问题是方法selectionChanged(...)只有当我真的选择一些东西,才能复制/粘贴它。但是我想访问这样突出显示的代码元素(这里我想获得IEditorPart)

Now the problem is that the method selectionChanged(...) is only called when i really select something so that I could copy/paste it. But I want to access the Code elements that are highlighted like this (here I would like to get the "IEditorPart")

不幸的是,我不知道我应该找什么。 >

Unfortunately, I have no idea what I should look for.

推荐答案

使用其他答案的输入,我最终得到以下解决方案:

Using the inputs from the other answers, I ended up with the following solution:

@Override
public void setActiveEditor(IAction action, IEditorPart editorPart) {
    ((CompilationUnitEditor) editorPart).getViewer().addTextListener(new ITextListener() {

        @Override
        public void textChanged(TextEvent event) {
            selectedText = event.getText();
        }
    });

}

这篇关于如何在Eclipse中获取选定的代码?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆