Replace selected code from eclipse editor thru plugin command

妖精的绣舞 提交于 2019-11-29 10:24:26

问题


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:


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


来源:https://stackoverflow.com/questions/1233102/replace-selected-code-from-eclipse-editor-thru-plugin-command

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!