### VS Code Getting Started Icons
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/icons-in-labels.md
This snippet lists icons used in the VS Code 'Getting Started' feature, categorized for beginners, codespaces, setup, and item completion status.
```HTML
||getting-started-beginner|lightbulb|Icon used for the beginner category of getting started|
```
```HTML
||getting-started-codespaces|github|Icon used for the codespaces category of getting started|
```
```HTML
||getting-started-item-checked|pass-filled|Used to represent getting started items which have been completed|
```
```HTML
||getting-started-item-unchecked|circle-large-outline|Used to represent getting started items which have not been completed|
```
```HTML
||getting-started-setup|heart|Icon used for the setup category of getting started|
```
--------------------------------
### Contribute Walkthroughs for VS Code Getting Started
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/contribution-points.md
This JSON snippet shows how to define walkthroughs for the VS Code Getting Started page. It includes a walkthrough with multiple steps, each having a title, description, media (image or markdown), and completion events.
```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"]
}
]
}
]
}
}
```
--------------------------------
### Install and Run LSP Sample
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
This snippet shows the bash commands to clone the VS Code extension samples repository, navigate to the lsp-sample directory, install dependencies, compile the code, and open the sample in VS Code.
```bash
> git clone https://github.com/microsoft/vscode-extension-samples.git
> cd vscode-extension-samples/lsp-sample
> npm install
> npm run compile
> code .
```
--------------------------------
### VS Code Remote Explorer Get Started Icon
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/icons-in-labels.md
An icon in the remote explorer view that signifies the 'getting started' section.
```HTML
```
--------------------------------
### Custom Setup: Install Extension with @vscode/test-electron
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/testing-extension.md
This TypeScript example shows a custom setup for VS Code extension testing using `@vscode/test-electron`. It downloads a specific VS Code version, resolves CLI arguments, installs another extension using `cp.spawnSync`, and then runs the 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();
```
--------------------------------
### Create MCP Install URL - TypeScript
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/mcp.md
Generates a URL to install an MCP server in VS Code. This URL can be used in browsers or command lines to trigger the installation process.
```typescript
const obj = {
// MCP server configuration object
};
// For Insiders, use `vscode-insiders` instead of `code`
const link = `vscode:mcp/install?${encodeURIComponent(JSON.stringify(obj))}`;
```
--------------------------------
### TextMate Grammar Example (Conceptual)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/syntax-highlight-guide.md
Illustrates the concept of TextMate tokens and scopes, showing how an operator like '+' in JavaScript is assigned a scope for syntax highlighting.
```JavaScript
keyword.operator.arithmetic.js
```
--------------------------------
### Clone and Setup Mock Debug
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/debugger-extension.md
Clones the Mock Debug repository from GitHub, navigates into the project directory, and installs the necessary dependencies using Yarn.
```bash
git clone https://github.com/microsoft/vscode-mock-debug.git
cd vscode-mock-debug
yarn
```
--------------------------------
### Install and Use js-yaml for Grammar Conversion
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/syntax-highlight-guide.md
This snippet demonstrates how to install the `js-yaml` package as a development dependency and use its command-line interface to convert a YAML TextMate grammar file to a JSON file, which is required by VS Code.
```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 Completion Events for Walkthrough Steps
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/contribution-points.md
This snippet demonstrates how to configure specific events that trigger the completion of a walkthrough step. It includes examples for command execution, setting changes, context evaluation, extension installation, view visibility, and link opening.
```plaintext
- `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.
```
--------------------------------
### Start Connection Listener
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
Initiates listening on the connection to receive and process incoming messages and events from VS Code.
```TypeScript
connection.listen();
```
--------------------------------
### Initialize Telemetry with @vscode/extension-telemetry
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/telemetry.md
This snippet demonstrates how to initialize the telemetry client using the `@vscode/extension-telemetry` npm module. It requires an extension ID, version, and an Application Insights instrumentation key. Ensure you have installed the module and obtained your instrumentation key from Azure Monitor.
```TypeScript
import { registerCommand } from '@vscode/extension-telemetry';
// Replace with your extension's ID and version
const extensionId = 'your-publisher.your-extension-name';
const extensionVersion = '1.0.0';
// Replace with your Application Insights instrumentation key
const instrumentationKey = 'YOUR_INSTRUMENTATION_KEY';
// Register the telemetry client
registerCommand(extensionId, extensionVersion, instrumentationKey);
```
--------------------------------
### VS Code Language Client Initialization and Management
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
Implements the core logic for a VS Code Language Client extension using TypeScript. It sets up the server options, client options (including document selection and file event synchronization), and manages the client's lifecycle (start and stop).
```typescript
import * as path from 'path';
import { workspace, ExtensionContext } from 'vscode';
import {
LanguageClient,
LanguageClientOptions,
ServerOptions,
TransportKind
} from 'vscode-languageclient/node';
let client: LanguageClient;
export function activate(context: ExtensionContext) {
// The server is implemented in node
let serverModule = context.asAbsolutePath(path.join('server', 'out', 'server.js'));
// The debug options for the server
// --inspect=6009: runs the server in Node's Inspector mode so VS Code can attach to the server for debugging
let debugOptions = { execArgv: ['--nolazy', '--inspect=6009'] };
// If the extension is launched in debug mode then the debug server options are used
// Otherwise the run options are used
let serverOptions: ServerOptions = {
run: { module: serverModule, transport: TransportKind.ipc },
debug: {
module: serverModule,
transport: TransportKind.ipc,
options: debugOptions
}
};
// Options to control the language client
let clientOptions: LanguageClientOptions = {
// Register the server for plain text documents
documentSelector: [{ scheme: 'file', language: 'plaintext' }],
synchronize: {
// Notify the server about file changes to '.clientrc files contained in the workspace
fileEvents: workspace.createFileSystemWatcher('**/.clientrc')
}
};
// Create the language client and start the client.
client = new LanguageClient(
'languageServerExample',
'Language Server Example',
serverOptions,
clientOptions
);
// Start the client. This will also launch the server
client.start();
}
export function deactivate(): Thenable | undefined {
if (!client) {
return undefined;
}
return client.stop();
}
```
--------------------------------
### TypeScript Example: Performing Completion Tests
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
This TypeScript code demonstrates how to test language completion features. It includes a test suite that activates the extension, triggers completion using `vscode.executeCompletionItemProvider`, and asserts the returned completion items against expected results.
```typescript
import * as vscode from 'vscode';
import * as assert from 'assert';
import { getDocUri, activate } from './helper';
suite('Should do completion', () => {
const docUri = getDocUri('completion.txt');
test('Completes JS/TS in txt file', async () => {
await testCompletion(docUri, new vscode.Position(0, 0), {
items: [
{ label: 'JavaScript', kind: vscode.CompletionItemKind.Text },
{ label: 'TypeScript', kind: vscode.CompletionItemKind.Text }
]
});
});
});
async function testCompletion(
docUri: vscode.Uri,
position: vscode.Position,
expectedCompletionList: vscode.CompletionList
) {
await activate(docUri);
// Executing the command `vscode.executeCompletionItemProvider` to simulate triggering completion
const actualCompletionList = (await vscode.commands.executeCommand(
'vscode.executeCompletionItemProvider',
docUri,
position
)) as vscode.CompletionList;
assert.ok(actualCompletionList.items.length >= 2);
expectedCompletionList.items.forEach((expectedItem, i) => {
const actualItem = actualCompletionList.items[i];
assert.equal(actualItem.label, expectedItem.label);
assert.equal(actualItem.kind, expectedItem.kind);
});
}
```
--------------------------------
### VS Code package.json Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/extension-manifest.md
A complete example of a `package.json` file for a VS Code extension, demonstrating common fields such as name, version, description, activation events, engines, main, scripts, devDependencies, and repository information.
```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"
}
```
--------------------------------
### Register MCP Server Definition Provider (TypeScript)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/mcp.md
Demonstrates registering an MCP server definition provider in a VS Code extension. It includes examples for both stdio and HTTP server definitions and shows how to prompt the user for an API key when resolving a server definition.
```TypeScript
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const didChangeEmitter = new vscode.EventEmitter();
context.subscriptions.push(vscode.lm.registerMcpServerDefinitionProvider('exampleProvider', {
onDidChangeMcpServerDefinitions: didChangeEmitter.event,
provideMcpServerDefinitions: async () => {
let servers: vscode.McpServerDefinition[] = [];
// Example of a simple stdio server definition
servers.push(new vscode.McpStdioServerDefinition({
label: 'myServer',
command: 'node',
args: ['server.js'],
cwd: vscode.Uri.file('/path/to/server'),
env: {
API_KEY: ''
},
version: '1.0.0'
}));
// Example of an HTTP server definition
servers.push(new vscode.McpHttpServerDefinition({
label: 'myRemoteServer',
uri: 'http://localhost:3000',
headers: {
'API_VERSION': '1.0.0'
},
version: '1.0.0'
}));
return servers;
},
resolveMcpServerDefinition: async (server: vscode.McpServerDefinition) => {
if (server.label === 'myServer') {
// Get the API key from the user, e.g. using vscode.window.showInputBox
// Update the server definition with the API key
}
// Return undefined to indicate that the server should not be started or throw an error
// If there is a pending tool call, the editor will cancel it and return an error message
// to the language model.
return server;
}
}));
}
```
--------------------------------
### Install VS Code Extension from VSIX file
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/publishing-extension.md
This section provides instructions on how to install a VS Code extension packaged as a .vsix file. It covers installation via the VS Code Extensions view and through the command line for both standard and Insiders versions.
```bash
# if you use VS Code
code --install-extension my-extension-0.0.1.vsix
# if you use VS Code Insiders
code-insiders --install-extension my-extension-0.0.1.vsix
```
--------------------------------
### VS Code Extension package.json
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/webview.md
Defines the metadata and contribution points for a VS Code extension. This example shows how to contribute a command 'catCoding.start' that will be available in the Command Palette.
```json
{
"name": "cat-coding",
"description": "Cat Coding",
"version": "0.0.1",
"publisher": "bierner",
"engines": {
"vscode": "^1.74.0"
},
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
{
"command": "catCoding.start",
"title": "Start new cat coding session",
"category": "Cat Coding"
}
]
},
"scripts": {
"vscode:prepublish": "tsc -p ./",
"compile": "tsc -watch -p ./",
"postinstall": "node ./node_modules/vscode/bin/install"
},
"dependencies": {
"vscode": "*"
},
"devDependencies": {
"@types/node": "^9.4.6",
"typescript": "^2.8.3"
}
}
```
--------------------------------
### TypeScript Example: Activating VS Code Extension and Document
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
This TypeScript code snippet shows how to activate a VS Code extension and open a document for testing purposes. It retrieves the extension by its ID, activates it, opens the specified document, and displays it in the editor, with a delay to ensure server activation.
```typescript
import * as vscode from 'vscode';
import * as path from 'path';
export let doc: vscode.TextDocument;
export let editor: vscode.TextEditor;
export let documentEol: string;
export let platformEol: string;
/**
* Activates the vscode.lsp-sample extension
*/
export async function activate(docUri: vscode.Uri) {
// The extensionId is `publisher.name` from package.json
const ext = vscode.extensions.getExtension('vscode-samples.lsp-sample')!;
await ext.activate();
try {
doc = await vscode.workspace.openTextDocument(docUri);
editor = await vscode.window.showTextDocument(doc);
await sleep(2000); // Wait for server activation
} catch (e) {
console.error(e);
}
}
async function sleep(ms: number) {
return new Promise(resolve => setTimeout(resolve, ms));
}
```
--------------------------------
### Example .vscodeignore for Publishing
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/bundling-extension.md
This bash script provides an example of a .vscodeignore file. It lists files and directories that should be excluded when publishing your VS Code extension, such as node_modules, source files, and configuration files, to reduce the package size.
```bash
.vscode
node_modules
out/
src/
tsconfig.json
webpack.config.js
esbuild.js
```
--------------------------------
### Install Extension
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/commands.md
Installs an extension into VS Code. Requires the extension ID or a VSIX resource URI, and optionally accepts installation options.
```javascript
workbench.extensions.installExtension(extensionIdOrVSIXUri, options)
```
--------------------------------
### Install VS Code Test CLI and Electron
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/testing-extension.md
Installs the necessary modules for running VS Code extension tests locally. `@vscode/test-cli` provides the command-line interface, and `@vscode/test-electron` enables tests to run in VS Code Desktop.
```bash
npm install --save-dev @vscode/test-cli @vscode/test-electron
```
--------------------------------
### Start Local HTTPS Server with npx serve
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/web-extensions.md
This command starts a local HTTP server using `npx serve` with CORS enabled, listening on port 5000, and configured to use SSL certificates for secure connections. It outputs the local and network URLs for accessing the server.
```shell
npx serve --cors -l 5000 --ssl-cert $HOME/certs/localhost.pem --ssl-key $HOME/certs/localhost-key.pem
```
--------------------------------
### Git Status Output Example (Bash)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/scm-provider.md
An example of the output from the 'git status' command, illustrating file changes, staging status, and modifications within a Git repository. This output serves as a reference for structuring the Source Control model in VS Code.
```Bash
vsce main* → git status
On branch main
Your branch is up-to-date with 'origin/main'.
Changes to be committed:
(use "git reset HEAD ..." to unstage)
modified: README.md
renamed: src/api.ts -> src/test/api.ts
Changes not staged for commit:
(use "git add/rm ..." to update what will be committed)
(use "git checkout -- ..." to discard changes in working directory)
deleted: .travis.yml
modified: README.md
```
--------------------------------
### Install vsce CLI Tool
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/publishing-extension.md
Installs the `vsce` command-line tool globally using npm. This tool is essential for packaging and publishing VS Code extensions.
```bash
npm install -g @vscode/vsce
```
--------------------------------
### Python Extension Settings Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/advanced-topics/python-extension-template.md
This snippet shows example settings that can be configured for a Python extension built with the template. These settings allow users to customize the behavior of the integrated Python tool, such as log levels, arguments, and interpreter paths.
```JSON
{
"configuration": {
"title": "My Tool Settings",
"properties": {
"mytool.logLevel": {
"type": "string",
"default": "info",
"description": "Logging level for My Tool."
},
"mytool.path": {
"type": "string",
"description": "Path to the Python tool executable."
}
}
}
}
```
--------------------------------
### Generate SSL Certificates with mkcert
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/web-extensions.md
This snippet demonstrates how to create a directory for certificates, navigate into it, install mkcert as a trusted Certificate Authority, and generate SSL certificates for localhost.
```bash
mkdir -p $HOME/certs
cd $HOME/certs
mkcert -install
mkcert localhost
```
--------------------------------
### Enable Indentation Guides
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/theme-color.md
Enable indentation guides and highlight the active indentation guide by setting the respective configuration options to true.
```json
{
"editor.guides.indentation": true,
"editor.guides.highlightActiveIndentation": true
}
```
--------------------------------
### Install ESLint and TypeScript Support (npm)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/advanced-topics/tslint-eslint-migration.md
Installs ESLint, the TypeScript parser, and the TypeScript ESLint plugin using npm. These are essential for ESLint to understand and lint TypeScript code.
```bash
npm install --save-dev eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin
```
--------------------------------
### Markdown Notebook Serializer Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/notebook.md
An example Visual Studio Code extension that allows users to open and edit Markdown files as notebooks, leveraging the Notebook API for a notebook-like editing experience.
```JavaScript
import * as vscode from 'vscode';
export class MarkdownNotebookSerializer implements vscode.NotebookSerializer {
async deserializeNotebook(content: Uint8Array, _token: vscode.CancellationToken):
Promise {
const contents = Buffer.from(content).toString('utf-8');
const cells = contents.split('\n---\n').map(cellContent => {
const lines = cellContent.split('\n');
const language = lines[0].startsWith('#') ? 'markdown' : 'code';
const code = lines.slice(1).join('\n');
const cellKind = language === 'markdown' ? vscode.NotebookCellKind.Markup : vscode.NotebookCellKind.Code;
return new vscode.NotebookCellData(cellKind, code, language);
});
return new vscode.NotebookData(cells);
}
async serializeNotebook(data: vscode.NotebookData, _token: vscode.CancellationToken):
Promise {
const contents = data.cells.map(cell => {
let header = '';
if (cell.kind === vscode.NotebookCellKind.Markup) {
header = '# ' + cell.languageId;
} else {
header = '// ' + cell.languageId;
}
return `${header}\n${cell.value}`;
}).join('\n---\n');
return Buffer.from(contents);
}
}
```
--------------------------------
### VS Code Extension API: Webview Guide
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/index.md
This snippet links to the Webview Guide, which explains how to create custom webviews within VS Code extensions. These webviews allow displaying custom HTML, CSS, and JavaScript content.
```Markdown
[Webview Guide](/api/extension-guides/webview)
```
--------------------------------
### Install Webpack and Webpack CLI using npm
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/bundling-extension.md
This command installs webpack and its command-line interface as development dependencies for a project. Webpack is a module bundler commonly used in modern JavaScript development.
```bash
npm i --save-dev webpack webpack-cli
```
--------------------------------
### Python Extension Command Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/advanced-topics/python-extension-template.md
This example demonstrates how a command is defined for a Python extension. The 'My Tool: Restart Server' command is registered with a specific command ID, allowing users to trigger actions within the extension via the VS Code command palette.
```JSON
{
"contributes": {
"commands": [
{
"command": "mytool.restart",
"title": "My Tool: Restart Server"
}
]
}
}
```
--------------------------------
### Install esbuild Bundler
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/bundling-extension.md
This snippet shows how to install esbuild as a development dependency using npm. esbuild is a fast JavaScript bundler recommended for consolidating extension code.
```bash
npm i --save-dev esbuild
```
--------------------------------
### VS Code Welcome View Extension Sample
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/ux-guidelines/sidebars.md
Sample code for contributing a Welcome View to VS Code, often used for initial onboarding or providing introductory information within the extension.
```Link
https://github.com/microsoft/vscode-extension-samples/tree/main/welcome-view-content-sample
```
--------------------------------
### VS Code Debug Start Keybinding Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/when-clause-contexts.md
Demonstrates a 'when' clause for the 'Start Debugging' command, enabling it only when debuggers are available and the editor is not in debug mode.
```JSON
{
"key": "f5",
"command": "workbench.action.debug.start",
"when": "debuggersAvailable && !inDebugMode"
}
```
--------------------------------
### Configure New Extension (Bash)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/get-started/your-first-extension.md
Example configuration prompts for creating a new TypeScript VS Code extension named 'HelloWorld'. It covers project identifier, description, Git initialization, bundler choice, and package manager.
```Bash
# ? What type of extension do you want to create? New Extension (TypeScript)
# ? What's the name of your extension? HelloWorld
### Press to choose default for all options below ###
# ? What's the identifier of your extension? helloworld
# ? What's the description of your extension? LEAVE BLANK
# ? Initialize a git repository? Y
# ? Which bundler to use? unbundled
# ? Which package manager to use? npm
# ? Do you want to open the new folder with Visual Studio Code? Open with `code`
```
--------------------------------
### Webpack Configuration Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/web-extensions.md
A basic webpack configuration file (`webpack.config.js`) used for bundling VS Code web extension sources into a single file, suitable for the browser environment.
```JavaScript
const path = require('path');
module.exports = {
target: 'webworker',
entry: './src/web/extension.ts',
output: {
filename: 'extension.js',
path: path.resolve(__dirname, 'out/web')
},
module: {
rules: [
{
test: /.ts?$/,
use: 'ts-loader',
exclude: /node_modules/
}
]
},
resolve: {
extensions: ['.ts', '.js']
}
};
```
--------------------------------
### LSP Sample Project Structure
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
This illustrates the typical directory structure for a VS Code Language Server Protocol sample, separating the client, server, and shared configuration files like package.json.
```json
{
"client": {
"src": {
"test": "// End to End tests for Language Client / Server",
"extension.ts": "// Language Client entry point"
}
},
"package.json": "// The extension manifest",
"server": {
"src": {
"server.ts": "// Language Server entry point"
}
}
}
```
--------------------------------
### Contribute Welcome View to VS Code
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/ux-guidelines/sidebars.md
Extensions can contribute a Welcome View, which is typically displayed when a user first opens VS Code or installs a new extension.
```JSON
{
"contributes": {
"viewsWelcome": [
{
"view": "myExtension.view",
"contents": "Welcome to My Extension!"
}
]
}
}
```
--------------------------------
### VS Code Quick Pick Extension Sample
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/ux-guidelines/quick-picks.md
This snippet provides a link to a sample VS Code extension that demonstrates the usage of Quick Picks, serving as a practical example for developers.
```Markdown
* [Quick Pick extension sample](https://github.com/microsoft/vscode-extension-samples/tree/main/quickinput-sample)
```
--------------------------------
### Install Latest vsce
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/extension-manifest.md
Ensures you are using the latest version of the `vsce` tool for packaging and publishing VS Code extensions. This is a prerequisite for many Marketplace features.
```bash
npm install -g @vscode/vsce
```
--------------------------------
### Get Active Editor Group Index
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/when-clause-contexts.md
Provides the index (starting from 1) of the active editor group within the editor grid. The top-left group has index 1.
```JSON
{
"when": "activeEditorGroupIndex == 1"
}
```
--------------------------------
### VS Code Extension API: Hello World Sample
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/index.md
This snippet refers to the 'Hello World' sample, a fundamental starting point for building VS Code extensions. It demonstrates basic extension concepts and serves as an entry point for learning the API.
```TypeScript
/*
This is a placeholder for the actual code from the helloworld-sample.
Refer to https://github.com/microsoft/vscode-extension-samples/tree/main/helloworld-sample for the complete code.
Example structure:
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
vscode.window.showInformationMessage('Hello World from Your Extension!');
});
context.subscriptions.push(disposable);
}
export function deactivate() {}
*/
```
--------------------------------
### Create TreeView (TypeScript)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/tree-view.md
Creates a VS Code TreeView programmatically, providing UI operations and access to the view. This TypeScript example demonstrates using `window.createTreeView` with a custom TreeDataProvider.
```typescript
vscode.window.createTreeView('ftpExplorer', {
treeDataProvider: new FtpTreeDataProvider()
});
```
--------------------------------
### VS Code API: Define Item Types and Get Type from TestItem
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/testing.md
This example defines an enum for TestItem types (File, TestCase) and shows how to retrieve the type associated with a TestItem using a WeakMap.
```typescript
enum ItemType {
File,
TestCase,
}
const testData = new WeakMap();
const getType = (testItem: vscode.TestItem) => testData.get(testItem)!;
```
--------------------------------
### Get All Available Language Models
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/language-model.md
Retrieves a list of all available language models that can be used with the VS Code Language Model API. This is useful for understanding model availability and selecting the most appropriate one for an extension.
```typescript
const allModels = await vscode.lm.selectChatModels(MODEL_SELECTOR);
```
--------------------------------
### Apply Theming to Custom Token Types
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/semantic-highlight-guide.md
This JSON example shows a theme definition where a specific color is applied to the 'type' token. Due to inheritance, this styling will also apply to custom subtypes like 'templateType'.
```JSON
{
"name": "Red Theme",
"semanticTokenColors": {
"type": "#ff0011"
}
}
```
--------------------------------
### VS Code LSP Multi Root Server Extension Sample
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/overview.md
This sample demonstrates how to handle Language Servers in a multi-root workspace environment. It shows how to manage multiple server instances for different workspace folders.
```TypeScript
// Sample code for multi-root LSP support would involve managing LanguageClient instances per workspace folder.
```
--------------------------------
### Get Document Settings (TypeScript)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/language-extensions/language-server-extension-guide.md
Retrieves configuration settings for a specific document resource. It caches settings and fetches them from the workspace if not already available. This function is crucial for applying user-defined configurations to extension behavior.
```typescript
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;
}
```
--------------------------------
### Configure MCP Development Mode (JSON)
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/mcp.md
Shows how to configure development mode for a Node.js MCP server in VS Code. This configuration enables watching for TypeScript file changes in the 'src' directory and attaches the Node.js debugger when the server starts.
```JSON
{
"servers": {
"my-mcp-server": {
"type": "stdio",
"command": "node",
"cwd": "${workspaceFolder}",
"args": [
"./build/index.js"
],
"dev": {
"watch": "src/**/*.ts",
"debug": { "type": "node" }
}
}
}
}
```
--------------------------------
### Package and Publish Extension with vsce
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/publishing-extension.md
Demonstrates the basic usage of the `vsce` tool to package an extension into a `.vsix` file and then publish it to the VS Code Marketplace.
```bash
cd myExtension
vsce package
# myExtension.vsix generated
vsce publish
# .myExtension published to VS Code Marketplace
```
--------------------------------
### Respect User Telemetry Settings
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/telemetry.md
This example shows how to check if telemetry is enabled for the user using the `isTelemetryEnabled` API and how to subscribe to changes in telemetry settings using `onDidChangeTelemetryEnabled`. This is crucial for respecting user privacy choices, even when using custom telemetry solutions.
```JavaScript
import { isTelemetryEnabled, onDidChangeTelemetryEnabled } from '@vscode/extension-telemetry';
// Check if telemetry is currently enabled
if (isTelemetryEnabled()) {
console.log('Telemetry is enabled.');
// Send telemetry data here
} else {
console.log('Telemetry is disabled.');
}
// Subscribe to changes in telemetry settings
const disposable = onDidChangeTelemetryEnabled(isEnabled => {
if (isEnabled) {
console.log('Telemetry enabled by user.');
// Enable telemetry sending
} else {
console.log('Telemetry disabled by user.');
// Disable telemetry sending
}
});
// Remember to dispose of the subscription when your extension is deactivated
// context.subscriptions.push(disposable);
```
--------------------------------
### Implement Language Model Tool in Extension Code
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/tools.md
This example demonstrates how to implement a language model tool in your VS Code extension's code using the Language Model API. It shows how to register the tool and handle its execution when called by the LLM.
```TypeScript
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const provider = vscode.lm.createChatProvider({
name: 'myTool',
description: 'A tool that does something useful.',
executeCommand: async (command, args) => {
if (command === 'myExtension.myToolCommand') {
const input = args[0].value;
// Implement your tool's logic here
return `Tool executed with input: ${input}`;
}
return 'Unknown command';
}
});
context.subscriptions.push(provider);
}
```
--------------------------------
### Check Extension Installation Status
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/when-clause-contexts.md
Determines if an extension is installed. This context key can be used to show UI elements only for installed extensions.
```JSON
{
"when": "extensionStatus == 'installed'"
}
```
--------------------------------
### VS Code Marketplace README File Example
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/publishing-extension.md
Illustrates the use of a README.md file in the root of an extension for its Visual Studio Marketplace page content. It also mentions how 'vsce' handles repository links and customizable flags for branch and base URLs.
```markdown
Add a `README.md` file to the root of your extension with the content you want to show on the extension's Marketplace page.
> [!NOTE]
> If you have a `repository` property in your `package.json` that points to a public GitHub repository, `vsce` will automatically detect it and adjust relative links accordingly, using the `main` branch by default. You can override this with the `--githubBranch` flag when running `vsce package` or `vsce publish`. You can also set base URLs for links and images with the `--baseContentUrl` and `--baseImagesUrl` flags.
```
--------------------------------
### MCP Server Development SDKs
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/mcp.md
VS Code supports MCP server development in various languages. The official SDKs provide the necessary tools and libraries to build your MCP server efficiently. Choose the SDK that best fits your project's requirements.
```TypeScript
https://github.com/modelcontextprotocol/typescript-sdk
```
```Python
https://github.com/modelcontextprotocol/python-sdk
```
```Java
https://github.com/modelcontextprotocol/java-sdk
```
```Kotlin
https://github.com/modelcontextprotocol/kotlin-sdk
```
```C#
https://github.com/modelcontextprotocol/csharp-sdk
```
--------------------------------
### Configure Azure Pipelines for VS Code Extension CI
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/continuous-integration.md
This YAML configuration sets up an Azure Pipeline to build and test a VS Code extension. It specifies triggers, defines build strategies for different operating systems (Linux, macOS, Windows), installs Node.js, starts Xvfb for headless Linux execution, and runs the extension tests using yarn.
```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'
```
--------------------------------
### Send Language Model Request with Error Handling
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/ai/language-model.md
This example shows how to send a request to a specific language model ('copilot' vendor, 'gpt-4o' family) and includes robust error handling. It catches potential `LanguageModelError` exceptions, logging specific details about the error, including the cause, and provides custom responses for certain error conditions like 'off_topic' requests.
```TypeScript
try {
const [model] = await vscode.lm.selectChatModels({ vendor: 'copilot', family: 'gpt-4o' });
const request = model.sendRequest(craftedPrompt, {}, token);
} catch (err) {
// Making the chat request might fail because
// - model does not exist
// - user consent not given
// - quota limits were exceeded
if (err instanceof vscode.LanguageModelError) {
console.log(err.message, err.code, err.cause);
if (err.cause instanceof Error && err.cause.message.includes('off_topic')) {
stream.markdown(vscode.l10n.t('I'm sorry, I can only explain computer science concepts.'));
}
} else {
// add other error handling logic
throw err;
}
}
```
--------------------------------
### TypeScript VS Code Extension Test Runner Setup
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/working-with-extensions/testing-extension.md
A TypeScript script using the `@vscode/test-electron` API to automate the process of downloading, unzipping, and launching VS Code for running extension tests. It configures the extension development path and the test runner script path.
```TypeScript
import * as path from 'path';
import { runTests } from '@vscode/test-electron';
async function main() {
try {
// The folder containing the Extension Manifest package.json
// Passed to `--extensionDevelopmentPath`
const extensionDevelopmentPath = path.resolve(__dirname, '../../');
// The path to the extension test runner script
// Passed to --extensionTestsPath
const extensionTestsPath = path.resolve(__dirname, './suite/index');
// Download VS Code, unzip it and run the integration test
await runTests({ extensionDevelopmentPath, extensionTestsPath });
} catch (err) {
console.error(err);
console.error('Failed to run tests');
process.exit(1);
}
}
main();
```
--------------------------------
### VS Code Active Bracket Pair Guide Colors
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/references/theme-color.md
Sets the background colors for active bracket pair guides, providing visual cues for matching bracket pairs. Supports up to six distinct color levels. Requires enabling bracket pair guides.
```JSON
{
"editorBracketPairGuide.activeBackground1": "#RRGGBB",
"editorBracketPairGuide.activeBackground2": "#RRGGBB",
"editorBracketPairGuide.activeBackground3": "#RRGGBB",
"editorBracketPairGuide.activeBackground4": "#RRGGBB",
"editorBracketPairGuide.activeBackground5": "#RRGGBB",
"editorBracketPairGuide.activeBackground6": "#RRGGBB"
}
```
--------------------------------
### VS Code Terminal Sample
Source: https://github.com/prudhvi-dev9/vscode-docs-api/blob/main/api/extension-guides/overview.md
Shows how to create and interact with terminals using the VS Code API. It covers creating new terminals with window.createTerminal, and listening for terminal events like activation, opening, and closing using window.onDidChangeActiveTerminal, window.onDidOpenTerminal, and window.onDidCloseTerminal.
```TypeScript
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
let disposable = vscode.commands.registerCommand('extension.createTerminal', () => {
const terminal = vscode.window.createTerminal('My Custom Terminal');
terminal.show();
terminal.sendText('echo Hello from VS Code!');
});
context.subscriptions.push(disposable);
vscode.window.onDidOpenTerminal((terminal) => {
console.log(`Terminal opened: ${terminal.name}`);
});
vscode.window.onDidChangeActiveTerminal((terminal) => {
if (terminal) {
console.log(`Active terminal changed to: ${terminal.name}`);
}
});
vscode.window.onDidCloseTerminal((terminal) => {
console.log(`Terminal closed: ${terminal.name}`);
});
}
```