views:

258

answers:

1

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 / */

A: 

Hi Catalin,

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