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.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.editor.SelectionModel;
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 Project project = event.getData(CommonDataKeys.PROJECT);
        final Editor editor = event.getData(CommonDataKeys.EDITOR);
        if (editor == null) {
            return;
        }
        final Document document = editor.getDocument();
        final SelectionModel selectionModel = editor.getSelectionModel();

        final int start = selectionModel.getSelectionStart();
        final int end = selectionModel.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();
}

@@ -239,32 +239,79 @@
 eCommandAction;%0A
+import com.intellij.openapi.editor.CaretModel;%0A
 import com.intel
@@ -873,79 +873,8 @@
 ) %7B%0A
-        final Project project = event.getData(CommonDataKeys.PROJECT);%0A
     
@@ -997,16 +997,87 @@
       %7D%0A
+        final Project project = event.getData(CommonDataKeys.PROJECT);%0A
         
@@ -1142,32 +1142,24 @@
 nal 
-SelectionModel selection
+CaretModel caret
 Mode
@@ -1172,25 +1172,21 @@
 itor.get
-Selection
+Caret
 Model();
@@ -1183,24 +1183,81 @@
 etModel();%0A%0A
+        caretModel.getAllCarets().forEach(caret -%3E %7B%0A    
         fina
@@ -1270,30 +1270,21 @@
 start = 
-selectionModel
+caret
 .getSele
@@ -1297,32 +1297,36 @@
 tart();%0A        
+    
 final int end = 
@@ -1329,22 +1329,13 @@
 d = 
-selectionModel
+caret
 .get
@@ -1347,24 +1347,28 @@
 tionEnd();%0A%0A
+    
         fina
@@ -1457,16 +1457,20 @@
         
+    
 WriteCom
@@ -1522,16 +1522,28 @@
 nable);%0A
+        %7D);%0A
     %7D%0A%0A%0A

Support multiple carets