in code_samples/editor_basics/src/main/java/org/intellij/sdk/editor/EditorIllustrationAction.java [32:51]
public void actionPerformed(@NotNull final AnActionEvent e) {
// Get all the required data from data keys
// Editor and Project were verified in update(), so they are not null.
final Editor editor = e.getData(CommonDataKeys.EDITOR);
if (editor == null) return;
final Project project = e.getData(CommonDataKeys.PROJECT);
if (project == null) return;
final Document document = editor.getDocument();
// Work off of the primary caret to get the selection info
Caret primaryCaret = editor.getCaretModel().getPrimaryCaret();
int start = primaryCaret.getSelectionStart();
int end = primaryCaret.getSelectionEnd();
// Replace the selection with a fixed string.
// Must do this document change in a write action context.
WriteCommandAction.runWriteCommandAction(project, () ->
document.replaceString(start, end, "Replacement")
);
// De-select the text range that was just replaced
primaryCaret.removeSelection();
}