Search code examples
visual-studio-codecommand-line-interfacevscode-extensions

How to use Terminal API to listen to all terminal commands/output in VS Code?


I want to listen to terminal output from extension, such as tsc -w and catch the moment if the output contains similar text:

Found 1 error. Watching for file changes.

Or the error exit code or something like that. Is it possible to do with old API or Proposed API?

Tried:

terminal.onDidWriteData(data => {
    console.log('onDidWriteData: ', data.trim());
});

It just outputs autogenerated rubbish like:

Windows PowerShell Copyright (C) Microsoft Corporation. All rights reserved.


Solution

  • Shell Integration API was released in v1.93. See release notes. You can find an example here. Some of the related API surface is:

    I think you'd use window.onDidStartTerminalShellExecution, which is fired when a terminal command is started in a terminal with shell integration, take the TerminalShellExecutionStartEvent's exection property, which is a TerminalShellExecution, and immediately call read to get a stream of the written data.

    Old answer

    For performance reasons, API: onDidWriteTerminalData event #78502 is succeeded by Expose shell integration command knowledge to extensions #145234.

    The latest draft of the API is in src/vscode-dts/vscode.proposed.terminalShellIntegration.d.ts. I'd quote it in this answer post, but it keeps changing and it's annoying for me to keep track of it and update this.

    You can find related release notes here in the release notes for VS Code 1.88 (where the API is now released in the "proposed" status). It includes a couple of API usage examples.

    The relevant proposal file if you want to try this out is src/vscode-dts/vscode.proposed.terminalExecuteCommandEvent.d.ts. See also https://code.visualstudio.com/api/advanced-topics/using-proposed-api.