in PluginsAndFeatures/azure-toolkit-for-intellij/azure-intellij-plugin-bicep/src/main/java/org/wso2/lsp4intellij/editor/EditorEventManager.java [1050:1131]
public Runnable getEditsRunnable(int version, List<Either<TextEdit, InsertReplaceEdit>> edits, String name, boolean setCaret) {
if (version < this.documentEventManager.getDocumentVersion()) {
LOG.warn(String.format("Edit version %d is older than current version %d", version, this.documentEventManager.getDocumentVersion()));
return null;
}
if (edits == null) {
LOG.warn("Received edits list is null.");
return null;
}
if (editor.isDisposed()) {
LOG.warn("Text edits couldn't be applied as the editor is already disposed.");
return null;
}
Document document = editor.getDocument();
if (!document.isWritable()) {
LOG.warn("Document is not writable");
return null;
}
return () -> {
// Creates a sorted edit list based on the insertion position and the edits will be applied from the bottom
// to the top of the document. Otherwise all the other edit ranges will be invalid after the very first edit,
// since the document is changed.
List<LSPTextEdit> lspEdits = new ArrayList<>();
edits.forEach(edit -> {
if(edit.isLeft()) {
String text = edit.getLeft().getNewText();
Range range = edit.getLeft().getRange();
if (range != null) {
int start = DocumentUtils.LSPPosToOffset(editor, range.getStart());
int end = DocumentUtils.LSPPosToOffset(editor, range.getEnd());
lspEdits.add(new LSPTextEdit(text, start, end));
}
} else if(edit.isRight()) {
String text = edit.getRight().getNewText();
Range range = edit.getRight().getInsert();
if (range != null) {
int start = DocumentUtils.LSPPosToOffset(editor, range.getStart());
int end = DocumentUtils.LSPPosToOffset(editor, range.getEnd());
lspEdits.add(new LSPTextEdit(text, start, end));
} else if ((range = edit.getRight().getReplace()) != null) {
int start = DocumentUtils.LSPPosToOffset(editor, range.getStart());
int end = DocumentUtils.LSPPosToOffset(editor, range.getEnd());
lspEdits.add(new LSPTextEdit(text, start, end));
}
}
});
// Sort according to the start offset, in descending order.
Collections.sort(lspEdits);
lspEdits.forEach(edit -> {
String text = edit.getText();
int start = edit.getStartOffset();
int end = edit.getEndOffset();
if (StringUtils.isEmpty(text)) {
document.deleteString(start, end);
if (setCaret) {
editor.getCaretModel().moveToOffset(start);
}
} else {
text = text.replace(DocumentUtils.WIN_SEPARATOR, DocumentUtils.LINUX_SEPARATOR);
if (end >= 0) {
if (end - start <= 0) {
document.insertString(start, text);
} else {
document.replaceString(start, end, text);
}
} else if (start == 0) {
document.setText(text);
} else if (start > 0) {
document.insertString(start, text);
}
if (setCaret) {
editor.getCaretModel().moveToOffset(start + text.length());
}
}
saveDocument();
});
};
}