### Contribute Walkthroughs to Getting Started Page (JSON) Source: https://code.visualstudio.com/api/references/contribution-points Enables the contribution of walkthroughs to the VS Code Getting Started page, automatically opening on extension install to introduce users to extension features. Walkthroughs include a title, description, ID, and a series of steps. Each step has a title, description, ID, media (image or Markdown), and optional completion events. Steps can be conditionally shown using 'when' conditions. ```json { "contributes": { "walkthroughs": [ { "id": "sample", "title": "Sample", "description": "A sample walkthrough", "steps": [ { "id": "runcommand", "title": "Run Command", "description": "This step will run a command and check off once it has been run.\n[Run Command](command:getting-started-sample.runCommand)", "media": { "image": "media/image.png", "altText": "Empty image" }, "completionEvents": ["onCommand:getting-started-sample.runCommand"] }, { "id": "changesetting", "title": "Change Setting", "description": "This step will change a setting and check off when the setting has changed\n[Change Setting](command:getting-started-sample.changeSetting)", "media": { "markdown": "media/markdown.md" }, "completionEvents": ["onSettingChanged:getting-started-sample.sampleSetting"] } ] } ] } } ``` -------------------------------- ### Custom Setup with @vscode/test-electron (TypeScript) Source: https://code.visualstudio.com/api/working-with-extensions/testing-extension Implement custom setups for VS Code extension testing using the granular API of `@vscode/test-electron`. This example demonstrates downloading a specific VS Code version, resolving CLI arguments, and installing an extension before running tests. ```typescript import * as cp from 'child_process'; import * as path from 'path'; import { downloadAndUnzipVSCode, resolveCliArgsFromVSCodeExecutablePath, runTests } from '@vscode/test-electron'; async function main() { try { const extensionDevelopmentPath = path.resolve(__dirname, '../../../'); const extensionTestsPath = path.resolve(__dirname, './suite/index'); const vscodeExecutablePath = await downloadAndUnzipVSCode('1.40.1'); const [cliPath, ...args] = resolveCliArgsFromVSCodeExecutablePath(vscodeExecutablePath); // Use cp.spawn / cp.exec for custom setup cp.spawnSync( cliPath, [...args, '--install-extension', ''], { encoding: 'utf-8', stdio: 'inherit' } ); // Run the extension test await runTests({ // Use the specified `code` executable vscodeExecutablePath, extensionDevelopmentPath, extensionTestsPath }); } catch (err) { console.error('Failed to run tests'); process.exit(1); } } main(); ``` -------------------------------- ### Clone Mock Debug and Install Dependencies (Bash) Source: https://code.visualstudio.com/api/extension-guides/debugger-extension Clones the vscode-mock-debug repository from GitHub and installs the necessary Node.js dependencies using Yarn. This is the initial setup step before opening the project in VS Code. ```bash git clone https://github.com/microsoft/vscode-mock-debug.git cd vscode-mock-debug yarn ``` -------------------------------- ### Install and Run LSP Sample Extension Source: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide This Bash script installs dependencies, compiles the TypeScript code, and opens the LSP sample workspace in VS Code. It's a prerequisite for exploring the client and server code. ```bash > git clone https://github.com/microsoft/vscode-extension-samples.git > cd vscode-extension-samples/lsp-sample > npm install > npm run compile > code . ``` -------------------------------- ### started Source: https://code.visualstudio.com/api/references/vscode-api Indicates that a test has started running. ```APIDOC ## started ### Description Indicates a test has started running. ### Method Not specified (likely internal API call) ### Endpoint Not specified ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body - **test** (TestItem) - Required - Test item to update. ### Request Example ```json { "test": { ... } } ``` ### Response #### Success Response (200) - **void** - This method does not return a value. #### Response Example ```json null ``` ``` -------------------------------- ### Start Local HTTP Server with npx serve Source: https://code.visualstudio.com/api/extension-guides/web-extensions Starts a local HTTP server with SSL enabled to serve your web extension. This command uses npx to run the 'serve' package, configuring it to use the generated SSL certificates and enabling CORS. The server listens on port 5000. ```shell npx serve --cors -l 5000 --ssl-cert $HOME/certs/localhost.pem --ssl-key $HOME/certs/localhost-key.pem ``` -------------------------------- ### Package Extension as VSIX for Manual Installation Source: https://code.visualstudio.com/api/advanced-topics/remote-extensions Packages a VS Code extension into a VSIX file, which can then be manually installed in a remote VS Code instance. This is useful for testing unpublished versions of extensions without needing a full debugging setup. ```shell vsce package ``` -------------------------------- ### Example Token Data for Encoding Source: https://code.visualstudio.com/api/references/vscode-api Provides sample data structures representing tokens with their line, start character, length, token type, and modifiers. This data serves as the input for the semantic token encoding process, showcasing the raw information before it is transformed into the integer array format. ```javascript { line: 2, startChar: 5, length: 3, tokenType: "property", tokenModifiers: ["private", "static"] }, { line: 2, startChar: 10, length: 4, tokenType: "type", tokenModifiers: [] }, { line: 5, startChar: 2, length: 7, tokenType: "class", tokenModifiers: [] } ``` -------------------------------- ### contributes.walkthroughs API Source: https://code.visualstudio.com/api/references/contribution-points Enables extensions to contribute walkthroughs to the 'Getting Started' page. These guide users through extension features upon installation. ```APIDOC ## POST /contributes/walkthroughs ### Description Contribute walkthroughs to appear on the Getting Started page. Walkthroughs are automatically opened on install of your extension and provide a convenient way to introduce users to features of your extension. Walkthroughs consist of a title, description, id, and a series of steps. Additionally, a `when` condition can be set to hide or show the walkthrough based on context keys. For example, a walkthrough to explain setup on a Linux platform could be given `when: "isLinux"` to only appear on Linux machines. Each step in a walkthrough has a title, description, id, and media element (either an image or Markdown content), along with an optional set of events that will cause the step to be checked (shown in the example below). Step descriptions are Markdown content, and support `**bold**`, `__underlined__`, and ```code``` rendering, as well as links. Similar to walkthroughs, steps can be given when conditions to hide or show them based on context keys. SVGs are recommended for images given their ability to scale and their support for VS Code's theme colors. Use the Visual Studio Code Color Mapper Figma plugin to easily reference theme colors in the SVGs. By default, if no `completionEvents` events are provided, the step will be checked off when any of it's buttons are clicked, or if the step has no buttons, when it is opened. If finer control is required, a list of `completionEvents` can be provided. Available completion events include: * `onCommand:myCommand.id`: Check off step when a command has been run. * `onSettingChanged:mySetting.id`: Check off step once the given setting has been modified. * `onContext:contextKeyExpression`: Check off step when a context key expression evaluates true. * `extensionInstalled:myExt.id`: Check off step if the given extension is installed. * `onView:myView.id`: Check off step once a given view becomes visible. * `onLink:https://...`: Check off step once a given link has been opened via a Walkthrough. Once a step has been checked off, it will remain checked off until the user explicitly unchecks the step or resets their progress (via the **Getting Started: Reset Progress** command). ### Method POST ### Endpoint /contributes/walkthroughs ### Request Body - **contributes** (object) - Required - An object containing contribution points. - **walkthroughs** (array) - Required - An array of walkthrough configurations. - **id** (string) - Required - A unique identifier for the walkthrough. - **title** (string) - Required - The title of the walkthrough. - **description** (string) - Required - A description of the walkthrough. - **steps** (array) - Required - An array of steps within the walkthrough. - **id** (string) - Required - A unique identifier for the step. - **title** (string) - Required - The title of the step. - **description** (string) - Required - The Markdown content for the step description. - **media** (object) - Optional - Media element for the step. Can be an image or Markdown. - **image** (string) - Required if `markdown` is not present - Path to the image file. - **altText** (string) - Required if `image` is present - Alternative text for the image. - **markdown** (string) - Required if `image` is not present - Path to the Markdown file. - **completionEvents** (array) - Optional - A list of events that trigger step completion. - **when** (string) - Optional - A context expression to control the visibility of the step. ### Request Example ```json { "contributes": { "walkthroughs": [ { "id": "sample", "title": "Sample", "description": "A sample walkthrough", "steps": [ { "id": "runcommand", "title": "Run Command", "description": "This step will run a command and check off once it has been run.\n[Run Command](command:getting-started-sample.runCommand)", "media": { "image": "media/image.png", "altText": "Empty image" }, "completionEvents": ["onCommand:getting-started-sample.runCommand"] }, { "id": "changesetting", "title": "Change Setting", "description": "This step will change a setting and check off when the setting has changed\n[Change Setting](command:getting-started-sample.changeSetting)", "media": { "markdown": "media/markdown.md" }, "completionEvents": ["onSettingChanged:getting-started-sample.sampleSetting"] } ] } ] } } ``` ### Response #### Success Response (200) - **message** (string) - A success message indicating the contribution was registered. #### Response Example ```json { "message": "Walkthroughs contributed successfully." } ``` ``` -------------------------------- ### Install Webpack and Webpack CLI Source: https://code.visualstudio.com/api/working-with-extensions/bundling-extension This bash command installs webpack and webpack-cli as development dependencies for your project. This makes webpack available on your command line for bundling your extension. ```bash npm i --save-dev webpack webpack-cli ``` -------------------------------- ### CodeActionKind Initialization Examples Source: https://code.visualstudio.com/api/references/vscode-api Demonstrates how to initialize new CodeActionKind instances for notebook-specific actions. These examples show how to append sub-kinds to base kinds like 'notebook' and 'source'. ```typescript const newKind = CodeActionKind.Notebook.append(CodeActionKind.Source.append('xyz').value) const newKind = CodeActionKind.Notebook.append('source.xyz') ``` -------------------------------- ### Create McpHttpServerDefinition Source: https://code.visualstudio.com/api/references/vscode-api Example of creating an instance of `McpHttpServerDefinition`, which represents an MCP server accessible via HTTP. It requires a label and a URI, with optional headers and version. ```typescript const serverDefinition = new McpHttpServerDefinition( 'MyHttpServer', vscode.Uri.parse('http://localhost:8080'), { 'X-API-Key': '12345' }, 'v1.0' ); ``` -------------------------------- ### Install VSIX Package Locally Source: https://code.visualstudio.com/api/working-with-extensions/publishing-extension These commands demonstrate how to install a locally packaged `.vsix` file into your VS Code instance or VS Code Insiders from the command line. ```bash # if you use VS Code code --install-extension my-extension-0.0.1.vsix ``` ```bash # if you use VS Code Insiders code-insiders --install-extension my-extension-0.0.1.vsix ``` -------------------------------- ### HTML Structure Example Source: https://code.visualstudio.com/api/language-extensions/embedded-languages Illustrates a simple HTML structure containing both HTML and CSS content. This serves as an example input for the language server to parse and identify different language regions. ```html
``` -------------------------------- ### VS Code Extension Configuration Example (JSON) Source: https://code.visualstudio.com/api/references/contribution-points This JSON snippet demonstrates how to define configuration settings for a Visual Studio Code extension. It includes examples of boolean and string types with default values and descriptions. These settings can be accessed using the workspace configuration API. ```json { "contributes": { "configuration": { "title": "Settings Editor Test Extension", "type": "object", "properties": { "settingsEditorTestExtension.booleanExample": { "type": "boolean", "default": true, "description": "Boolean Example" }, "settingsEditorTestExtension.stringExample": { "type": "string", "default": "Hello World", "description": "String Example" } } } } } ``` -------------------------------- ### Apply Bold Style to All Declarations in VS Code Theme Source: https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide This example shows how to apply a style to semantic tokens using selectors. Here, all tokens matching the 'declaration' semantic token type will be rendered in bold. ```json "*.declaration": { "bold": true } ``` -------------------------------- ### Install ESLint and TypeScript Support (npm) Source: https://code.visualstudio.com/api/advanced-topics/tslint-eslint-migration Installs ESLint, a TypeScript parser, and TypeScript-specific ESLint plugins using npm. These are necessary for ESLint to understand and lint TypeScript code. ```bash npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin ``` -------------------------------- ### Start Debugging Source: https://code.visualstudio.com/api/references/vscode-api Initiates a debugging session. ```APIDOC ## POST /v1/debugging/start ### Description Starts a debugging session. ### Method POST ### Endpoint /v1/debugging/start ### Parameters #### Request Body - **folder** (WorkspaceFolder) - Required - The workspace folder in which to start debugging. - **nameOrConfiguration** (string | DebugConfiguration) - Required - The name of the debug configuration or the configuration object itself. - **parentSessionOrOptions** (DebugSession | DebugSessionOptions) - Optional - The parent debug session or options for the new session. ### Request Example ```json { "folder": { "uri": "file:///path/to/workspace", "name": "MyWorkspace" }, "nameOrConfiguration": "Launch Program", "parentSessionOrOptions": { "id": "parent-session-123" } } ``` ### Response #### Success Response (200) - **success** (boolean) - True if the debugging session started successfully, false otherwise. ``` -------------------------------- ### Activate on Search Start (VS Code API) Source: https://code.visualstudio.com/api/references/activation-events Activates an extension when a search is initiated within a folder identified by a specific scheme. The `file` scheme is used as an example. ```json "activationEvents": [ "onSearch:file" ] ``` -------------------------------- ### Start Debugging API Source: https://code.visualstudio.com/api/references/vscode-api Initiates a debugging session using named configurations or a direct DebugConfiguration object. Unsaved files are saved, and configurations are updated before debugging starts. Folder-specific variables are resolved against the provided workspace folder. ```APIDOC ## startDebugging ### Description Starts a debugging session. ### Method `startDebugging` ### Parameters #### Path Parameters - **folder** (WorkspaceFolder) - Required - The workspace folder for looking up named configurations and resolving variables or `undefined` for a non-folder setup. - **nameOrConfiguration** (string | DebugConfiguration) - Required - Either the name of a debug or compound configuration or a DebugConfiguration object. - **parentSessionOrOptions** (DebugSession | DebugSessionOptions) - Optional - Debug session options. When passed a parent debug session, assumes options with just this parent session. ### Returns - **Thenable** - A thenable that resolves when debugging could be successfully started. ### Request Example ```json { "folder": "/path/to/workspace", "nameOrConfiguration": "Launch Chrome", "parentSessionOrOptions": {} } ``` ### Response Example ```json { "success": true } ``` ``` -------------------------------- ### Startup Activation Event (*) Source: https://code.visualstudio.com/api/references/activation-events The '*' activation event is emitted whenever VS Code starts up. Extensions listening to this event will be activated upon startup. Use this sparingly and only when other activation events are not suitable. ```APIDOC ## Start up (*) ### Description The `*` activation event is emitted and interested extensions will be activated whenever VS Code starts up. > **Note:** To ensure a great user experience, please use this activation event in your extension only when no other activation events combination works in your use-case. ### Method N/A (Activation Event) ### Endpoint N/A ### Parameters N/A ### Request Example ```json { "activationEvents": [ "*" ] } ``` ### Response #### Success Response (200) N/A (Activation Event) #### Response Example N/A ``` -------------------------------- ### Create MCP Installation URL in TypeScript Source: https://code.visualstudio.com/api/extension-guides/ai/mcp Generates a VS Code MCP server installation URL by JSON stringifying and URL encoding a server configuration object. This URL can be used in browsers or command lines to initiate the installation process. For the Insiders build, 'vscode-insiders' should be used instead of 'vscode'. ```typescript // For Insiders, use `vscode-insiders` instead of `code` const link = `vscode:mcp/install?${encodeURIComponent(JSON.stringify(obj))}`; ``` -------------------------------- ### Install ESLint and TypeScript Support (yarn) Source: https://code.visualstudio.com/api/advanced-topics/tslint-eslint-migration Installs ESLint, a TypeScript parser, and TypeScript-specific ESLint plugins using yarn. This is an alternative to npm for managing project dependencies. ```bash yarn add eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --dev ``` -------------------------------- ### Complete package.json for VS Code Extension Source: https://code.visualstudio.com/api/references/extension-manifest A comprehensive example of a package.json file for a VS Code extension. It includes metadata such as name, version, description, activation events, engines, scripts, dependencies, and repository information. This file is crucial for defining the extension's identity and behavior. ```json { "name": "wordcount", "displayName": "Word Count", "version": "0.1.0", "publisher": "ms-vscode", "description": "Markdown Word Count Example - reports out the number of words in a Markdown file.", "author": { "name": "sean" }, "categories": ["Other"], "icon": "images/icon.png", "galleryBanner": { "color": "#C80000", "theme": "dark" }, "pricing": "Free", "activationEvents": ["onLanguage:markdown"], "engines": { "vscode": "^1.0.0" }, "main": "./out/extension", "scripts": { "vscode:prepublish": "node ./node_modules/vscode/bin/compile", "compile": "node ./node_modules/vscode/bin/compile -watch -p ./'" }, "devDependencies": { "@types/vscode": "^0.10.x", "typescript": "^1.6.2" }, "license": "SEE LICENSE IN LICENSE.txt", "bugs": { "url": "https://github.com/microsoft/vscode-wordcount/issues", "email": "sean@contoso.com" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode-wordcount.git" }, "homepage": "https://github.com/microsoft/vscode-wordcount/blob/main/README.md" } ``` -------------------------------- ### Install Yeoman and VS Code Generators (Bash) Source: https://code.visualstudio.com/api/extension-guides/notebook Provides the command to install Yeoman and the VS Code Generators globally using npm. This is a prerequisite for using the Yeoman generator to create a new Notebook Renderer extension. ```bash npm install -g yo generator-code ``` -------------------------------- ### Start Language Server Connection with TypeScript Source: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide Initiates the listening process for the language server connection. This allows the server to receive and process requests from the VS Code client. ```typescript // Listen on the connection connection.listen(); ``` -------------------------------- ### Install vsce CLI Tool Source: https://code.visualstudio.com/api/working-with-extensions/publishing-extension Installs the `vsce` command-line tool globally using npm. Ensure Node.js is installed before running this command. This tool is essential for managing and publishing VS Code extensions. ```bash npm install -g @vscode/vsce ``` -------------------------------- ### LSP Sample Project Structure Overview Source: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide This text-based representation outlines the directory structure of the lsp-sample project. It highlights the 'client' and 'server' directories, along with key files like 'extension.ts' and 'server.ts'. ```text . ├── client // Language Client │ ├── src │ │ ├── test // End to End tests for Language Client / Server │ │ └── extension.ts // Language Client entry point ├── package.json // The extension manifest └── server // Language Server └── src └── server.ts // Language Server entry point ``` -------------------------------- ### Register and Show Basic Webview Panel in TypeScript Source: https://code.visualstudio.com/api/extension-guides/webview This TypeScript code registers the 'catCoding.start' command and, when executed, creates and shows a new webview panel. It uses the `vscode.window.createWebviewPanel` function to initialize the panel with an internal ID, title, and display column. No HTML content is set yet. ```typescript import * as vscode from 'vscode'; export function activate(context: vscode.ExtensionContext) { context.subscriptions.push( vscode.commands.registerCommand('catCoding.start', () => { // Create and show a new webview const panel = vscode.window.createWebviewPanel( 'catCoding', // Identifies the type of the webview. Used internally 'Cat Coding', // Title of the panel displayed to the user vscode.ViewColumn.One, // Editor column to show the new webview panel in. {} ); }) ); } ``` -------------------------------- ### VS Code Debug Start Command Keybinding Example Source: https://code.visualstudio.com/api/references/when-clause-contexts This JSON snippet demonstrates how a 'when clause' is used to conditionally enable the 'Start Debugging' command's F5 keyboard shortcut. It requires specific debugger availability and ensures the editor is not currently in debug mode. ```json { "key": "f5", "command": "workbench.action.debug.start", "when": "debuggersAvailable && !inDebugMode" } ``` -------------------------------- ### Language Server Initialization and Capabilities (TypeScript) Source: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide Demonstrates the initialization of a VS Code language server using TypeScript. It sets up the connection, text document manager, and defines the server's capabilities, such as text document synchronization and completion provider. ```typescript import { createConnection, TextDocuments, Diagnostic, DiagnosticSeverity, ProposedFeatures, InitializeParams, DidChangeConfigurationNotification, CompletionItem, CompletionItemKind, TextDocumentPositionParams, TextDocumentSyncKind, InitializeResult } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; // Create a connection for the server, using Node's IPC as a transport. // Also include all preview / proposed LSP features. let connection = createConnection(ProposedFeatures.all); // Create a simple text document manager. let documents: TextDocuments = new TextDocuments(TextDocument); let hasConfigurationCapability: boolean = false; let hasWorkspaceFolderCapability: boolean = false; let hasDiagnosticRelatedInformationCapability: boolean = false; connection.onInitialize((params: InitializeParams) => { let capabilities = params.capabilities; // Does the client support the `workspace/configuration` request? // If not, we fall back using global settings. hasConfigurationCapability = !!( capabilities.workspace && !!capabilities.workspace.configuration ); hasWorkspaceFolderCapability = !!( capabilities.workspace && !!capabilities.workspace.workspaceFolders ); hasDiagnosticRelatedInformationCapability = !!( capabilities.textDocument && capabilities.textDocument.publishDiagnostics && capabilities.textDocument.publishDiagnostics.relatedInformation ); const result: InitializeResult = { capabilities: { textDocumentSync: TextDocumentSyncKind.Incremental, // Tell the client that this server supports code completion. completionProvider: { resolveProvider: true } } }; if (hasWorkspaceFolderCapability) { result.capabilities.workspace = { workspaceFolders: { supported: true } }; } return result; }); connection.onInitialized(() => { if (hasConfigurationCapability) { // Register for all configuration changes. connection.client.register(DidChangeConfigurationNotification.type, undefined); } if (hasWorkspaceFolderCapability) { connection.workspace.onDidChangeWorkspaceFolders(_event => { connection.console.log('Workspace folder change event received.'); }); } }); // The example settings interface ExampleSettings { maxNumberOfProblems: number; } // The global settings, used when the `workspace/configuration` request is not supported by the client. // Please note that this is not the case when using this server with the client provided in this example // but could happen with other clients. const defaultSettings: ExampleSettings = { maxNumberOfProblems: 1000 }; let globalSettings: ExampleSettings = defaultSettings; // Cache the settings of all open documents let documentSettings: Map> = new Map(); connection.onDidChangeConfiguration(change => { if (hasConfigurationCapability) { // Reset all cached document settings documentSettings.clear(); } else { globalSettings = ( (change.settings.languageServerExample || defaultSettings) ); } // Revalidate all open text documents documents.all().forEach(validateTextDocument); }); function getDocumentSettings(resource: string): Thenable { if (!hasConfigurationCapability) { return Promise.resolve(globalSettings); } let result = documentSettings.get(resource); if (!result) { result = connection.workspace.getConfiguration({ scopeUri: resource, section: 'languageServerExample' }); documentSettings.set(resource, result); } return result; } // Only keep settings for open documents documents.onDidClose(e => { documentSettings.delete(e.document.uri); }); // The content of a text document has changed. This event is emitted // when the text document first opened or when its content has changed. documents.onDidChangeContent(change => { ``` -------------------------------- ### Remove First Workspace Folder Source: https://code.visualstudio.com/api/references/vscode-api This example shows how to remove the first workspace folder from the workspace. It specifies the starting index as 0 and the delete count as 1. ```typescript workspace.updateWorkspaceFolders(0, 1); ``` -------------------------------- ### Folding Markers API Source: https://code.visualstudio.com/api/language-extensions/language-configuration-guide Configure folding markers for code blocks using start and end regular expressions. This allows for custom folding behavior beyond indentation-based folding. ```APIDOC ## POST /websites/code_visualstudio_api/folding ### Description Configures custom folding markers for code blocks. ### Method POST ### Endpoint /websites/code_visualstudio_api/folding ### Parameters #### Request Body - **folding** (object) - Required - Folding configuration object. - **markers** (object) - Required - Defines the start and end markers for folding. - **start** (string) - Required - Regular expression for the start folding marker (e.g., `^\s*//\s*#?region\b`). - **end** (string) - Required - Regular expression for the end folding marker (e.g., `^\s*//\s*#?endregion\b`). ### Request Example ```json { "folding": { "markers": { "start": "^\\s*//\\s*#?region\\b", "end": "^\\s*//\\s*#?endregion\\b" } } } ``` ### Response #### Success Response (200) - **message** (string) - Confirmation message indicating successful configuration. ``` -------------------------------- ### runHandler Implementation Source: https://code.visualstudio.com/api/extension-guides/testing This section provides a detailed implementation of the `runHandler` function, demonstrating how to create a `TestRun`, queue tests, execute them, and report their status (passed or failed). ```APIDOC ## Implementing the runHandler ### Description The `runHandler` is responsible for executing tests. It should create a `TestRun` object using `controller.createTestRun`, process the `TestRunRequest` (including included and excluded tests), and update the status of each test using methods like `run.passed()` or `run.failed()`. ### Method `runHandler(shouldDebug: boolean, request: vscode.TestRunRequest, token: vscode.CancellationToken)` ### Endpoint N/A (This is a handler function) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```typescript async function runHandler( shouldDebug: boolean, request: vscode.TestRunRequest, token: vscode.CancellationToken ) { const run = controller.createTestRun(request); const queue: vscode.TestItem[] = []; // Loop through all included tests, or all known tests, and add them to our queue if (request.include) { request.include.forEach(test => queue.push(test)); } else { controller.items.forEach(test => queue.push(test)); } // For every test that was queued, try to run it. Call run.passed() or run.failed(). while (queue.length > 0 && !token.isCancellationRequested) { const test = queue.pop()!; // Skip tests the user asked to exclude if (request.exclude?.includes(test)) { continue; } switch (getType(test)) { case ItemType.File: // If we're running a file and don't know what it contains yet, parse it now if (test.children.size === 0) { await parseTestsInFileContents(test); } break; case ItemType.TestCase: // Otherwise, just run the test case. const start = Date.now(); try { await assertTestPasses(test); run.passed(test, Date.now() - start); } catch (e) { run.failed(test, new vscode.TestMessage(e.message), Date.now() - start); } break; } test.children.forEach(test => queue.push(test)); } // Make sure to end the run after all tests have been executed: run.end(); } ``` ### Response #### Success Response (200) N/A (This is a handler function, side effects are reported via the `TestRun` object) #### Response Example N/A ``` -------------------------------- ### Add Workspace Folder at End Source: https://code.visualstudio.com/api/references/vscode-api This example demonstrates how to add a new workspace folder to the end of the existing workspace folders. It checks if workspace folders exist and uses their length as the starting index for the update. ```typescript workspace.updateWorkspaceFolders(workspace.workspaceFolders ? workspace.workspaceFolders.length : 0, null, { uri: ...}); ``` -------------------------------- ### Initialize Handler for Capabilities Source: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide This section explains how to update the server's capabilities during the initialization phase to inform the client about supported features like code completion. ```APIDOC ## POST /initialize ### Description Initializes the language server and declares its capabilities to the client. ### Method POST ### Endpoint /initialize ### Parameters #### Request Body - **params** (InitializeParams) - Required - Initialization parameters from the client. ### Request Example ```json { "processId": 12345, "clientInfo": { "name": "VS Code", "version": "1.70.0" }, "capabilities": { ... }, "initializationOptions": { ... } } ``` ### Response #### Success Response (200) - **InitializeResult** (object) - The result of the initialization, including server capabilities. #### Response Example ```json { "capabilities": { "completionProvider": { "resolveProvider": true } } } ``` ``` -------------------------------- ### Auto-Indentation Example in JavaScript (VS Code) Source: https://code.visualstudio.com/api/language-extensions/language-configuration-guide Demonstrates how VS Code automatically indents code in JavaScript after a line matching the `increaseIndentPattern`, specifically after an opening bracket. This behavior is controlled by the `indentationRules` configuration. ```javascript if (true) { console.log(); ``` -------------------------------- ### Apply Theming to Custom Token Types in VS Code Source: https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide Theme authors can define styling rules for semantic tokens in their 'package.json' using 'semanticTokenColors'. Styles defined for a 'superType' will automatically apply to its subtypes, such as the 'templateType' in this example. ```json { "name": "Red Theme", "semanticTokenColors": { "type": "#ff0011" } } ``` -------------------------------- ### Color Java Classes with Italic Style in VS Code Theme Source: https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide This example demonstrates how to apply specific foreground color and font style to semantic tokens. It targets 'class' tokens specifically within the 'java' language, making them green and italic. ```json "class:java": { "foreground": "#0f0", "italic": true } ``` -------------------------------- ### Configure Extension Commands in package.json Source: https://code.visualstudio.com/api/extension-guides/ai/language-model-tutorial This JSON snippet shows how to define commands within a VS Code extension's package.json file. It includes the command ID and a user-facing title. The example demonstrates updating a default command to a custom 'Toggle Tutor Annotations' command. ```json "contributes": { "commands": [ { "command": "code-tutor.helloWorld", "title": "Hello World" } ] } ``` ```json "contributes": { "commands": [ { "command": "code-tutor.annotate", "title": "Toggle Tutor Annotations" } ] } ``` -------------------------------- ### Activate on VS Code Startup Source: https://code.visualstudio.com/api/references/activation-events The wildcard '*' activation event is emitted whenever VS Code starts up. Extensions should use this event sparingly, only when no other specific activation events meet their needs, to ensure optimal performance. ```json "activationEvents": [ "*" ] ``` -------------------------------- ### Generate VS Code Extension Code (Bash) Source: https://code.visualstudio.com/api/extension-guides/color-theme This bash command installs the Yeoman scaffolding tool and the VS Code extension generator globally. It's the first step in creating a new Visual Studio Code extension, including color themes. ```bash npm install -g yo generator-code yo code ``` -------------------------------- ### createQuickPick() Source: https://code.visualstudio.com/api/references/vscode-api Creates a QuickPick for the user to select an item from a list. Use when window.showQuickPick lacks flexibility. ```APIDOC ## createQuickPick() ### Description Creates a QuickPick to let the user pick an item from a list of items of type T. Use when `window.showQuickPick` does not offer the required flexibility. ### Method N/A (Function) ### Endpoint N/A ### Parameters N/A ### Request Example N/A ### Response #### Success Response - **QuickPick** (QuickPick) - A new QuickPick. #### Response Example ```json { "QuickPick": "new QuickPick instance" } ``` ``` -------------------------------- ### Exclude Files from Extension Package using .vscodeignore Source: https://code.visualstudio.com/api/working-with-extensions/publishing-extension This example shows how to create a .vscodeignore file to prevent specific files from being included in your extension's package. It uses glob patterns, with lines starting with '!' including files. This is useful for excluding development-specific files like TypeScript source files. ```bash **/*.ts **/tsconfig.json !file.ts ``` -------------------------------- ### Convert YAML to JSON Grammar using js-yaml CLI Source: https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide This snippet demonstrates how to convert a TextMate grammar written in YAML to JSON format using the `js-yaml` command-line tool. This is useful for managing complex grammars with comments and concise syntax. Ensure `js-yaml` is installed as a development dependency. ```bash # Install js-yaml as a development only dependency in your extension $ npm install js-yaml --save-dev # Use the command-line tool to convert the yaml grammar to json $ npx js-yaml syntaxes/abc.tmLanguage.yaml > syntaxes/abc.tmLanguage.json ``` -------------------------------- ### Configure Folding Markers in VS Code Source: https://code.visualstudio.com/api/language-extensions/language-configuration-guide Defines custom start and end regular expressions for folding markers in VS Code. This configuration is used when indentation-based folding is active and no specific folding provider is available for the language. It allows for custom region definitions like `//#region` and `//#endregion`. ```json { "folding": { "markers": { "start": "^\\s*//\\s*#?region\\b", "end": "^\\s*//\\s*#?endregion\\b" } } } ``` -------------------------------- ### Activate on Walkthrough Open (nodejsWelcome) Source: https://code.visualstudio.com/api/references/activation-events This activation event is emitted when a specific walkthrough, identified by 'nodejsWelcome', is opened by the user. It's designed for extensions that provide guided walkthroughs. ```json "activationEvents": [ "onWalkthrough:nodejsWelcome" ] ``` -------------------------------- ### Generate VS Code Extension Project with Yeoman Source: https://code.visualstudio.com/api/extension-guides/ai/chat-tutorial This command uses Yeoman and the generator-code package to scaffold a new Visual Studio Code extension project. It prompts the user for various configuration options to set up the project structure and initial files. ```bash npx --package yo --package generator-code -- yo code ``` -------------------------------- ### Define Semantic Coloring Rules in a VS Code Color Theme Source: https://code.visualstudio.com/api/language-extensions/semantic-highlight-guide This JSON example demonstrates how to define semantic highlighting and custom coloring rules within a VS Code Color Theme file. It enables semantic highlighting for the theme and specifies a custom color for readonly variables in Java. ```jsonc { "name": "Red Theme", "tokenColors": [ { "scope": "comment", "settings": { "foreground": "#dd0000", "fontStyle": "italic" } } ], "semanticHighlighting": true, "semanticTokenColors": { "variable.readonly:java": "#ff0011" } } ``` -------------------------------- ### Provide Code Completion Items with TypeScript Source: https://code.visualstudio.com/api/language-extensions/language-server-extension-guide Provides a static list of completion items ('TypeScript' and 'JavaScript') when code completion is requested. This example ignores the position parameters and always returns the same items. It utilizes `TextDocumentPositionParams` and `CompletionItem` types. ```typescript // This handler provides the initial list of the completion items. connection.onCompletion( (_textDocumentPosition: TextDocumentPositionParams): CompletionItem[] => { // The pass parameter contains the position of the text document in // which code complete got requested. For the example we ignore this // info and always provide the same completion items. return [ { label: 'TypeScript', kind: CompletionItemKind.Text, data: 1 }, { label: 'JavaScript', kind: CompletionItemKind.Text, data: 2 } ]; } ); ``` -------------------------------- ### Azure Pipelines Configuration for VS Code Extension Tests Source: https://code.visualstudio.com/api/working-with-extensions/continuous-integration This YAML configuration sets up an Azure Pipeline to run VS Code extension integration tests across multiple operating systems (Linux, macOS, Windows). It includes Node.js installation, xvfb setup for Linux headless environments, and test execution. ```yaml trigger: branches: include: - main tags: include: - v* strategy: matrix: linux: imageName: 'ubuntu-latest' mac: imageName: 'macos-latest' windows: imageName: 'windows-latest' pool: vmImage: $(imageName) steps: - task: NodeTool@0 inputs: versionSpec: '10.x' displayName: 'Install Node.js' - bash: | /usr/bin/Xvfb :99 -screen 0 1024x768x24 > /dev/null 2>&1 & echo ">>> Started xvfb" displayName: Start xvfb condition: and(succeeded(), eq(variables['Agent.OS'], 'Linux')) - bash: | echo ">>> Compile vscode-test" yarn && yarn compile echo ">>> Compiled vscode-test" cd sample echo ">>> Run sample integration test" yarn && yarn compile && yarn test displayName: Run Tests env: DISPLAY: ':99.0' ``` -------------------------------- ### QuickPickOptions Interface Source: https://code.visualstudio.com/api/references/vscode-api Options to configure the behavior of the quick pick UI. ```APIDOC ## QuickPickOptions Interface ### Properties - **canPickMany** (boolean) - Optional - Allows multiple selections, result is an array of picks. - **ignoreFocusOut** (boolean) - Optional - Keeps picker open when focus moves out. Ignored on iPad. - **matchOnDescription** (boolean) - Optional - Includes description when filtering picks. - **matchOnDetail** (boolean) - Optional - Includes detail when filtering picks. - **placeHolder** (string) - Optional - Placeholder text in the input box. - **title** (string) - Optional - Title of the quick pick. ### Events - **onDidSelectItem** (`item: string | QuickPickItem`) - Optional - Function invoked whenever an item is selected. ``` -------------------------------- ### Override Token Types for Embedded Languages in Strings/Comments Source: https://code.visualstudio.com/api/language-extensions/syntax-highlight-guide This example shows how to ensure embedded languages within strings or comments are treated as source code, not string or comment content. It uses `embeddedLanguages` to define the embedded language scope and `tokenTypes` to explicitly set the token type to 'other', preventing features like auto-closing pairs from being disabled. ```json { "contributes": { "grammars": [ { "path": "./syntaxes/injection.json", "scopeName": "sql-string.injection", "injectTo": ["source.js"], "embeddedLanguages": { "my.sql.template.string": "sql" }, "tokenTypes": { "my.sql.template.string": "other" } } ] } } ``` -------------------------------- ### Configure Launch.json for Extension Tests Source: https://code.visualstudio.com/api/working-with-extensions/bundling-extension A launch configuration for Visual Studio Code to execute extension tests. It specifies the extension development path, test path, and uses a preLaunchTask to compile tests before launching. ```json { "name": "Extension Tests", "type": "extensionHost", "request": "launch", "runtimeExecutable": "${execPath}", "args": [ "--extensionDevelopmentPath=${workspaceFolder}", "--extensionTestsPath=${workspaceFolder}/out/test" ], "outFiles": ["${workspaceFolder}/out/test/**/*.js"], "preLaunchTask": "npm: compile-tests" } ``` -------------------------------- ### Run and Debug a VS Code Extension Source: https://code.visualstudio.com/api/get-started/your-first-extension Compile and run your VS Code extension in a new development host window. This is typically done by pressing F5 or using the 'Debug: Start Debugging' command from the Command Palette after opening the extension's source code. ```bash Press F5 or run the command **Debug: Start Debugging** from the Command Palette (Ctrl+Shift+P). ``` -------------------------------- ### Task Start Event Source: https://code.visualstudio.com/api/references/vscode-api An event signaling the start of a task execution. ```APIDOC ## TaskStartEvent ### Description An event signaling the start of a task execution. ### Properties - **execution** (TaskExecution) - Required - The task item representing the task that got started. ``` -------------------------------- ### Marketplace Resource Links in package.json Source: https://code.visualstudio.com/api/references/extension-manifest Configuration for optional resource links such as license, homepage, bugs, and repository in the package.json file. These links are displayed in the 'Resources' section of the extension's Marketplace page, providing users with access to important information. ```json { "license": "SEE LICENSE IN LICENSE.txt", "homepage": "https://github.com/microsoft/vscode-wordcount/blob/main/README.md", "bugs": { "url": "https://github.com/microsoft/vscode-wordcount/issues", "email": "sean@contoso.com" }, "repository": { "type": "git", "url": "https://github.com/microsoft/vscode-wordcount.git" } } ``` -------------------------------- ### Activate on Startup Finish (VS Code API) Source: https://code.visualstudio.com/api/references/activation-events Activates an extension some time after VS Code has finished starting up. This event is similar to the `*` activation event but does not slow down the initial startup process. It fires after all `*` activated extensions have completed. ```json "activationEvents": [ "onStartupFinished" ] ``` -------------------------------- ### Task Process Start Event Source: https://code.visualstudio.com/api/references/vscode-api An event signaling the start of a process execution triggered through a task. ```APIDOC ## TaskProcessStartEvent ### Description An event signaling the start of a process execution triggered through a task. ### Properties - **execution** (TaskExecution) - Required - The task execution for which the process got started. - **processId** (number) - Required - The underlying process id. ``` -------------------------------- ### Manage Webview Panel Visibility and Creation (TypeScript) Source: https://code.visualstudio.com/api/extension-guides/webview This snippet demonstrates how to manage a single webview panel. It checks if a panel already exists and reveals it if it does, or creates a new one if it doesn't. It also handles resetting the panel reference when it's disposed. ```typescript export function activate(context: vscode.ExtensionContext) { // Track the current panel with a webview let currentPanel: vscode.WebviewPanel | undefined = undefined; context.subscriptions.push( vscode.commands.registerCommand('catCoding.start', () => { const columnToShowIn = vscode.window.activeTextEditor ? vscode.window.activeTextEditor.viewColumn : undefined; if (currentPanel) { // If we already have a panel, show it in the target column currentPanel.reveal(columnToShowIn); } else { // Otherwise, create a new panel currentPanel = vscode.window.createWebviewPanel( 'cat Coding', 'Cat Coding', columnToShowIn || vscode.ViewColumn.One, {} ); currentPanel.webview.html = getWebviewContent('Coding Cat'); // Reset when the current panel is closed currentPanel.onDidDispose( () => { currentPanel = undefined; }, null, context.subscriptions ); } }) ); } ```