We've developed a plugin that retrieves data from a third-party API and inserts it into the editor. We need to apply specific styling to the inserted content, which should persist until the user performs the next action (e.g., pressing a key).
Currently, the text insertion and initial styling application work correctly. However, the style is immediately removed.
Code:
public Object execute(ExecutionEvent event) throws ExecutionException {
IEditorPart editor = PlatformUI.getWorkbench().getActiveWorkbenchWindow().getActivePage().getActiveEditor();
if (!(editor instanceof ITextEditor))
return null;
try {
final ITextEditor textEditor = (ITextEditor) editor;
final IDocument document = textEditor.getDocumentProvider().getDocument(textEditor.getEditorInput());
final ITextViewer iTextViewer = (ITextViewer) textEditor.getAdapter(ITextViewer.class);
if (iTextViewer == null) {
return null;
}
styledText = iTextViewer.getTextWidget();
int insertPosition = styledText.getCaretOffset();
RestPayload job = new RestPayload();
job.addJobChangeListener(new JobChangeAdapter() {
@Override
public void done(IJobChangeEvent event) {
if (event.getResult() != null) {
IStatus result = event.getResult();
Display.getDefault().asyncExec(() -> {
if (result.isOK()) {
try {
String generatedCode = job.getPayload();
document.replace(insertPosition, 0, generatedCode);
suggestionStyle = new StyleRange();
suggestionStyle.start = insertPosition;
suggestionStyle.foreground = new Color(Display.getDefault(), 192, 192, 192);
suggestionStyle.length = generatedCode.length();
styledText.setStyleRange(suggestionStyle);
styledText.update();
Display.getDefault().timerExec(2000, () -> {
styledText.setStyleRange(suggestionStyle);
styledText.redraw();
});
} catch (Exception ex) {
logger.warn("Error inserting/styling code", ex);
}
} else {
showAlert("Code Assist Error", "Code assist failed: " + result.getMessage());
}
});
}
}
});
job.schedule();
} catch (Throwable eGenThrowable) {
showAlert("Issue", eGenThrowable.getMessage());
eGenThrowable.printStackTrace();
logger.warn("Issue while exchanging data", eGenThrowable);
}
return styledText;
}
Note:
Display.getDefault().timerExec(1000, () -> {
styledText.setStyleRange(suggestionStyle);
styledText.redraw();
});
The above code snippet obscures the inserted code. However, it is not an applicable solution.
AbstractTextEditoror one of its many subclasses? If so you can't just mess with the StyledText directly because the editor code is managing it and will overwrite your changes as it sees fit. You must use one of the APIs provided by the editor.editor.getSite().getId()should give you the plug-in id of the editor.