Detect if file is completion copy from Document/VirtualFile?

In my plugin I have a DocumentListener which I use to record changes happening to documents for later post-processing. I'd like to detect if a given Document is actually a file copy for completion purposes, either from the Document itself or from the VirtualFile. I know I can do this by checking psiFile.originalFile, but if I call PsiDocumentManager.getPsiFile(), then that will cause the PSI to be parsed on every document modification.

Currently I'm calling PsiDocumentManager.getCachedPsiFile(), and if that returns non-null then I use the originalFile check as above, and otherwise I assume the Document is not a completion copy. This seems to work, but I'm unsure if it's a reliable method. Is there a better way to do this?

4 comments
Comment actions Permalink
Official comment

This looks like a valid approximate way to detect a completion copy. I say "approximate" because there are other clients (e.g. live templates, or some inspections) who also copy a file and modify the copy's document. Unfortunately there's no reliable way to detect that it's precisely a completion copy.

If you only care about the document being "physical", you could check its VirtualFile#isInLocalFileSystem or !(instanceof LightVirtualFile) or something like that.

Comment actions Permalink

I actually didn't realise that copies were made under other circumstances too - I'd like to avoid those as well. I considered the LightVirtualFile check, however I'm concerned about the document listener then not working in other editors. For example, I have a REPL editor in a tool window which is a LightVirtualFile, and I suppose that the diff editor views probably are as well? I can add an explicit check for my REPL editor, but are there other cases I'm likely to need to catch where the user might want to edit a representation of a file which will be a LightVirtualFile?

0
Comment actions Permalink

You could check if there's any editor at all associated with the document (EditorFactory.getEditors).

0
Comment actions Permalink

Ah, good idea - thanks, I'll do that.

0

Please sign in to leave a comment.