blob: 692fd6c345444a669c1c372c104f622e98fab4dd (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
|
package me.laria.code.idea_caseconv;
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.Caret;
import com.intellij.openapi.editor.CaretModel;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.editor.Editor;
import com.intellij.openapi.project.Project;
import java.util.ArrayList;
abstract class SelectionReplacerAction extends AnAction {
@Override
public void update(final AnActionEvent e) {
//Get required data keys
final Project project = e.getData(CommonDataKeys.PROJECT);
final Editor editor = e.getData(CommonDataKeys.EDITOR);
//Set visibility only in case of existing project and editor and if some text in the editor is selected
e.getPresentation().setVisible(
project != null
&& editor != null
&& editor.getSelectionModel().hasSelection()
);
}
@Override
public void actionPerformed(AnActionEvent anActionEvent) {
Editor editor = anActionEvent.getData(CommonDataKeys.EDITOR);
Project project = anActionEvent.getData(CommonDataKeys.PROJECT);
assert editor != null;
assert project != null;
CaretModel caretModel = editor.getCaretModel();
Document document = editor.getDocument();
ArrayList<Replacement> replacements = new ArrayList<>();
for (Caret caret : caretModel.getAllCarets()) {
if (!caret.hasSelection()) {
continue;
}
replacements.add(new Replacement(
caret.getSelectionStart(),
caret.getSelectionEnd(),
this.replace(caret.getSelectedText())
));
}
// Sort in reverse order so a replacement won't mess up the indices of the other replacements
replacements.sort((o1, o2) -> -o1.compareTo(o2));
WriteCommandAction.runWriteCommandAction(project, () -> replacements.forEach(r -> r.doReplace(document)));
}
abstract protected String replace(String s);
}
|