Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VSCode: Create a document in memory with URI for automated testing?

Background

I created an extension that interacts with documents. In order to test the extension I need to create documents, that the extension can work with. The extension has to access the document via uri.

Currently I'm using vscode.workspace.openTextDocument({content: _content, language: _language}); for document creation. The problem is, it does not have a valid URI.

Question

How can I create a virtual document in memory, that has a valid URI?

like image 530
DarkTrick Avatar asked Feb 19 '26 16:02

DarkTrick


1 Answers

As rioV8 said, you can also use an existing document and change its content. Here the code:

export class TmpFile
{
  private static _lastDocId: number = 0;
    private static _getNextDocId(): string{
        this._lastDocId++;
        return "tmpfile_" + this._lastDocId;
    }

    public static async createDocument(strContent: string, extension:string = "")
        : Promise<vscode.TextDocument | null>
    {
        let folder = "/tmp"
        let filename = this._getNextDocId ();
        let ext = (extension != "" ? "." + extension : "");


        const newFile = vscode.Uri.parse('untitled:' + path.join(folder, filename + ext));

        {
            const edit = new vscode.WorkspaceEdit();
            edit.insert(newFile, new vscode.Position(0, 0), strContent);
            
            let success = await vscode.workspace.applyEdit(edit);           
            
            if (!success)
                return null;
        }

        let document = await vscode.workspace.openTextDocument(newFile);
        return document;
    }
}

Pro's

  • It's a file (schema), so all LSP commands will work
  • The path (used above) does not even need to exist.

Con's

  • The file is really opened in the editor. You need to close it later
  • The file is a changed file in the editor, so it will ask you to save the changes upon closing.
  • Files cannot be closed in vscode. You can only run:
vscode.window.showTextDocument(doc.uri, {preview: true, preserveFocus: false})
    .then(() => {        
        return vscode.commands.executeCommand('workbench.action.closeActiveEditor');
    });
```<br>
which is a rather nasty workaround.
like image 56
DarkTrick Avatar answered Feb 21 '26 13:02

DarkTrick



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!