Update document on document change

Hello,
I used Document.addDocumentListener to a a document listener.
I get the error

java.lang.IllegalStateException: Detected document modification from DocumentListener

 at com.intellij.openapi.editor.impl.DocumentImpl.assertNotNestedModification(DocumentImpl.java:665)

The assertNotNestedModification method documentation explains we should not use document listeners to change the document which is what I was exactly trying to do.

If this does not work, then I'm wondering what is the proper way to do the following:
I have two virtual files. I need to change the text of the second file depending on the change of the text in first file, e.g. on key press.

Any idea how to do this?

Message was edited by: maida_vale The two virtual files may represent the same file.

5 comments
Comment actions Permalink

I have dealt with it recently this way:
 

ApplicationManager.getApplication().invokeLater(new Runnable() {

    @Override
    public void run() {
        new WriteCommandAction.Simple(project) {

            @Override
            protected void run() throws Throwable {
               ...
            }
        }.execute();
    }
})
0
Comment actions Permalink

That does work! Thank you.
However it seems like a trick. It would be interesting to find out how this should be properly done.

0
Comment actions Permalink

Looks like your code might not be doing what you think it's doing. The assertion is only fired if you're trying to modify the same document on which the listener was invoked. Modifying a different document is allowed and should not trigger this assertion.

0
Comment actions Permalink

That's right. The assertion is not triggered if changes are made to a different document. However, the two virtual files may represent the same file and therefore they have associated the same document. How do we handle this case?

0
Comment actions Permalink

In that situation, you do need to use invokeLater(), and also to ensure that no other modifications have been performed to the document between the time your listener was triggered and the time invokeLater() is called.

0

Please sign in to leave a comment.