WriteCommandAction deleting values instead replacing
Answered
Here is my code written in one on AnAction classes:
@Override
public void actionPerformed(@NotNull AnActionEvent e) {
//get current file
PsiFile currentFile = e.getData(LangDataKeys.PSI_FILE);
//find element for replacement
final PsiElement[] last = new PsiElement[1];
currentFile.accept(new PsiRecursiveElementWalkingVisitor() {
@Override
public void visitElement(@NotNull PsiElement element) {
if(element.getText().equals("property")) {
last[0] = findValue(element);
}
super.visitElement(element);
}
});
WriteCommandAction.runWriteCommandAction(e.getProject(), () -> {
var what = PsiFileFactory.getInstance(e.getProject())
.createFileFromText(PlainTextLanguage.INSTANCE, "it's value");
last[0].replace(what.getLastChild());
});
}
one more function used within visitElement
private PsiElement findValue(PsiElement element) {
if (element.getNextSibling() != null) {
return findValue(element.getNextSibling());
}
return element;
}
Sample of properties when code is working and replacement is happen:
one=1
two=2
three=3
property=x
But once I change property
position to this:
one=1
two=2
property=x
three=3
and click 3 times my action button for created AnActionEvent, it will just remove whole line:
click 1:
one=1
two=2
property=
three=3
click 2:
one=1
two=2
property
three=3
click 3:
one=1
two=2
three=3
Any suggestion on how to replace property regardles of it's position in the opened file ?
Please sign in to leave a comment.
Is this in a .properties file? Why do you generate the new value using
PlainTextLanguage.INSTANCE
then and notcom.intellij.lang.properties.PropertiesLanguage
Yann Cebron hi thx for reply, but this class is not available at least for me, should I add dependency for this pack ?
You must add dependency on Properties plugin https://plugins.jetbrains.com/docs/intellij/plugin-dependencies.html#1-locating-plugin-id-and-preparing-sandbox, Plugin ID
com.intellij.properties
Actually I just checked with proposed
PropertiesLanguage.INSTANCE
and seems this not help, still removing value on clickWhen this happen I got this ST:
Ok I managed to solve that, for those who stuck with the same:
first need to find element you want to replace in PsiFile
then create new PsiFile but first replace using regex content to desired ones
then in created PsiFile find element you replaced content for
and finaly
replace opened file with element you found in created file, like this: