package com.fwdekker.randomness;

import com.intellij.openapi.actionSystem.AnAction;
import com.intellij.openapi.actionSystem.AnActionEvent;
import com.intellij.openapi.actionSystem.CommonDataKeys;
import com.intellij.openapi.command.WriteCommandAction;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;


/**
 * Inserts a randomly generated string at the position of the event's editor's caret.
 */
public abstract class InsertRandomSomething extends AnAction {
    /**
     * Inserts the string generated by {@link #generateString()} at the caret in the editor.
     *
     * @param event the performed action
     */
    @Override
    public void actionPerformed(final AnActionEvent event) {
        final Editor editor = event.getData(CommonDataKeys.EDITOR);
        if (editor == null) {
            return;
        }
        final Project project = event.getData(CommonDataKeys.PROJECT);
        final Document document = editor.getDocument();
        final CaretModel caretModel = editor.getCaretModel();

        caretModel.getAllCarets().forEach(caret -> {
            final int start = caret.getSelectionStart();
            final int end = caret.getSelectionEnd();

            final Runnable runnable = () -> document.replaceString(start, end, generateString());
            WriteCommandAction.runWriteCommandAction(project, runnable);
        });
    }


    /**
     * Generates a random string.
     *
     * @return a random string
     */
    protected abstract String generateString();
}

@@ -1296,24 +1296,133 @@
 tionEnd();%0A%0A
+            final String string = generateString();%0A            final int newEnd = start + string.length();%0A%0A
             
@@ -1452,16 +1452,34 @@
  = () -%3E
+ %7B%0A               
  documen
@@ -1510,25 +1510,81 @@
 nd, 
-generateString())
+string);%0A                caret.setSelection(start, newEnd);%0A            %7D
 ;%0A  

Fix #3