Document changes not flushed when IDE is not focused

Answered

I have plugin process running as a thread (executeOnPooledThread) and it performs document update using

 vfsDoc.setText(content)
PsiDocumentManager.getInstance(project).commitDocument(vfsDoc)

If IDE window is not focused (I am doing different things in a meantime) changes are not flushed to filesystem. When I click anywhere on IDE it gets flushed immediately.

How to force file flushing? I was trying VfsUtil.markDirtyAndRefresh(false, false, false, vfsFile) but it's not working.

0
1 comment

Ok, ChatGPT solved issue:

To force file changes to be flushed to the filesystem in an IntelliJ plugin, you can use the FileDocumentManager and VirtualFile APIs. Here's how you can modify your code to ensure that changes are properly flushed:

import com.intellij.openapi.application.ApplicationManager;
import com.intellij.openapi.editor.Document;
import com.intellij.openapi.fileEditor.FileDocumentManager;
import com.intellij.openapi.project.Project;
import com.intellij.openapi.vfs.VirtualFile;
import com.intellij.psi.PsiDocumentManager;

public class MyPlugin {

    public void updateDocumentContent(Project project, VirtualFile vfsFile, String content) {
        // Retrieve the document associated with the virtual file
        Document document = FileDocumentManager.getInstance().getDocument(vfsFile);
        if (document != null) {
            // Perform document updates
            ApplicationManager.getApplication().runWriteAction(() -> {
                document.setText(content);
                PsiDocumentManager.getInstance(project).commitDocument(document);
            });

            // Flush changes to the filesystem
            ApplicationManager.getApplication().invokeLater(() -> {
                FileDocumentManager.getInstance().saveDocument(document);
                vfsFile.refresh(true, false);
            });
        }
    }
}

In this code:

  1. We first retrieve the Document associated with the VirtualFile using FileDocumentManager.getInstance().getDocument(vfsFile).
  2. We then perform the document updates inside a write action using ApplicationManager.getApplication().runWriteAction().
  3. After making the changes, we invoke FileDocumentManager.getInstance().saveDocument(document) to save the document to the filesystem.
  4. Finally, we refresh the VirtualFile using vfsFile.refresh(true, false) to ensure that the changes are reflected immediately in the IDE.

By using FileDocumentManager.getInstance().saveDocument(document), we explicitly trigger the save operation for the document, ensuring that the changes are flushed to the filesystem. Additionally, by calling vfsFile.refresh(true, false), we ensure that the changes are immediately reflected in the IDE.

0

Please sign in to leave a comment.