Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print selection cursors index in JetBrains' IDEs

Is there a way to access the index of the cursors when multiple selection cursors are active?

Example :

Say I had the following text, with 5 cursors

lo|rem
ip|sum
do|lor
si|t
am|et

With access to the index of the cursors, I could easily make turn it into

lo1rem
ip2sum
do3lor
si4t
am5et
like image 395
Abderrahmane TAHRI JOUTI Avatar asked Feb 12 '19 15:02

Abderrahmane TAHRI JOUTI


1 Answers

You can do this with a plugin by simply iterating over each caret/cursor from getCaretModel().getAllCarets() and inserting a running index. The getAllCarets() method always returns carets sorted by visual order:

public class CaretIndexAction extends AnAction {
    public CaretIndexAction() {
        super("Insert Caret Index(es)");
    }

    public void actionPerformed(AnActionEvent event) {
        Editor editor = PlatformDataKeys.EDITOR.getData(event.getDataContext());
        Document doc = editor.getDocument();

        WriteCommandAction.runWriteCommandAction(event.getProject(), () -> {
            int i = 1;
            for (Caret c : editor.getCaretModel().getAllCarets()) {
                doc.replaceString(c.getSelectionStart(), c.getSelectionEnd(), String.valueOf(i));
                i++;
            }
        });
    }
}

Result:

enter image description here

like image 172
cody Avatar answered Jan 03 '23 01:01

cody