如何在Eclipse中获取所选代码?

6 java eclipse eclipse-plugin

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

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

}
Run Code Online (Sandbox Code Playgroud)

现在的问题是方法selectionChanged(...)仅在我真正选择某些内容时调用,以便我可以复制/粘贴它.但我想访问像这样突出显示的代码元素(这里我想得到"IEditorPart")

在此输入图像描述

不幸的是,我不知道我应该寻找什么.

And*_*erg 7

你应该做这个:

        ((CompilationUnitEditor) editorPart).getViewer().getSelectedRange();
Run Code Online (Sandbox Code Playgroud)

ISourceViewer关于源位置和编辑器,该类有许多有用且有趣的方法.你可能也想看看JavaSourceViewer.


编辑

看起来我没有完全回答你的问题.问题是selectionChanged事件只在选择的长度> 0时才被调用.我不知道为什么会这样,但这就是动作委托一直工作的方式.

如果您希望在插入符更改时收到通知,则应该使用编辑器的查看器注册选择更改的侦听器.做这样的事情:

((CompilationUnitEditor) editorPart).getViewer()
  .addSelectionChangedListener(mySelectionListener);
Run Code Online (Sandbox Code Playgroud)

mySelectionListener是类型的org.eclipse.jface.viewers.ISelectionChangedListener.以这种方式注册,应该为您提供您正在寻找的所有活动.编辑关闭时要小心取消注册.


小智 1

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

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

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

}
Run Code Online (Sandbox Code Playgroud)