How to modify files in plugin

Answered

Hello,

I want to create a plugin for file read/write operations. The plugin will read the opened file, make changes then save it.

I have an issue with the write process. Whenever I write changes to the file, it directly changes the file system making the undo option unavailable.

 

Currently, I'm doing it like this:

VirtualFile file = event.getData(PlatformDataKeys.VIRTUAL_FILE);
try {
file.setWritable(true);
byte[] newContent = changeContent(file.contentsToByteArray());
file.setBinaryContent(newContent);
} catch (Exception e) {
}

How can I fix it?

1
1 comment

I found the solution in the documentation. Here is how to do it, if someone got interested:

Project project = event.getProject();
VirtualFile file = event.getData(PlatformDataKeys.VIRTUAL_FILE);
Document document = event.getData(PlatformDataKeys.EDITOR).getDocument();
try {
String newContent = changeContent(document.getText());
Runnable r = () -> {
document.setReadOnly(false);
document.setText(newContent);
};
WriteCommandAction.runWriteCommandAction(project, r);
} catch (Exception e) {
}
1

Please sign in to leave a comment.