Convert Figma logo to code with AI

microsoft logovscode-extension-samples

Sample code illustrating the VS Code extension API.

8,569
3,364
8,569
81

Top Related Projects

162,288

Visual Studio Code

19,861

Eclipse Theia is a cloud & desktop IDE framework implemented in TypeScript.

60,150

:atom: The hackable text editor

A browser based code editor

100,112

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

Defines a common protocol for language servers.

Quick Overview

The microsoft/vscode-extension-samples repository is a collection of sample extensions for Visual Studio Code. It provides developers with practical examples and templates to learn how to create various types of VS Code extensions, covering a wide range of functionalities and APIs.

Pros

  • Comprehensive collection of extension samples covering many VS Code APIs
  • Well-documented examples with clear explanations and comments
  • Regularly updated to reflect the latest VS Code extension capabilities
  • Serves as an excellent learning resource for both beginners and experienced developers

Cons

  • Some samples may become outdated as VS Code evolves rapidly
  • Not all possible extension types or use cases are covered
  • Requires basic knowledge of TypeScript and VS Code extension development
  • May not provide in-depth explanations for more complex extension concepts

Code Examples

Here are a few short code examples from different sample extensions:

  1. Registering a simple command (from helloworld-sample):
import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
        vscode.window.showInformationMessage('Hello World from VS Code!');
    });

    context.subscriptions.push(disposable);
}
  1. Creating a custom tree view (from tree-view-sample):
import * as vscode from 'vscode';

export class DepNodeProvider implements vscode.TreeDataProvider<Dependency> {
    getTreeItem(element: Dependency): vscode.TreeItem {
        return element;
    }

    getChildren(element?: Dependency): Thenable<Dependency[]> {
        if (!element) {
            return Promise.resolve(this.getDependencies());
        }
        return Promise.resolve([]);
    }

    private getDependencies(): Dependency[] {
        return [
            new Dependency('Dependency 1', vscode.TreeItemCollapsibleState.None),
            new Dependency('Dependency 2', vscode.TreeItemCollapsibleState.None)
        ];
    }
}
  1. Adding a custom editor (from custom-editor-sample):
import * as vscode from 'vscode';

export class CatCustomEditorProvider implements vscode.CustomTextEditorProvider {
    public static register(context: vscode.ExtensionContext): vscode.Disposable {
        const provider = new CatCustomEditorProvider(context);
        const providerRegistration = vscode.window.registerCustomEditorProvider(CatCustomEditorProvider.viewType, provider);
        return providerRegistration;
    }

    private static readonly viewType = 'catCustoms.catScratch';

    constructor(
        private readonly context: vscode.ExtensionContext
    ) { }

    public async resolveCustomTextEditor(
        document: vscode.TextDocument,
        webviewPanel: vscode.WebviewPanel,
        _token: vscode.CancellationToken
    ): Promise<void> {
        webviewPanel.webview.options = {
            enableScripts: true,
        };
        webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
    }

    private getHtmlForWebview(webview: vscode.Webview): string {
        // Implementation details omitted for brevity
    }
}

Getting Started

To get started with VS Code extension development using these samples:

  1. Clone the repository:

    git clone https://github.com/microsoft/vscode-extension-samples.git
    
  2. Choose a sample extension and navigate to its directory:

    cd vscode-extension-samples/helloworld-sample
    
  3. Install dependencies:

    npm install
    
  4. Open the sample in VS Code:

    code .
    
  5. Press F5 to run the extension in a new VS Code window.

  6. Explore the sample code and modify it to learn and experiment with VS Code extension development.

Competitor Comparisons

162,288

Visual Studio Code

Pros of vscode

  • Comprehensive codebase for the full VS Code editor
  • Extensive documentation and active community support
  • Regular updates and feature additions

Cons of vscode

  • Larger and more complex codebase, potentially harder to navigate
  • Steeper learning curve for contributors
  • May require more resources to run and test locally

Code comparison

vscode:

export class ExtensionContext implements vscode.ExtensionContext {
    readonly subscriptions: { dispose(): any }[] = [];
    readonly workspaceState: vscode.Memento;
    readonly globalState: vscode.Memento & { setKeysForSync(keys: string[]): void };
    readonly extensionPath: string;
    readonly extensionUri: vscode.Uri;
    readonly environmentVariableCollection: vscode.EnvironmentVariableCollection;

    constructor(private _extensionPath: string, private _extensionUri: vscode.Uri) {
        // ...
    }
}

vscode-extension-samples:

export function activate(context: vscode.ExtensionContext) {
    console.log('Congratulations, your extension "helloworld-sample" is now active!');

    let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
        vscode.window.showInformationMessage('Hello World!');
    });

    context.subscriptions.push(disposable);
}

The vscode repository contains the core implementation of the VS Code editor, while vscode-extension-samples provides simplified examples for extension development. The code snippets illustrate the difference in complexity and scope between the two projects.

19,861

Eclipse Theia is a cloud & desktop IDE framework implemented in TypeScript.

Pros of Theia

  • More comprehensive platform for building IDEs and tools
  • Supports both browser-based and desktop applications
  • Highly extensible and customizable architecture

Cons of Theia

  • Steeper learning curve due to its complexity
  • Requires more setup and configuration compared to VSCode extension samples
  • May be overkill for simple extensions or small projects

Code Comparison

Theia (TypeScript):

@injectable()
export class MyService {
    @inject(OtherService)
    protected readonly otherService: OtherService;

    doSomething(): void {
        // Implementation
    }
}

VSCode Extension Samples (JavaScript):

const vscode = require('vscode');

function activate(context) {
    let disposable = vscode.commands.registerCommand('extension.helloWorld', function () {
        vscode.window.showInformationMessage('Hello World!');
    });
    context.subscriptions.push(disposable);
}

The Theia example showcases its dependency injection system and TypeScript usage, while the VSCode Extension Samples demonstrate a simpler approach to registering commands using JavaScript. Theia's code structure reflects its more complex and flexible architecture, whereas VSCode Extension Samples focus on straightforward extension development.

60,150

:atom: The hackable text editor

Pros of Atom

  • Full-featured text editor with a rich ecosystem of packages
  • Open-source project with a large community of contributors
  • Highly customizable and hackable, allowing for deep modifications

Cons of Atom

  • Larger codebase and more complex architecture
  • Slower performance compared to VS Code extensions
  • Development has been discontinued by GitHub

Code Comparison

Atom (JavaScript):

atom.commands.add('atom-workspace', {
  'my-package:toggle': () => {
    console.log('My package was toggled!');
  }
});

vscode-extension-samples (TypeScript):

vscode.commands.registerCommand('extension.helloWorld', () => {
  vscode.window.showInformationMessage('Hello World!');
});

The code snippets demonstrate the different approaches to registering commands in Atom and VS Code extensions. Atom uses a more JavaScript-oriented syntax, while VS Code extensions typically use TypeScript and leverage the VS Code API.

While Atom provides a full-featured text editor, vscode-extension-samples focuses specifically on demonstrating how to create extensions for VS Code. The latter is more targeted and up-to-date, making it easier for developers to learn and implement VS Code extensions.

A browser based code editor

Pros of monaco-editor

  • Lightweight and versatile, can be embedded in various web applications
  • Provides a rich set of features for code editing without the full VSCode environment
  • Easier to integrate into existing web projects

Cons of monaco-editor

  • Limited to client-side functionality, lacks server-side capabilities
  • Fewer extension points and customization options compared to VSCode extensions
  • May require more setup and configuration for advanced features

Code Comparison

monaco-editor:

import * as monaco from 'monaco-editor';

monaco.editor.create(document.getElementById('container'), {
    value: 'function hello() {\n\tconsole.log("Hello world!");\n}',
    language: 'javascript'
});

vscode-extension-samples:

import * as vscode from 'vscode';

export function activate(context: vscode.ExtensionContext) {
    let disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
        vscode.window.showInformationMessage('Hello World!');
    });
    context.subscriptions.push(disposable);
}

The monaco-editor code demonstrates creating a simple editor instance, while the vscode-extension-samples code shows how to register a command in a VSCode extension. This highlights the different focus of each project: monaco-editor for embedding editors in web applications, and vscode-extension-samples for extending VSCode functionality.

100,112

TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

Pros of TypeScript

  • Larger community and more widespread adoption
  • More comprehensive documentation and resources
  • Broader scope, applicable to various JavaScript projects

Cons of TypeScript

  • Steeper learning curve for beginners
  • Larger codebase, potentially more complex to navigate
  • May require additional setup and configuration

Code Comparison

TypeScript:

interface Person {
  name: string;
  age: number;
}

function greet(person: Person) {
  return `Hello, ${person.name}!`;
}

vscode-extension-samples:

const vscode = require('vscode');

function activate(context) {
  console.log('Extension activated');
}

module.exports = { activate };

The TypeScript example showcases static typing and interfaces, while the vscode-extension-samples code demonstrates a basic VS Code extension structure.

TypeScript provides a more robust type system and language features, making it suitable for large-scale projects. vscode-extension-samples, on the other hand, focuses specifically on VS Code extension development, offering targeted examples and patterns for that purpose.

While TypeScript has broader applications, vscode-extension-samples excels in its niche, providing ready-to-use samples for VS Code extension developers. The choice between the two depends on the specific needs of the project and the developer's familiarity with VS Code extension development.

Defines a common protocol for language servers.

Pros of language-server-protocol

  • Provides a standardized protocol for language features across multiple editors and IDEs
  • Enables better separation of concerns between language-specific logic and editor integration
  • Supports a wider range of programming languages and tools

Cons of language-server-protocol

  • More complex to implement and maintain compared to simple VS Code extensions
  • Requires additional setup and configuration for both client and server components
  • May have higher resource usage due to the client-server architecture

Code Comparison

vscode-extension-samples:

vscode.languages.registerCompletionItemProvider('javascript', {
    provideCompletionItems(document, position, token, context) {
        return [new vscode.CompletionItem('Hello World')];
    }
});

language-server-protocol:

connection.onCompletion((textDocumentPosition, token) => {
    return [
        { label: 'Hello World', kind: CompletionItemKind.Text }
    ];
});

The vscode-extension-samples code is specific to VS Code, while the language-server-protocol code can be used with any LSP-compatible editor. The LSP approach provides a more standardized and flexible solution for implementing language features across different development environments.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

VS Code Extension Samples

This repository contains sample code illustrating the VS Code extension API. Each sample is a self-contained extension that explains one topic in VS Code API or VS Code's Contribution Points. You can read, play with or adapt from these samples to create your own extensions.

You can expect from each sample:

  • An explanation of its functionality
  • A gif or screenshot demonstrating its usage
  • Link to a guide on VS Code website, if it has one
  • Listing of used VS Code API and Contribution Points
  • Code of the same style, enforced using ESLint

Prerequisites

You need to have node and npm installed on your system to run the examples. It is recommended to use the node version used for VS Code development itself which is documented here

Usage

  • git clone https://github.com/Microsoft/vscode-extension-samples
  • code <any-sample-folder>
  • npm install in the terminal, then F5 to run the sample
  • Alternatively, follow the instructions in each sample's README for setting up and running the sample

Getting Started

Samples

SampleGuide on VS Code WebsiteAPI & Contribution
Webview Sample/api/extension-guides/webviewwindow.createWebviewPanel
window.registerWebviewPanelSerializer
Webview View SampleN/Awindow.registerWebviewViewProvider
Webview Codicons SampleN/A
Status Bar SampleN/Awindow.createStatusBarItem
StatusBarItem
Tree View Sample/api/extension-guides/tree-viewwindow.createTreeView
window.registerTreeDataProvider
TreeView
TreeDataProvider
contributes.views
contributes.viewsContainers
Task Provider Sample/api/extension-guides/task-providertasks.registerTaskProvider
Task
ShellExecution
contributes.taskDefinitions
Multi Root SampleN/Aworkspace.getWorkspaceFolder
workspace.onDidChangeWorkspaceFolders
Completion Provider SampleN/Alanguages.registerCompletionItemProvider
CompletionItem
SnippetString
Code Actions SampleN/Alanguages.registerCodeActionsProvider
CodeActionProvider
File System Provider SampleN/Aworkspace.registerFileSystemProvider
Editor Decorator SampleN/ATextEditor.setDecorations
DecorationOptions
DecorationInstanceRenderOptions
ThemableDecorationInstanceRenderOptions
window.createTextEditorDecorationType
TextEditorDecorationType
contributes.colors
L10n SampleN/A
Terminal SampleN/Awindow.createTerminal
window.onDidChangeActiveTerminal
window.onDidCloseTerminal
window.onDidOpenTerminal
window.Terminal
window.terminals
Extension Terminal SampleN/Awindow.createTerminal
window.Pseudoterminal
window.ExtensionTerminalOptions
Color Theme Sample/api/extension-guides/color-themecontributes.themes
Product Icon Theme Sample/api/extension-guides/product-icon-themecontributes.productIconThemes
Vim SampleN/Acommands
StatusBarItem
window.createStatusBarItem
TextEditorCursorStyle
window.activeTextEditor
Position
Range
Selection
TextEditor
TextEditorRevealType
TextDocument
webpack-sample/api/working-with-extensions/bundling-extension
esbuild-sample/api/working-with-extensions/bundling-extension
Source Control Sample/api/extension-guides/scm-providerworkspace.workspaceFolders
SourceControl
SourceControlResourceGroup
scm.createSourceControl
TextDocumentContentProvider
contributes.menus
Commenting API SampleN/A
Document Editing SampleN/Acommands
Custom Data Sample/api/extension-guides/custom-data-extension
CodeLens Provider SampleN/Alanguages.registerCodeLensProvider
CodeLensProvider
CodeLens
Call Hierarchy SampleN/Alanguages.registerCallHierarchyProvider
CallHierarchyProvider
CallHierarchyItem
CallHierarchyOutgoingCall
CallHierarchyIncomingCall
Custom Editors Sample/api/extension-guides/custom-editorswindow.registerCustomEditorProvider
CustomTextEditorProvider
contributes.customEditors
Semantic tokens/api/language-extensions/semantic-highlight-guidelanguages.registerDocumentSemanticTokensProvider
vscode.DocumentSemanticTokensProvider
Test Provider SampleN/A
Getting Started SampleN/A
notebook-renderer-sample/api/extension-guides/notebook#notebook-renderercontributes.notebookRenderer
notebook-extend-markdown-renderer-sample/api/extension-guides/notebook#notebook-renderercontributes.notebookRenderer
jupyter-server-provider-sampleN/A
Chat SampleN/A
Notifications SampleN/A

Language Server Protocol Samples

SampleGuide on VS Code WebsiteAPI & Contribution
Snippet Sample/api/language-extensions/snippet-guidecontributes.snippets
Language Configuration Sample/api/language-extensions/language-configuration-guidecontributes.languages
LSP Sample/api/language-extensions/language-server-extension-guide
LSP Log Streaming SampleN/A
LSP Multi Root Server Samplehttps://github.com/Microsoft/vscode/wiki/Extension-Authoring:-Adopting-Multi-Root-Workspace-APIs#language-client--language-server
LSP Web Extension Sample/api/language-extensions/language-server-extension-guide
LSP User Input SampleN/A

License

Copyright (c) Microsoft Corporation. All rights reserved.

Licensed under the MIT License.