microsoft / vscode

Visual Studio Code
https://code.visualstudio.com
MIT License
164.11k stars 29.27k forks source link

Expose API to determine if TextEditor is disposed #83258

Closed JarrettSpiker closed 5 years ago

JarrettSpiker commented 5 years ago

The current API for TextEditor has no way to determine if the TextEditor is disposed.

When developing an extension, it is sometimes helpful to know if a referenced TextEditor has been disposed.

I notice that the TextEditor has a private property called _disposed. Could extension developers have an isDisposed() method?

Example Use Case:

If I am trying to clear decorations on the editor based on a timeout, and the user closed the editor during the timeout, a "TextEditor is closed/disposed" warning is printed. Something like:

let editor : TextEditor;
let highlight = vscode.window.createTextEditorDecorationType(...);
...
...
...
editor.setDecorations(highlight, [range]);

// if the editor is closed before 3 seconds passes, this prints a warning
setTimeout(() => editor.setDecorations(highlight, []), 3000); 

Something similar is done in the sample VSCode extension for decorations, as well as in several other sample extensions.

This can be a real pain in unit tests which don't wait for the timeout to complete before cleaning up the editor.

I would like to be able to do something like:

setTimeout(() => {
    if (editor && !editor.isDisposed()) {
        this.setDecorationInEditor(editor, this.highlightBackgroundDecoration, []);
    }
}, 3000);

I tried determining if the document is closed, but that did not work.

vscodebot[bot] commented 5 years ago

(Experimental duplicate detection) Thanks for submitting this issue. Please also check if it is already covered by an existing one, like:

alexdima commented 5 years ago

I think you can do this in a more straight-forward way by looping through vscode.window.visibleTextEditors. Any editor that does not appear there is not visible (kind of disposed)... In any ways, editors that are not visible have their decorations auto-removed.


FYI @aeschli That text editor decoration sample is IMHO flawed. We shouldn't capture text editor instances in closures and use those instances in an async callback. We should always check that the active editor is still the initial one using vscode.window.activeTextEditor...