File creation in my plug-in (undo/redo)

Answered

I created a plug-in that create specific file to current project.

I use java.io.File class and .createNewFile(); function...

It works OK but undo button is still disabled.

 

In intellij, File > New > (any type of file..) process is done, undo button enabled, and when i clicked that button, intelliJ asked to me, 

"Are you sure to cancel create file?" and if i select "yes", it delete the new file....

 

 

Is there any way to create a new file ? I want to undo-able creation process.

5 comments
Comment actions Permalink
Official comment

You should use VFS (or better PSI) to create files, either VirtualFile.createChildData(this, name) or PsiDirectory.add(file) where file = PsiFileFactory.getInstance(project).createFileFromText(). You should also wrap the entire creation operation into a command and write action, by using WriteCommandAction.performWriteCommandAction(project, ...)

Comment actions Permalink

Dear Peter Gromov, 

Thank you for your reply! I successfully create a file with your guide, but after creating, undo button is still disabled. 

Creating a file should be add to the stack(?), but i cannot know how to do it....

Can you explain more about it?

0
Comment actions Permalink

i really sorry, but it shows undo button

VirtualFile baseDir = e.getProject().getBaseDir();
final VirtualFile targetDir = baseDir.getFileSystem().findFileByPath("C:\\Users\\Jonghun\\IdeaProjects\\textProject\\src");
if(targetDir != null) {
WriteCommandAction.runWriteCommandAction(e.getProject(), new Runnable() {
@Override
public void run() {
try {
targetDir.createChildData(this, System.currentTimeMillis()+".txt");
} catch (IOException e1) {
e1.printStackTrace();
}
}
});
}

 

But, if i click undo button, it deleted the file. (Why intelliJ does NOT show question? "Are you sure......" )

Is it because the new file have no contents in it?

 

 

0
Comment actions Permalink

I see. Then, instead of runWriteCommandAction, you'd need to create an anonymous WriteCommandAction instance and execute() it, plus override getUndoConfirmationPolicy method. By default it's DO_NOT_REQUEST_CONFIRMATION, you'll need to return REQUEST_CONFIRMATION instead.

BTW baseDir.getFileSystem() is the same as LocalFileSystem.getInstance().

0
Comment actions Permalink

Dear Peter Gromov,

Thank you for your help! I will try it!

0

Please sign in to leave a comment.