Replace selected code from eclipse editor thru plu

2019-02-05 14:55发布

How do I replace the selected section of code (selected by mouse selection) in eclipse editor and replace it with the same code only in /* selected text */ through a plugin? I have already designed a plugin to create a button in the toolbar. When I click it, I need it to change the text that is selected and put it into /* */.

1条回答
beautiful°
2楼-- · 2019-02-05 15:40

try this snippet, that should give you enough hints to do your job:

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();
}    
查看更多
登录 后发表回答