Notebook API | Visual Studio Code Extension API
AI agents: See llms.txt for documentation discovery and navigation. Documentation articles are also available as Markdown by appending .md to the article URL. Join VS Code at Microsoft Ignite or catch the sessions online. A year of VS Code, wrapped. Explore the highlights. Notebook API View as Markdown Ask in VS Code Ask in VS Code Insiders The Notebook API allows Visual Studio Code extensions to open files as notebooks, execute notebook code cells, and render notebook outputs in a variety of rich and interactive formats.
You may know of popular notebook interfaces like Jupyter Notebook or Google Colab – the Notebook API allows for similar experiences inside Visual Studio Code. Parts of a Notebook A notebook consists of a sequence of cells and their outputs. The cells of a notebook can be either Markdown cells or code cells , and are rendered within the core of VS Code. The outputs can be of various formats. Some output formats, such as plain text, JSON, images, and HTML are rendered by VS Code core.
Others, such as application-specific data or interactive applets, are rendered by extensions. Cells in a notebook are read and written to the file system by a NotebookSerializer , which handles reading data from the file system and converting it into a description of cells, as well as persisting modifications to the notebook back to the file system. The code cells of a notebook can be executed by a NotebookController , which takes the contents of a cell and from it produces zero or more outputs in a variety of formats ranging from plain text to formatted documents or interactive applets.
Application-specific output formats and interactive applet outputs are rendered by a NotebookRenderer . Visually: Serializer NotebookSerializer API Reference A NotebookSerializer is responsible for taking the serialized bytes of a notebook and deserializing those bytes into NotebookData , which contains list of Markdown and code cells. It is responsible for the opposite conversion as well: taking NotebookData and converting the data into serialized bytes to be saved.
Samples: JSON Notebook Serializer : Simple example notebook that takes JSON input and outputs prettified JSON in a custom NotebookRenderer . Markdown Serializer : Open and edit Markdown files as a notebook. Example In this example, we build a simplified notebook provider extension for viewing files in the Jupyter Notebook format with a .notebook extension (instead of its traditional file extension .ipynb ). A notebook serializer is declared in package.json under the contributes.notebooks section as follows: { ...
"contributes" : { ... "notebooks" : [ { "type" : "my-notebook" , "displayName" : "My Notebook" , "selector" : [ { "filenamePattern" : "*.notebook" } ] } ] } } The notebook serializer is then registered in the extension's activation event: import { TextDecoder , TextEncoder } from 'util' ; import * as vscode from 'vscode' ; export function activate ( context : vscode . ExtensionContext ) { context . subscriptions . push ( vscode . workspace . registerNotebookSerializer ( 'my-notebook' , new SampleSerializer ()) ); } interface RawNotebook { cells : RawNotebookCell []; } interface RawNotebookCell { source : string []; cell_type : 'code' | 'markdown' ; } class SampleSerializer implements vscode .
NotebookSerializer { async deserializeNotebook ( content : Uint8Array , _token : vscode . CancellationToken ): Promise < vscode . NotebookData > { var contents = new TextDecoder (). decode ( content ); let raw : RawNotebookCell []; try { raw = (< RawNotebook > JSON . parse ( contents )). cells ; } catch { raw = []; } const cells = raw . map ( item => new vscode . NotebookCellData ( item . cell_type === 'code' ? vscode .
NotebookCellKind . Code : vscode . NotebookCellKind . Markup , item . source . join ( ' \n ' ), item . cell_type === 'code' ? 'python' : 'markdown' ) ); return new vscode . NotebookData ( cells ); } async serializeNotebook ( data : vscode . NotebookData , _token : vscode . CancellationToken ): Promise < Uint8Array > { let contents : RawNotebookCell [] = []; for ( const cell of data . cells ) { contents . push ({ cell_type: cell . kind === vscode .
NotebookCellKind . Code ? 'code' : 'markdown' , source: cell . value . split ( /\r ? \n/ g ) }); } return new TextEncoder (). encode ( JSON . stringify ( contents )); } } Now try running your extension and opening a Jupyter Notebook formatted file saved with the .notebook extension: You should be able to open Jupyter-formatted notebooks and view their cells as both plain text and rendered Markdown, as well as edit the cells.
However, outputs will not be persisted to disk; to save outputs you would need to also serialize and deserialize the outputs of cells from NotebookData . To run a cell, you will need to implement a NotebookController . Controller NotebookController API Reference A NotebookController is responsible for taking a code cell and executing the code to produce some or no outputs. A controller is directly associated with a notebook serializer and a type of notebook by setting the NotebookController#notebookType property on creation of the controller.
Then the controller is registered globally by pushing the controller onto the extension subscriptions on activate of the extension. export function activate ( context : vscode . ExtensionContext ) { context . subscriptions . push ( new Controller ()); } class Controller { readonly controllerId = 'my-notebook-controller-id' ; readonly notebookType = 'my-notebook' ; readonly label = 'My Notebook' ; readonly supportedLanguages = [ 'python' ]; private readonly _controller : vscode .
NotebookController ; private _executionOrder = 0 ; constructor () { this . _controller = vscode . notebooks . createNotebookController ( this . controllerId , this . notebookType , this . label ); this . _controller . supportedLanguages = this . supportedLanguages ; this . _controller . supportsExecutionOrder = true ; this . _controller . executeHandler = this . _execute . bind ( this ); } private _execute ( cells : vscode .
NotebookCell [], _notebook : vscode . NotebookDocument , _controller : vscode . NotebookController ): void { for ( let cell of cells ) { this . _doExecution ( cell ); } } private async _doExecution ( cell : vscode . NotebookCell ): Promise < void > { const execution = this . _controller . createNotebookCellExecution ( cell ); execution . executionOrder = ++ this . _executionOrder ; execution . start ( Date . now ()); // Keep track of elapsed time to execute cell. /* Do some execution here; not implemented */ execution . replaceOutput ([ new vscode .
NotebookCellOutput ([ vscode . NotebookCellOutputItem . text ( 'Dummy output text!' ) ]) ]); execution . end ( true , Date . now ()); } } If you're publishing a NotebookController -providing extension separately from its serializer, then add an entry like notebookKernel<ViewTypeUpperCamelCased> to the keywords in its package.json . For example, if you published an alternative kernel for the github-issues notebook type, you should add a keyword notebookKernelGithubIssues keyword to your extension.
This improves the discoverability of the extension when opening notebooks of the type <ViewTypeUpperCamelCased> from within Visual Studio Code. Samples: GitHub Issues Notebook : Controller to execute queries for GitHub Issues REST Book : Controller to run REST queries. Regexper notebooks : Controller to visualize regular expressions. Output types Outputs must be in one of three formats: Text Output, Error Output, or Rich Output.
A kernel may provide multiple outputs for a single execution of a cell, in which case they will be displayed as a list. Simple formats like Text Output, Error Output, or "simple" variants of Rich Output (HTML, Markdown, JSON, etc.) are rendered by VS Code core, whereas application specific Rich Output types are rendered by a NotebookRenderer . An extension may optionally choose to render "simple" Rich Outputs itself, for instance to
The rest of this page is on the live site.