### Install Dependencies Source: https://github.com/microsoft/vscode-extension-samples/blob/main/chat-model-provider-sample/README.md Install project dependencies using npm. ```bash npm install ``` -------------------------------- ### Start Vim Editor Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Initiate Vim by typing 'vim' followed by the filename at the shell prompt. ```shell vim tutor ``` -------------------------------- ### Markdown Test Discovery Example Source: https://github.com/microsoft/vscode-extension-samples/blob/main/test-provider-sample/README.md This example shows the format for defining tests within a Markdown file. Headings are used to group tests, and lines following the heading are treated as individual tests. ```markdown # Easy Math 2 + 2 = 4 // this test will pass 2 + 2 = 5 // this test will fail # Harder Math 230230 + 5819123 = 6049353 ``` -------------------------------- ### Language Client Setup with vscode-languageclient Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Initialize a Language Client to communicate with a Language Server. This involves specifying the server module path and transport mechanism, along with client-specific options like document selectors. ```typescript import { LanguageClient, ServerOptions, TransportKind, LanguageClientOptions } from 'vscode-languageclient/node'; let client: LanguageClient; export function activate(context: vscode.ExtensionContext) { const serverModule = context.asAbsolutePath(path.join('server', 'out', 'server.js')); const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc } }; const clientOptions: LanguageClientOptions = { documentSelector: [{ scheme: 'file', language: 'plaintext' }], synchronize: { fileEvents: vscode.workspace.createFileSystemWatcher('**/.clientrc') } }; client = new LanguageClient('lspExample', 'Language Server Example', serverOptions, clientOptions); client.start(); } export function deactivate() { return client?.stop(); } ``` -------------------------------- ### Python Module Import Source: https://github.com/microsoft/vscode-extension-samples/blob/main/notebook-format-code-action-sample/nb-before.ipynb A basic example showing how to import the `os` module in Python. This module provides a way of using operating system dependent functionality. ```python import os ``` -------------------------------- ### Contribute a Simple Chat Participant Source: https://github.com/microsoft/vscode-extension-samples/blob/main/chat-sample/README.md Example of a basic chat participant that responds to user queries. Suitable for simple interactions without complex tool usage. ```typescript import * as vscode from "vscode"; export function activate(context: vscode.ExtensionContext) { const provider = { async provideChatResponse( request: vscode.ChatRequest, token: vscode.CancellationToken ): Promise { if (request.command === "@cat") { return "Meow!"; } return "I am a simple chat participant. Ask me something."; }, }; context.subscriptions.push(vscode.chat.registerChatParticipant("cat", provider)); } ``` -------------------------------- ### Move to Start of Line in Vim Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Type '0' (zero) in Normal mode to move the cursor to the beginning of the current line. ```vim 0 ``` -------------------------------- ### Contribute a Sophisticated Chat Participant with LanguageModelTool Source: https://github.com/microsoft/vscode-extension-samples/blob/main/chat-sample/README.md An advanced example showing a chat participant that invokes tools using the `LanguageModelTool` API. It handles dynamic tool invocation and `toolReferences`. ```typescript import * as vscode from "vscode"; import { ChatParticipant, createApiProvider, LanguageModelTool } from "@vscode/chat-extension-utils"; export function activate(context: vscode.ExtensionContext) { const participant = new ChatParticipant({ name: "@tool", description: "A chat participant that uses the LanguageModelTool API.", tools: [ new LanguageModelTool({ name: "get_current_time", description: "Gets the current time.", execute: async () => { return new Date().toLocaleTimeString(); } }) ] }); context.subscriptions.push(vscode.chat.registerChatParticipant(participant.name, createApiProvider(participant))); } ``` -------------------------------- ### Python Get Current Working Directory Source: https://github.com/microsoft/vscode-extension-samples/blob/main/notebook-format-code-action-sample/nb-after.ipynb This Python snippet shows how to get and print the current working directory using the os module. ```python current_dir = os.getcwd() print("Current working directory:", current_dir) ``` -------------------------------- ### LSP Sample Project Structure Source: https://github.com/microsoft/vscode-extension-samples/blob/main/lsp-sample/README.md Overview of the directory structure for the LSP sample project, including client, server, and package.json. ```plaintext . ├── 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 ``` -------------------------------- ### Language Server Protocol — LanguageClient / createConnection Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Demonstrates setting up a Language Server Protocol client and server. The client launches and communicates with the server, which handles diagnostics, completions, and configuration. ```APIDOC ## Language Server Protocol — `LanguageClient` / `createConnection` ### Description The LSP sample splits into a **client** (uses `vscode-languageclient`) and a **server** (uses `vscode-languageserver`). The client launches the server process and wires up document synchronization; the server implements handlers for diagnostics, completions, and configuration. ### Client Usage ```typescript // lsp-sample/client/src/extension.ts import { LanguageClient, ServerOptions, TransportKind, LanguageClientOptions } from 'vscode-languageclient/node'; let client: LanguageClient; export function activate(context: vscode.ExtensionContext) { const serverModule = context.asAbsolutePath(path.join('server', 'out', 'server.js')); const serverOptions: ServerOptions = { run: { module: serverModule, transport: TransportKind.ipc }, debug: { module: serverModule, transport: TransportKind.ipc } }; const clientOptions: LanguageClientOptions = { documentSelector: [{ scheme: 'file', language: 'plaintext' }], synchronize: { fileEvents: vscode.workspace.createFileSystemWatcher('**/.clientrc') } }; client = new LanguageClient('lspExample', 'Language Server Example', serverOptions, clientOptions); client.start(); } export function deactivate() { return client?.stop(); } ``` ### Server Usage ```typescript // lsp-sample/server/src/server.ts import { createConnection, TextDocuments, ProposedFeatures, DiagnosticSeverity } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; const connection = createConnection(ProposedFeatures.all); const documents = new TextDocuments(TextDocument); connection.onInitialize(() => ({ capabilities: { textDocumentSync: 1, // Incremental completionProvider: { resolveProvider: true }, diagnosticProvider: { interFileDependencies: false, workspaceDiagnostics: false } } })); // Diagnostics: flag all-uppercase words connection.languages.diagnostics.on(async params => ({ kind: 'full', items: (documents.get(params.textDocument.uri)?.getText() ?? '') .matchAll(/\b[A-Z]{2,}\b/g) ? [...documents.get(params.textDocument.uri)!.getText().matchAll(/\b[A-Z]{2,}\b/g)] .map(m => ({ severity: DiagnosticSeverity.Warning, range: { start: documents.get(params.textDocument.uri)!.positionAt(m.index!), end: documents.get(params.textDocument.uri)!.positionAt(m.index! + m[0].length) }, message: `${m[0]} is all uppercase.`, source: 'ex' })) : [] })); connection.onCompletion(() => [ { label: 'TypeScript', kind: 1, data: 1 }, { label: 'JavaScript', kind: 1, data: 2 } ]); connection.onCompletionResolve(item => { item.detail = item.data === 1 ? 'TypeScript details' : 'JavaScript details'; return item; }); documents.listen(connection); connection.listen(); ``` ``` -------------------------------- ### Python Time Sleep Example Source: https://github.com/microsoft/vscode-extension-samples/blob/main/notebook-format-code-action-sample/nb-after.ipynb This Python snippet demonstrates the use of time.sleep() for pausing execution. ```python import time for i in range(10): time.sleep(0.1) ``` -------------------------------- ### Project Structure Source: https://github.com/microsoft/vscode-extension-samples/blob/main/lsp-web-extension-sample/README.md Overview of the directory structure for the LSP web extension sample, separating client and server components. ```plaintext . ├── client // Language Client │ ├── src │ │ └── browserClientMain.ts // Language Client entry point ├── package.json // The extension manifest. └── server // Language Server └── src └── browserServerMain.ts // Language Server entry point ``` -------------------------------- ### Create Source Control Provider Source: https://github.com/microsoft/vscode-extension-samples/blob/main/source-control-sample/README.md Initializes a custom source control provider for a workspace folder, creates a resource group for changes, and registers a repository. ```javascript this.jsFiddleScm = vscode.scm.createSourceControl('jsfiddle', 'JSFiddle #' + fiddle.slug, workspaceFolder.uri); this.changedResources = this.jsFiddleScm.createResourceGroup('workingTree', 'Changes'); this.fiddleRepository = new FiddleRepository(workspaceFolder, fiddle.slug); this.jsFiddleScm.quickDiffProvider = this.fiddleRepository; ``` -------------------------------- ### Vim: Execute External Command Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Prefix an external shell command with '!' to execute it. For example, ':!ls' lists directory contents. ```vim :!ls ``` ```vim :!dir ``` -------------------------------- ### vscode.workspace.registerFileSystemProvider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Allows mounting custom URI schemes (e.g., `memfs:/`) to treat in-memory or remote content as a real file system with full editor support. ```APIDOC ## vscode.workspace.registerFileSystemProvider — Virtual File System Mounts a custom URI scheme (e.g., `memfs:/`) so VS Code treats in-memory (or remote) content as a real file system with full editor support. ### Registering a File System Provider ```typescript const memFs = new MemFS(); // implements vscode.FileSystemProvider context.subscriptions.push( vscode.workspace.registerFileSystemProvider('memfs', memFs, { isCaseSensitive: true }) ); ``` ### Populating the Virtual File System ```typescript const enc = new TextEncoder(); memFs.writeFile(vscode.Uri.parse('memfs:/hello.ts'), enc.encode('const x = 42;'), { create: true, overwrite: true }); memFs.createDirectory(vscode.Uri.parse('memfs:/src/')); ``` ### Adding a Virtual Workspace Folder ```typescript vscode.workspace.updateWorkspaceFolders(0, 0, { uri: vscode.Uri.parse('memfs:/'), name: 'MemFS' }); ``` ``` -------------------------------- ### Delete Two Words (Vimscript) Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Example of deleting two words using the 'd' operator and 'w' motion with a count. ```vimscript d2w ``` -------------------------------- ### Workspace Configuration for `datei://` Scheme Source: https://github.com/microsoft/vscode-extension-samples/blob/main/nodefs-provider-sample/README.md Configure your `.code-workspace` file to include a local folder using the `datei://` scheme. Replace `` with the actual path. ```json { "folders": [ { "uri": "datei://" } ] } ``` -------------------------------- ### Repeat Motion in Vim Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Prefix a motion command with a count to repeat it that many times. For example, '2w' moves two words forward. ```vim 2w ``` ```vim 3e ``` -------------------------------- ### Configure Activation Events for Source Control Source: https://github.com/microsoft/vscode-extension-samples/blob/main/source-control-sample/README.md This JSON snippet defines the activation event for a source control extension. It activates when a workspace contains the '.jsfiddle' file, indicating a cloned repository. ```JSON "activationEvents": [ "workspaceContains:.jsfiddle" ], ``` -------------------------------- ### Delete Text with Count and Motion (Vimscript) Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Use a number before a motion to delete multiple units of text. For example, 'd2w' deletes two words. ```vimscript d number motion ``` -------------------------------- ### Basic TypeScript Variable Declaration Source: https://github.com/microsoft/vscode-extension-samples/blob/main/getting-started-sample/media/web.md A simple TypeScript code snippet showing variable declaration. No specific setup is required beyond a TypeScript environment. ```typescript const a = 12; ``` -------------------------------- ### Language Server Implementation with vscode-languageserver Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Set up a Language Server using `vscode-languageserver/node`. This includes creating a connection, managing text documents, and defining capabilities like completion and diagnostic providers. ```typescript import { createConnection, TextDocuments, ProposedFeatures, DiagnosticSeverity } from 'vscode-languageserver/node'; import { TextDocument } from 'vscode-languageserver-textdocument'; const connection = createConnection(ProposedFeatures.all); const documents = new TextDocuments(TextDocument); connection.onInitialize(() => ({ capabilities: { textDocumentSync: 1, // Incremental completionProvider: { resolveProvider: true }, diagnosticProvider: { interFileDependencies: false, workspaceDiagnostics: false } } })); // Diagnostics: flag all-uppercase words connection.languages.diagnostics.on(async params => ({ kind: 'full', items: (documents.get(params.textDocument.uri)?.getText() ?? '') .matchAll(/\b[A-Z]{2,}\b/g) ? [...documents.get(params.textDocument.uri)!.getText().matchAll(/\b[A-Z]{2,}\b/g)] .map(m => ({ severity: DiagnosticSeverity.Warning, range: { start: documents.get(params.textDocument.uri)!.positionAt(m.index!), end: documents.get(params.textDocument.uri)!.positionAt(m.index! + m[0].length) }, message: `${m[0]} is all uppercase.`, source: 'ex' })) : [] })); connection.onCompletion(() => [ { label: 'TypeScript', kind: 1, data: 1 }, { label: 'JavaScript', kind: 1, data: 2 } ]); connection.onCompletionResolve(item => { item.detail = item.data === 1 ? 'TypeScript details' : 'JavaScript details'; return item; }); documents.listen(connection); connection.listen(); ``` -------------------------------- ### Create a Chat Participant with Tools Source: https://github.com/microsoft/vscode-extension-samples/blob/main/chat-sample/README.md Demonstrates using the `@vscode/chat-extension-utils` library to create a chat participant that can utilize tools for more advanced interactions. ```typescript import * as vscode from "vscode"; import { ChatParticipant, createApiProvider } from "@vscode/chat-extension-utils"; export function activate(context: vscode.ExtensionContext) { const participant = new ChatParticipant({ name: "@catTools", description: "A chat participant that uses tools.", toolData: [ { name: "get_current_time", description: "Gets the current time.", execute: async () => { return new Date().toLocaleTimeString(); } } ] }); context.subscriptions.push(vscode.chat.registerChatParticipant(participant.name, createApiProvider(participant))); } ``` -------------------------------- ### Save and Exit Vim Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Use ':wq' to save changes and exit Vim. Use ':q!' to exit without saving. ```vim :wq ``` ```vim :q! ``` -------------------------------- ### Populate Changed Files View Source: https://github.com/microsoft/vscode-extension-samples/blob/main/source-control-sample/README.md Creates a SourceControlResourceState for each changed document, linking it to the diff command and providing a tooltip. ```javascript { resourceUri: doc.uri, command: { title: "Show changes", command: "vscode.diff", arguments: [repositoryUri, doc.uri, `Checked-out version ↔ Local changes`], tooltip: "Diff your changes" } } ``` -------------------------------- ### Sample Chat Model Provider Implementation Source: https://github.com/microsoft/vscode-extension-samples/blob/main/chat-model-provider-sample/README.md Implements the LanguageModelChatProvider2 interface to provide custom chat models. Handles model information and chat requests. ```typescript import * as vscode from "vscode"; const MODEL_ID_CAT = "cat"; const MODEL_ID_DOG = "dog"; class SampleChatModelProvider implements vscode.LanguageModelChatProvider2 { async provideLanguageModelChatInfo(model: vscode.ChatModel, token: vscode.CancellationToken): Promise { return { capabilities: { toolCalls: true, vision: true, maxInputTokens: 120000, maxOutputTokens: 8192, } }; } async provideLanguageModelChatResponse(model: vscode.ChatModel, messages: vscode.ChatRequestTurn[], options: vscode.LanguageModelChatOptions, progress: vscode.Progress, token: vscode.CancellationToken): Promise { const prompt = messages[messages.length - 1].user; if (!prompt) { return; } let responseText = ""; if (model.modelId === MODEL_ID_CAT) { responseText = "Meow!"; } else if (model.modelId === MODEL_ID_DOG) { responseText = "Woof!"; } else { throw new Error(`Unknown model: ${model.modelId}`); } progress.report({ fragment: responseText }); } async provideLanguageModelChatModels(token: vscode.CancellationToken): Promise { return [ { modelId: MODEL_ID_CAT, vendor: { id: "sample", name: "Sample Provider" }, description: "A sample cat model.", family: vscode.LanguageModelFamily.Other, version: "1.0" }, { modelId: MODEL_ID_DOG, vendor: { id: "sample", name: "Sample Provider" }, description: "A sample dog model.", family: vscode.LanguageModelFamily.Other, version: "1.0" } ]; } } ``` -------------------------------- ### Sample Data for Call Hierarchy Source: https://github.com/microsoft/vscode-extension-samples/blob/main/call-hierarchy-sample/README.md This is the sample data format expected by the call hierarchy provider. It uses a simple subject ~ verb ~ object syntax. ```plaintext Coyote eats deer. Deer eats plants. Coyote eats lizard. Lizard eats bird. Lizard eats frog. Lizard eats butterfly. Bird eats seeds. Frog eats insects. Butterfly eats fruit. ``` -------------------------------- ### Create a Webview Panel in VS Code Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Opens a full HTML/CSS/JS panel inside VS Code. Use `webview.asWebviewUri` to reference local extension assets and `postMessage` / `onDidReceiveMessage` for bi-directional messaging. Scripts are sandboxed. ```typescript // webview-sample/src/extension.ts function createPanel(context: vscode.ExtensionContext) { const panel = vscode.window.createWebviewPanel( 'catCoding', // viewType (must match serializer registration) 'Cat Coding', // panel title vscode.ViewColumn.One, { enableScripts: true, localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'media')] } ); const scriptUri = panel.webview.asWebviewUri( vscode.Uri.joinPath(context.extensionUri, 'media', 'main.js') ); const nonce = Math.random().toString(36).slice(2); panel.webview.html = `

0

`; // Extension → Webview panel.webview.postMessage({ command: 'refactor' }); // Webview → Extension panel.webview.onDidReceiveMessage(msg => { if (msg.command === 'alert') { vscode.window.showErrorMessage(msg.text); } }); // Restore panel after VS Code restart vscode.window.registerWebviewPanelSerializer('catCoding', { async deserializeWebviewPanel(webviewPanel, _state) { // re-attach panel with same options } }); } ``` -------------------------------- ### Register Inline Completion Item Provider with vscode.languages.registerInlineCompletionItemProvider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Provides inline completion suggestions (ghost text) similar to GitHub Copilot. Supports snippet insertions, partial acceptance callbacks, and command attachments. Completions are determined by parsing comments on the previous line. ```typescript const provider: vscode.InlineCompletionItemProvider = { async provideInlineCompletionItems(document, position, _ctx, _token) { // Look at the comment on the previous line for completion spec: // // [startCol,endCol]:text const prevLine = document.lineAt(position.line - 1).text; const match = /\/\/ \[(\d+),(\d+|\*)](s?):(.+)/.exec(prevLine); if (!match) return; const [, start, end, flags, text] = match; const isSnippet = flags.includes('s'); return { items: [{ insertText: isSnippet ? new vscode.SnippetString(text) : text, range: new vscode.Range(position.line, +start, position.line, end === '*' ? document.lineAt(position.line).text.length : +end) }], commands: [{ command: 'demo-ext.command1', title: 'Inline Demo Command', arguments: [1, 2] }] }; }, handleDidShowCompletionItem(_item) { console.log('completion shown'); }, handleDidPartiallyAcceptCompletionItem(_item, info) { console.log('partial accept', info); } }; vscode.languages.registerInlineCompletionItemProvider({ pattern: '**' }, provider); ``` -------------------------------- ### vscode.window.createWebviewPanel Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Opens a full HTML/CSS/JS panel inside VS Code. Scripts are sandboxed; use `webview.asWebviewUri` to reference local extension assets. Bi-directional messaging uses `postMessage` / `onDidReceiveMessage`. ```APIDOC ## `vscode.window.createWebviewPanel` — Webview Panel ### Description Opens a full HTML/CSS/JS panel inside VS Code. Scripts are sandboxed; use `webview.asWebviewUri` to reference local extension assets. Bi-directional messaging uses `postMessage` / `onDidReceiveMessage`. ### Usage Example ```typescript // webview-sample/src/extension.ts function createPanel(context: vscode.ExtensionContext) { const panel = vscode.window.createWebviewPanel( 'catCoding', // viewType (must match serializer registration) 'Cat Coding', // panel title vscode.ViewColumn.One, { enableScripts: true, localResourceRoots: [vscode.Uri.joinPath(context.extensionUri, 'media')] } ); const scriptUri = panel.webview.asWebviewUri( vscode.Uri.joinPath(context.extensionUri, 'media', 'main.js') ); const nonce = Math.random().toString(36).slice(2); panel.webview.html = `

0

`; // Extension → Webview panel.webview.postMessage({ command: 'refactor' }); // Webview → Extension panel.webview.onDidReceiveMessage(msg => { if (msg.command === 'alert') { vscode.window.showErrorMessage(msg.text); } }); // Restore panel after VS Code restart vscode.window.registerWebviewPanelSerializer('catCoding', { async deserializeWebviewPanel(webviewPanel, _state) { // re-attach panel with same options } }); } ``` ``` -------------------------------- ### Register Virtual File System Provider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Mounts a custom URI scheme (e.g., memfs:/) to treat in-memory or remote content as a real file system. This enables full editor support for virtual files. ```typescript const memFs = new MemFS(); // implements vscode.FileSystemProvider context.subscriptions.push( vscode.workspace.registerFileSystemProvider('memfs', memFs, { isCaseSensitive: true }) ); // Populate the virtual FS const enc = new TextEncoder(); memFs.writeFile(vscode.Uri.parse('memfs:/hello.ts'), enc.encode('const x = 42;'), { create: true, overwrite: true }); memFs.createDirectory(vscode.Uri.parse('memfs:/src/')); // Add virtual workspace folder so VS Code opens it as a project vscode.workspace.updateWorkspaceFolders(0, 0, { uri: vscode.Uri.parse('memfs:/'), name: 'MemFS' }); ``` -------------------------------- ### vscode.languages.registerCompletionItemProvider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Supplies IntelliSense suggestions for a given language. This can be triggered either eagerly or by specific trigger characters. ```APIDOC ## `vscode.languages.registerCompletionItemProvider` — Completion Provider Supplies IntelliSense suggestions for a given language. Triggered either eagerly or by specific trigger characters. ```typescript // completions-sample/src/extension.ts // Provider 1: always-available completions const provider1 = vscode.languages.registerCompletionItemProvider('plaintext', { provideCompletionItems() { const snippet = new vscode.CompletionItem('Good part of the day'); snippet.insertText = new vscode.SnippetString('Good ${1|morning,afternoon,evening|}!'); snippet.documentation = new vscode.MarkdownString('Time-aware greeting snippet'); const cmd = new vscode.CompletionItem('new'); cmd.kind = vscode.CompletionItemKind.Keyword; cmd.insertText = 'new '; cmd.command = { command: 'editor.action.triggerSuggest', title: 'Re-trigger' }; return [new vscode.CompletionItem('Hello World!'), snippet, cmd]; } }); // Provider 2: triggered by '.' — offer console methods const provider2 = vscode.languages.registerCompletionItemProvider( 'plaintext', { provideCompletionItems(document, position) { const prefix = document.lineAt(position).text.slice(0, position.character); if (!prefix.endsWith('console.')) return undefined; return ['log', 'warn', 'error'].map(m => new vscode.CompletionItem(m, vscode.CompletionItemKind.Method) ); } }, '.' // trigger character ); context.subscriptions.push(provider1, provider2); ``` ``` -------------------------------- ### Watch for Changes Source: https://github.com/microsoft/vscode-extension-samples/blob/main/chat-model-provider-sample/README.md Automatically recompile the extension when source files change. ```bash npm run watch ``` -------------------------------- ### Register Completion Item Provider for Plaintext Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Supplies IntelliSense suggestions for plaintext files. Can be triggered eagerly or by specific characters like '.'. ```typescript // completions-sample/src/extension.ts // Provider 1: always-available completions const provider1 = vscode.languages.registerCompletionItemProvider('plaintext', { provideCompletionItems() { const snippet = new vscode.CompletionItem('Good part of the day'); snippet.insertText = new vscode.SnippetString('Good ${1|morning,afternoon,evening|}!'); snippet.documentation = new vscode.MarkdownString('Time-aware greeting snippet'); const cmd = new vscode.CompletionItem('new'); cmd.kind = vscode.CompletionItemKind.Keyword; cmd.insertText = 'new '; cmd.command = { command: 'editor.action.triggerSuggest', title: 'Re-trigger' }; return [new vscode.CompletionItem('Hello World!'), snippet, cmd]; } }); // Provider 2: triggered by '.' — offer console methods const provider2 = vscode.languages.registerCompletionItemProvider( 'plaintext', { provideCompletionItems(document, position) { const prefix = document.lineAt(position).text.slice(0, position.character); if (!prefix.endsWith('console.')) return undefined; return ['log', 'warn', 'error'].map(m => new vscode.CompletionItem(m, vscode.CompletionItemKind.Method) ); } }, '.' // trigger character ); context.subscriptions.push(provider1, provider2); ``` -------------------------------- ### Vim Search Forward (/) Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Use the '/' command followed by a search term to find the next occurrence of that term in the file. Press 'n' to repeat the search in the same direction or 'N' to search in the opposite direction. ```vim /errroor ``` ```vim n ``` ```vim N ``` -------------------------------- ### Contribute View Actions Source: https://github.com/microsoft/vscode-extension-samples/blob/main/tree-view-sample/USAGE.md Add commands and associate them with menu locations in the view title or item context menus using the 'contributes' section. ```json "contributes": { "commands": [ { "command": "nodeDependencies.refreshEntry", "title": "Refresh", "icon": { "light": "resources/light/refresh.svg", "dark": "resources/dark/refresh.svg" } } ], "menus": { "view/title": [ { "command": "nodeDependencies.refreshEntry", "when": "view == nodeDependencies", "group": "navigation" } ] } } ``` ```json "contributes": { "menus": { "view/item/context": [ { "command": "nodeDependencies.deleteEntry", "when": "view == nodeDependencies && viewItem == dependency" } ] } } ``` -------------------------------- ### vscode.window.registerCustomEditorProvider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Registers a `CustomTextEditorProvider` that renders a webview instead of the default text editor for specific file types. ```APIDOC ## `vscode.window.registerCustomEditorProvider` — Custom Editor Registers a `CustomTextEditorProvider` that renders a webview instead of the default text editor for specific file types (declared in `package.json` under `contributes.customEditors`). ```typescript // custom-editor-sample/src/catScratchEditor.ts class CatScratchEditorProvider implements vscode.CustomTextEditorProvider { static register(ctx: vscode.ExtensionContext): vscode.Disposable { return vscode.window.registerCustomEditorProvider( 'catCustoms.catScratch', new CatScratchEditorProvider(ctx) ); } async resolveCustomTextEditor( document: vscode.TextDocument, panel: vscode.WebviewPanel, _token: vscode.CancellationToken ): Promise { panel.webview.options = { enableScripts: true }; panel.webview.html = this.getHtml(panel.webview); const sync = () => panel.webview.postMessage({ type: 'update', text: document.getText() }); // Keep webview in sync with the document model const sub = vscode.workspace.onDidChangeTextDocument(e => { if (e.document.uri.toString() === document.uri.toString()) sync(); }); panel.onDidDispose(() => sub.dispose()); panel.webview.onDidReceiveMessage(e => { if (e.type === 'add') { const edit = new vscode.WorkspaceEdit(); const json = JSON.parse(document.getText() || '{}'); json.scratches = [...(json.scratches ?? []), { id: Date.now(), text: '😸' }]; edit.replace(document.uri, new vscode.Range(0, 0, document.lineCount, 0), JSON.stringify(json, null, 2)); vscode.workspace.applyEdit(edit); } }); sync(); } // ... getHtml omitted for brevity } ``` ``` -------------------------------- ### Export Localizable Strings Source: https://github.com/microsoft/vscode-extension-samples/blob/main/l10n-sample/README.md Use this command to extract localizable strings from your extension's source code into a `bundle.l10n.json` file. Specify the output directory and the source directory. ```sh npx @vscode/l10n-dev export -o ./l10n ./src ``` -------------------------------- ### Configure Source Control Commands Source: https://github.com/microsoft/vscode-extension-samples/blob/main/source-control-sample/README.md Defines commands to be displayed in the source control view's title bar, including commit, discard, refresh, and browse actions. ```json "contributes": { "commands": [ ... ], "menus": { "scm/title": [ { "command": "extension.source-control.commit", "group": "navigation", "when": "scmProvider == jsfiddle" }, { "command": "extension.source-control.discard", "group": "navigation", "when": "scmProvider == jsfiddle" }, { "command": "extension.source-control.refresh", "group": "navigation", "when": "scmProvider == jsfiddle" }, { "command": "extension.source-control.browse", "when": "scmProvider == jsfiddle" } ] } }, ``` -------------------------------- ### Create TreeView Programmatically Source: https://github.com/microsoft/vscode-extension-samples/blob/main/tree-view-sample/USAGE.md Use `window.createTreeView` to create a view and gain programmatic access to its UI operations. This requires providing a TreeDataProvider. ```typescript vscode.window.createTreeView('ftpExplorer', { treeDataProvider: new FtpTreeDataProvider() }); ``` -------------------------------- ### Vim: Confirm Substitutions Source: https://github.com/microsoft/vscode-extension-samples/blob/main/vim-sample/vimtutor.txt Add the 'c' flag to '%s/old/new/gc' to prompt for confirmation before each substitution in the entire file. ```vim :%s/old/new/gc ``` -------------------------------- ### vscode.window.createTerminal Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Enables the creation of integrated terminals, sending text to them, monitoring their lifecycle, and registering custom link or profile providers. ```APIDOC ## vscode.window.createTerminal — Terminal Control Creates integrated terminals, sends text, monitors lifecycle, and registers link providers or profile providers. ### Creating and Interacting with Terminals ```typescript const terminal = vscode.window.createTerminal('My Terminal'); terminal.sendText("echo 'Hello from extension!'"); terminal.show(); ``` ### Updating Environment Variables ```typescript context.environmentVariableCollection.replace('FOO', 'BAR'); context.environmentVariableCollection.append('PATH', '/my/tool/bin'); ``` ### Listening for Terminal Lifecycle Events - `vscode.window.onDidOpenTerminal`: Called when a terminal is opened. - `vscode.window.onDidCloseTerminal`: Called when a terminal is closed. ### Registering a Custom Terminal Link Provider Implement the `provideTerminalLinks` and `handleTerminalLink` methods to define custom links within the terminal. ```typescript vscode.window.registerTerminalLinkProvider({ provideTerminalLinks(ctx, _token) { const idx = ctx.line.indexOf('link'); return idx === -1 ? [] : [{ startIndex: idx, length: 4, tooltip: 'Open link' }]; }, handleTerminalLink(link) { vscode.window.showInformationMessage(`Link clicked: ${link.tooltip}`); } }); ``` ``` -------------------------------- ### registerCodeLensProvider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Adds a CodeLens provider to VS Code. This allows extensions to contribute clickable action links above lines of code. The `provideCodeLenses` method is responsible for returning `CodeLens` objects, and `resolveCodeLens` can be used to lazily attach commands to these lenses. ```APIDOC ## registerCodeLensProvider ### Description Adds a CodeLens provider to VS Code, enabling extensions to contribute clickable action links above lines of code. The `provideCodeLenses` method returns `CodeLens` objects, and `resolveCodeLens` lazily attaches commands. ### Method Signature ```typescript vscode.languages.registerCodeLensProvider(selector: DocumentSelector, provider: CodeLensProvider): Disposable ``` ### Parameters * **selector** (DocumentSelector) - A glob pattern or language identifier that identifies the documents for which the provider should be active. * **provider** (CodeLensProvider) - The CodeLens provider to register. ### Example Usage ```typescript import * as vscode from 'vscode'; class CodelensProvider implements vscode.CodeLensProvider { private _onDidChangeCodeLenses = new vscode.EventEmitter(); onDidChangeCodeLenses = this._onDidChangeCodeLenses.event; provideCodeLenses(document: vscode.TextDocument): vscode.CodeLens[] { const lenses: vscode.CodeLens[] = []; for (const [i, line] of document.getText().split('\n').entries()) { if (line.includes('//')) { lenses.push(new vscode.CodeLens(new vscode.Range(i, 0, i, 0))); } } return lenses; } resolveCodeLens(lens: vscode.CodeLens): vscode.CodeLens { lens.command = { title: 'Codelens provided by sample extension', command: 'codelens-sample.codelensAction', arguments: ['Argument 1', false] }; return lens; } } // Registration: vscode.languages.registerCodeLensProvider('*', new CodelensProvider()); ``` ``` -------------------------------- ### Contribute View Container and View Source: https://github.com/microsoft/vscode-extension-samples/blob/main/tree-view-sample/USAGE.md Define a new view container in the activity bar and a view within that container using the 'contributes' section of your extension's package.json. ```json "contributes": { "viewsContainers": { "activitybar": [ { "id": "package-explorer", "title": "Package Explorer", "icon": "media/dep.svg" } ] }, "views": { "tree-view": [ { "id": "nodeDependencies", "name": "Node Dependencies", "when": "workspaceHasPackageJSON" } ] } } ``` -------------------------------- ### vscode.tasks.registerTaskProvider Source: https://context7.com/microsoft/vscode-extension-samples/llms.txt Implements `vscode.TaskProvider` to allow VS Code to auto-detect tasks. `provideTasks` discovers tasks, and `resolveTask` constructs a runnable `Task` from a definition. ```APIDOC ## vscode.tasks.registerTaskProvider — Custom Task Provider Implements `vscode.TaskProvider` so VS Code can auto-detect tasks (e.g., from a Rakefile). `provideTasks` discovers tasks; `resolveTask` constructs a runnable `Task` from a definition stored in `tasks.json`. ### Class: RakeTaskProvider Implements the `vscode.TaskProvider` interface. #### Constructor - `workspaceRoot` (string): The root path of the workspace. #### Methods - `provideTasks(): Thenable | undefined`: Discovers and returns available tasks. - `resolveTask(task: vscode.Task): vscode.Task | undefined`: Constructs a runnable `Task` from a definition. ### Registration ```typescript vscode.tasks.registerTaskProvider(RakeTaskProvider.RakeType, new RakeTaskProvider(workspaceRoot)); ``` ``` -------------------------------- ### Create Decoration Ranges with Regex Source: https://github.com/microsoft/vscode-extension-samples/blob/main/decorator-sample/USAGE.md Generate an array of DecorationOptions by finding text matches using a regular expression. Each decoration includes a range and an optional hover message. ```typescript const regEx = /\d+/g; const text = activeEditor.document.getText(); const smallNumbers: vscode.DecorationOptions[] = []; let match; while (match = regEx.exec(text)) { const startPos = activeEditor.document.positionAt(match.index); const endPos = activeEditor.document.positionAt(match.index + match[0].length); const decoration = { range: new vscode.Range(startPos, endPos), hoverMessage: 'Number **' + match[0] + '**' }; if (match[0].length < 3) { smallNumbers.push(decoration); } } ``` -------------------------------- ### Provide Original Resource for Diff Source: https://github.com/microsoft/vscode-extension-samples/blob/main/source-control-sample/README.md Retrieves the original resource content from the repository, used for comparing with local changes in the diff view. ```javascript this.fiddleRepository.provideOriginalResource(doc.uri, null) ```