通过插件命令在Eclipse编辑器中替换选定的代码

3

如何通过插件在Eclipse编辑器中替换所选代码部分(由鼠标选择)并将其替换为相同的代码,只不过在/*选定的文本*/中?我已经设计了一个插件来创建工具栏中的按钮。当我点击它时,我需要它更改所选的文本并将其放入/* */中。

1个回答

8

试试这个片段,它应该能够为您提供足够的提示来完成您的工作:

try {               
    IEditorPart part = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
    if ( part instanceof ITextEditor ) {
        final ITextEditor editor = (ITextEditor)part;
        IDocumentProvider prov = editor.getDocumentProvider();
        IDocument doc = prov.getDocument( editor.getEditorInput() );
        ISelection sel = editor.getSelectionProvider().getSelection();
        if ( sel instanceof TextSelection ) {
            final TextSelection textSel = (TextSelection)sel;
            String newText = "/*" + textSel.getText() + "*/";
            doc.replace( textSel.getOffset(), textSel.getLength(), newText );
        }
    }
} catch ( Exception ex ) {
    ex.printStackTrace();
}    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接