Merge branch 'main' into lramos15/telemetry-sample

This commit is contained in:
Logan Ramos
2023-03-30 12:55:16 -07:00
committed by GitHub
321 changed files with 44523 additions and 61745 deletions

View File

@ -11,14 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.helloWorld"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -31,15 +29,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.74.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

3
.editorconfig Normal file
View File

@ -0,0 +1,3 @@
[*.{ts,tsx,js,jsx,json}]
indent_style = tab
tab_width = 4

View File

@ -1,25 +0,0 @@
name: PR Chat
on:
pull_request_target:
types: [opened, ready_for_review, closed]
jobs:
main:
runs-on: ubuntu-latest
if: ${{ !github.event.pull_request.draft }}
steps:
- name: Checkout Actions
uses: actions/checkout@v2
with:
repository: "microsoft/vscode-github-triage-actions"
ref: stable
path: ./actions
- name: Install Actions
run: npm install --production --prefix ./actions
- name: Run Code Review Chat
uses: ./actions/code-review-chat
with:
token: ${{secrets.GITHUB_TOKEN}}
slack_token: ${{ secrets.SLACK_TOKEN }}
slack_bot_name: "VSCodeBot"
notification_channel: codereview

View File

@ -8,14 +8,14 @@ const child_process = require('child_process');
const { samples, lspSamples } = require('./samples');
async function tryRunInstall(
/** @type {string} */command,
/** @type {string} */ command,
/** @type {import('./samples').Sample} */ sample,
) {
const packageJsonPath = path.join(sample.path, 'package.json');
if (fs.existsSync(packageJsonPath)) {
const packageJson = JSON.parse(fs.readFileSync(packageJsonPath).toString());
if (packageJson['devDependencies'] || packageJson['dependencies']) {
console.log(`=== Running install on ${path.basename(sample.path)} ===`);
console.log(`=== Running ${command} on ${path.basename(sample.path)} ===`);
child_process.execSync(command, {
cwd: sample.path,
stdio: 'inherit'

View File

@ -97,8 +97,8 @@ const samples = [
contributions: ['colors']
},
{
description: 'I18n Sample',
path: 'i18n-sample',
description: 'L10n Sample',
path: 'l10n-sample',
guide: null,
apis: [],
contributions: []

View File

@ -45,7 +45,7 @@ You need to have [node](https://nodejs.org/en/) and [npm](https://nodejs.org/en/
| [Code Actions Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/code-actions-sample) | N/A | [languages.registerCodeActionsProvider](https://code.visualstudio.com/api/references/vscode-api#languages.registerCodeActionsProvider)<br>[CodeActionProvider](https://code.visualstudio.com/api/references/vscode-api#CodeActionProvider) |
| [File System Provider Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/fsprovider-sample) | N/A | [workspace.registerFileSystemProvider](https://code.visualstudio.com/api/references/vscode-api#workspace.registerFileSystemProvider) |
| [Editor Decorator Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/decorator-sample) | N/A | [TextEditor.setDecorations](https://code.visualstudio.com/api/references/vscode-api#TextEditor.setDecorations)<br>[DecorationOptions](https://code.visualstudio.com/api/references/vscode-api#DecorationOptions)<br>[DecorationInstanceRenderOptions](https://code.visualstudio.com/api/references/vscode-api#DecorationInstanceRenderOptions)<br>[ThemableDecorationInstanceRenderOptions](https://code.visualstudio.com/api/references/vscode-api#ThemableDecorationInstanceRenderOptions)<br>[window.createTextEditorDecorationType](https://code.visualstudio.com/api/references/vscode-api#window.createTextEditorDecorationType)<br>[TextEditorDecorationType](https://code.visualstudio.com/api/references/vscode-api#TextEditorDecorationType)<br>[contributes.colors](https://code.visualstudio.com/api/references/contribution-points#contributes.colors) |
| [I18n Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/i18n-sample) | N/A | |
| [L10n Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/l10n-sample) | N/A | |
| [Terminal Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/terminal-sample) | N/A | [window.createTerminal](https://code.visualstudio.com/api/references/vscode-api#window.createTerminal)<br>[window.onDidChangeActiveTerminal](https://code.visualstudio.com/api/references/vscode-api#window.onDidChangeActiveTerminal)<br>[window.onDidCloseTerminal](https://code.visualstudio.com/api/references/vscode-api#window.onDidCloseTerminal)<br>[window.onDidOpenTerminal](https://code.visualstudio.com/api/references/vscode-api#window.onDidOpenTerminal)<br>[window.Terminal](https://code.visualstudio.com/api/references/vscode-api#window.Terminal)<br>[window.terminals](https://code.visualstudio.com/api/references/vscode-api#window.terminals) |
| [Extension Terminal Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/extension-terminal-sample) | N/A | [window.createTerminal](https://code.visualstudio.com/api/references/vscode-api#window.createTerminal)<br>[window.Pseudoterminal](https://code.visualstudio.com/api/references/vscode-api#window.Pseudoterminal)<br>[window.ExtensionTerminalOptions](https://code.visualstudio.com/api/references/vscode-api#window.ExtensionTerminalOptions) |
| [Color Theme Sample](https://github.com/Microsoft/vscode-extension-samples/tree/main/theme-sample) | [/api/extension-guides/color-theme](https://code.visualstudio.com/api/extension-guides/color-theme) | [contributes.themes](https://code.visualstudio.com/api/references/contribution-points#contributes.themes) |

File diff suppressed because it is too large Load Diff

View File

@ -4,15 +4,12 @@
"description": "AuthenticationProvider API Sample",
"version": "0.0.1",
"engines": {
"vscode": "^1.60.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:vscode-authenticationprovider-sample.login",
"onAuthenticationRequest:AzureDevOpsPAT"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -41,11 +38,11 @@
"@types/isomorphic-fetch": "^0.0.35",
"@types/node": "^16.11.7",
"@types/vscode": "^1.60.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"glob": "^7.1.7",
"typescript": "^4.8.4",
"typescript": "^5.0.2",
"vscode-test": "^1.5.2"
},
"dependencies": {

View File

@ -1,137 +1,137 @@
import {
authentication,
AuthenticationProvider,
AuthenticationProviderAuthenticationSessionsChangeEvent,
AuthenticationSession,
Disposable,
Event,
EventEmitter,
SecretStorage,
window,
} from 'vscode';
class AzureDevOpsPatSession implements AuthenticationSession {
// We don't know the user's account name, so we'll just use a constant
readonly account = { id: AzureDevOpsAuthenticationProvider.id, label: 'Personal Access Token' };
// This id isn't used for anything in this example, so we set it to a constant
readonly id = AzureDevOpsAuthenticationProvider.id;
// We don't know what scopes the PAT has, so we have an empty array here.
readonly scopes = [];
/**
*
* @param accessToken The personal access token to use for authentication
*/
constructor(public readonly accessToken: string) {}
}
export class AzureDevOpsAuthenticationProvider implements AuthenticationProvider, Disposable {
static id = 'AzureDevOpsPAT';
private static secretKey = 'AzureDevOpsPAT';
// this property is used to determine if the token has been changed in another window of VS Code.
// It is used in the checkForUpdates function.
private currentToken: Promise<string | undefined> | undefined;
private initializedDisposable: Disposable | undefined;
private _onDidChangeSessions = new EventEmitter<AuthenticationProviderAuthenticationSessionsChangeEvent>();
get onDidChangeSessions(): Event<AuthenticationProviderAuthenticationSessionsChangeEvent> {
return this._onDidChangeSessions.event;
}
constructor(private readonly secretStorage: SecretStorage) { }
dispose(): void {
this.initializedDisposable?.dispose();
}
private ensureInitialized(): void {
if (this.initializedDisposable === undefined) {
void this.cacheTokenFromStorage();
this.initializedDisposable = Disposable.from(
// This onDidChange event happens when the secret storage changes in _any window_ since
// secrets are shared across all open windows.
this.secretStorage.onDidChange(e => {
if (e.key === AzureDevOpsAuthenticationProvider.secretKey) {
void this.checkForUpdates();
}
}),
// This fires when the user initiates a "silent" auth flow via the Accounts menu.
authentication.onDidChangeSessions(e => {
if (e.provider.id === AzureDevOpsAuthenticationProvider.id) {
void this.checkForUpdates();
}
}),
);
}
}
// This is a crucial function that handles whether or not the token has changed in
// a different window of VS Code and sends the necessary event if it has.
private async checkForUpdates(): Promise<void> {
const added: AuthenticationSession[] = [];
const removed: AuthenticationSession[] = [];
const changed: AuthenticationSession[] = [];
const previousToken = await this.currentToken;
const session = (await this.getSessions())[0];
if (session?.accessToken && !previousToken) {
added.push(session);
} else if (!session?.accessToken && previousToken) {
removed.push(session);
} else if (session?.accessToken !== previousToken) {
changed.push(session);
} else {
return;
}
void this.cacheTokenFromStorage();
this._onDidChangeSessions.fire({ added: added, removed: removed, changed: changed });
}
private cacheTokenFromStorage() {
this.currentToken = this.secretStorage.get(AzureDevOpsAuthenticationProvider.secretKey) as Promise<string | undefined>;
return this.currentToken;
}
// This function is called first when `vscode.authentication.getSessions` is called.
async getSessions(_scopes?: string[]): Promise<readonly AuthenticationSession[]> {
this.ensureInitialized();
const token = await this.cacheTokenFromStorage();
return token ? [new AzureDevOpsPatSession(token)] : [];
}
// This function is called after `this.getSessions` is called and only when:
// - `this.getSessions` returns nothing but `createIfNone` was set to `true` in `vscode.authentication.getSessions`
// - `vscode.authentication.getSessions` was called with `forceNewSession: true`
// - The end user initiates the "silent" auth flow via the Accounts menu
async createSession(_scopes: string[]): Promise<AuthenticationSession> {
this.ensureInitialized();
// Prompt for the PAT.
const token = await window.showInputBox({
ignoreFocusOut: true,
placeHolder: 'Personal access token',
prompt: 'Enter an Azure DevOps Personal Access Token (PAT).',
password: true,
});
// Note: this example doesn't do any validation of the token beyond making sure it's not empty.
if (!token) {
throw new Error('PAT is required');
}
// Don't set `currentToken` here, since we want to fire the proper events in the `checkForUpdates` call
await this.secretStorage.store(AzureDevOpsAuthenticationProvider.secretKey, token);
console.log('Successfully logged in to Azure DevOps');
return new AzureDevOpsPatSession(token);
}
// This function is called when the end user signs out of the account.
async removeSession(_sessionId: string): Promise<void> {
await this.secretStorage.delete(AzureDevOpsAuthenticationProvider.secretKey);
}
}
import {
authentication,
AuthenticationProvider,
AuthenticationProviderAuthenticationSessionsChangeEvent,
AuthenticationSession,
Disposable,
Event,
EventEmitter,
SecretStorage,
window,
} from 'vscode';
class AzureDevOpsPatSession implements AuthenticationSession {
// We don't know the user's account name, so we'll just use a constant
readonly account = { id: AzureDevOpsAuthenticationProvider.id, label: 'Personal Access Token' };
// This id isn't used for anything in this example, so we set it to a constant
readonly id = AzureDevOpsAuthenticationProvider.id;
// We don't know what scopes the PAT has, so we have an empty array here.
readonly scopes = [];
/**
*
* @param accessToken The personal access token to use for authentication
*/
constructor(public readonly accessToken: string) { }
}
export class AzureDevOpsAuthenticationProvider implements AuthenticationProvider, Disposable {
static id = 'AzureDevOpsPAT';
private static secretKey = 'AzureDevOpsPAT';
// this property is used to determine if the token has been changed in another window of VS Code.
// It is used in the checkForUpdates function.
private currentToken: Promise<string | undefined> | undefined;
private initializedDisposable: Disposable | undefined;
private _onDidChangeSessions = new EventEmitter<AuthenticationProviderAuthenticationSessionsChangeEvent>();
get onDidChangeSessions(): Event<AuthenticationProviderAuthenticationSessionsChangeEvent> {
return this._onDidChangeSessions.event;
}
constructor(private readonly secretStorage: SecretStorage) { }
dispose(): void {
this.initializedDisposable?.dispose();
}
private ensureInitialized(): void {
if (this.initializedDisposable === undefined) {
void this.cacheTokenFromStorage();
this.initializedDisposable = Disposable.from(
// This onDidChange event happens when the secret storage changes in _any window_ since
// secrets are shared across all open windows.
this.secretStorage.onDidChange(e => {
if (e.key === AzureDevOpsAuthenticationProvider.secretKey) {
void this.checkForUpdates();
}
}),
// This fires when the user initiates a "silent" auth flow via the Accounts menu.
authentication.onDidChangeSessions(e => {
if (e.provider.id === AzureDevOpsAuthenticationProvider.id) {
void this.checkForUpdates();
}
}),
);
}
}
// This is a crucial function that handles whether or not the token has changed in
// a different window of VS Code and sends the necessary event if it has.
private async checkForUpdates(): Promise<void> {
const added: AuthenticationSession[] = [];
const removed: AuthenticationSession[] = [];
const changed: AuthenticationSession[] = [];
const previousToken = await this.currentToken;
const session = (await this.getSessions())[0];
if (session?.accessToken && !previousToken) {
added.push(session);
} else if (!session?.accessToken && previousToken) {
removed.push(session);
} else if (session?.accessToken !== previousToken) {
changed.push(session);
} else {
return;
}
void this.cacheTokenFromStorage();
this._onDidChangeSessions.fire({ added: added, removed: removed, changed: changed });
}
private cacheTokenFromStorage() {
this.currentToken = this.secretStorage.get(AzureDevOpsAuthenticationProvider.secretKey) as Promise<string | undefined>;
return this.currentToken;
}
// This function is called first when `vscode.authentication.getSessions` is called.
async getSessions(_scopes?: string[]): Promise<readonly AuthenticationSession[]> {
this.ensureInitialized();
const token = await this.cacheTokenFromStorage();
return token ? [new AzureDevOpsPatSession(token)] : [];
}
// This function is called after `this.getSessions` is called and only when:
// - `this.getSessions` returns nothing but `createIfNone` was set to `true` in `vscode.authentication.getSessions`
// - `vscode.authentication.getSessions` was called with `forceNewSession: true`
// - The end user initiates the "silent" auth flow via the Accounts menu
async createSession(_scopes: string[]): Promise<AuthenticationSession> {
this.ensureInitialized();
// Prompt for the PAT.
const token = await window.showInputBox({
ignoreFocusOut: true,
placeHolder: 'Personal access token',
prompt: 'Enter an Azure DevOps Personal Access Token (PAT).',
password: true,
});
// Note: this example doesn't do any validation of the token beyond making sure it's not empty.
if (!token) {
throw new Error('PAT is required');
}
// Don't set `currentToken` here, since we want to fire the proper events in the `checkForUpdates` call
await this.secretStorage.store(AzureDevOpsAuthenticationProvider.secretKey, token);
console.log('Successfully logged in to Azure DevOps');
return new AzureDevOpsPatSession(token);
}
// This function is called when the end user signs out of the account.
async removeSession(_sessionId: string): Promise<void> {
await this.secretStorage.delete(AzureDevOpsAuthenticationProvider.secretKey);
}
}

View File

@ -1,53 +1,51 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import 'isomorphic-fetch';
import * as vscode from 'vscode';
import { AzureDevOpsAuthenticationProvider } from './authProvider';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
console.log('Congratulations, your extension "vscode-authenticationprovider-sample" is now active!');
// Register our authentication provider. NOTE: this will register the provider globally which means that
// any other extension can use this provider via the `getSession` API.
// NOTE: when implementing an auth provider, don't forget to register an activation event for that provider
// in your package.json file: "onAuthenticationRequest:AzureDevOpsPAT"
context.subscriptions.push(vscode.authentication.registerAuthenticationProvider(
AzureDevOpsAuthenticationProvider.id,
'Azure Repos',
new AzureDevOpsAuthenticationProvider(context.secrets),
));
let disposable = vscode.commands.registerCommand('vscode-authenticationprovider-sample.login', async () => {
// Get our PAT session.
const session = await vscode.authentication.getSession(AzureDevOpsAuthenticationProvider.id, [], { createIfNone: true });
try {
// Make a request to the Azure DevOps API. Keep in mind that this particular API only works with PAT's with
// 'all organizations' access.
const req = await fetch('https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=6.0', {
headers: {
authorization: `Basic ${Buffer.from(`:${session.accessToken}`).toString('base64')}`,
'content-type': 'application/json',
},
});
if (!req.ok) {
throw new Error(req.statusText);
}
const res = await req.json() as { displayName: string };
vscode.window.showInformationMessage(`Hello ${res.displayName}`);
} catch (e: any) {
if (e.message === 'Unauthorized') {
vscode.window.showErrorMessage('Failed to get profile. You need to use a PAT that has access to all organizations. Please sign out and try again.');
}
throw e;
}
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {}
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import 'isomorphic-fetch';
import * as vscode from 'vscode';
import { AzureDevOpsAuthenticationProvider } from './authProvider';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
console.log('Congratulations, your extension "vscode-authenticationprovider-sample" is now active!');
// Register our authentication provider. NOTE: this will register the provider globally which means that
// any other extension can use this provider via the `getSession` API.
// NOTE: when implementing an auth provider, don't forget to register an activation event for that provider
// in your package.json file: "onAuthenticationRequest:AzureDevOpsPAT"
context.subscriptions.push(vscode.authentication.registerAuthenticationProvider(
AzureDevOpsAuthenticationProvider.id,
'Azure Repos',
new AzureDevOpsAuthenticationProvider(context.secrets),
));
let disposable = vscode.commands.registerCommand('vscode-authenticationprovider-sample.login', async () => {
// Get our PAT session.
const session = await vscode.authentication.getSession(AzureDevOpsAuthenticationProvider.id, [], { createIfNone: true });
try {
// Make a request to the Azure DevOps API. Keep in mind that this particular API only works with PAT's with
// 'all organizations' access.
const req = await fetch('https://app.vssps.visualstudio.com/_apis/profile/profiles/me?api-version=6.0', {
headers: {
authorization: `Basic ${Buffer.from(`:${session.accessToken}`).toString('base64')}`,
// eslint-disable-next-line @typescript-eslint/naming-convention
'content-type': 'application/json',
},
});
if (!req.ok) {
throw new Error(req.statusText);
}
const res = await req.json() as { displayName: string };
vscode.window.showInformationMessage(`Hello ${res.displayName}`);
} catch (e: any) {
if (e.message === 'Unauthorized') {
vscode.window.showErrorMessage('Failed to get profile. You need to use a PAT that has access to all organizations. Please sign out and try again.');
}
throw e;
}
});
context.subscriptions.push(disposable);
}

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -23,7 +23,7 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"contributes": {
@ -44,10 +44,10 @@
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,72 +1,72 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { ExtensionContext, StatusBarAlignment, window, StatusBarItem, Selection, workspace, TextEditor, commands } from 'vscode';
import { basename } from 'path';
export function activate(context: ExtensionContext) {
// Create a status bar item
const status = window.createStatusBarItem(StatusBarAlignment.Left, 1000000);
context.subscriptions.push(status);
// Update status bar item based on events for multi root folder changes
context.subscriptions.push(workspace.onDidChangeWorkspaceFolders(e => updateStatus(status)));
// Update status bar item based on events for configuration
context.subscriptions.push(workspace.onDidChangeConfiguration(e => updateStatus(status)));
// Update status bar item based on events around the active editor
context.subscriptions.push(window.onDidChangeActiveTextEditor(e => updateStatus(status)));
context.subscriptions.push(window.onDidChangeTextEditorViewColumn(e => updateStatus(status)));
context.subscriptions.push(workspace.onDidOpenTextDocument(e => updateStatus(status)));
context.subscriptions.push(workspace.onDidCloseTextDocument(e => updateStatus(status)));
updateStatus(status);
}
function updateStatus(status: StatusBarItem): void {
const info = getEditorInfo();
status.text = info ? info.text || '' : '';
status.tooltip = info ? info.tooltip : undefined;
status.color = info ? info.color : undefined;
if (info) {
status.show();
} else {
status.hide();
}
}
function getEditorInfo(): { text?: string; tooltip?: string; color?: string; } | null {
const editor = window.activeTextEditor;
// If no workspace is opened or just a single folder, we return without any status label
// because our extension only works when more than one folder is opened in a workspace.
if (!editor || !workspace.workspaceFolders || workspace.workspaceFolders.length < 2) {
return null;
}
let text: string | undefined;
let tooltip: string | undefined;
let color: string | undefined;
// If we have a file:// resource we resolve the WorkspaceFolder this file is from and update
// the status accordingly.
const resource = editor.document.uri;
if (resource.scheme === 'file') {
const folder = workspace.getWorkspaceFolder(resource);
if (!folder) {
text = `$(alert) <outside workspace> → ${basename(resource.fsPath)}`;
} else {
text = `$(file-submodule) ${basename(folder.uri.fsPath)} (${folder.index + 1} of ${workspace.workspaceFolders.length}) → $(file-code) ${basename(resource.fsPath)}`;
tooltip = resource.fsPath;
const multiRootConfigForResource = workspace.getConfiguration('multiRootSample', resource);
color = multiRootConfigForResource.get('statusColor');
}
}
return { text, tooltip, color };
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { ExtensionContext, StatusBarAlignment, window, StatusBarItem, Selection, workspace, TextEditor, commands } from 'vscode';
import { basename } from 'path';
export function activate(context: ExtensionContext) {
// Create a status bar item
const status = window.createStatusBarItem(StatusBarAlignment.Left, 1000000);
context.subscriptions.push(status);
// Update status bar item based on events for multi root folder changes
context.subscriptions.push(workspace.onDidChangeWorkspaceFolders(e => updateStatus(status)));
// Update status bar item based on events for configuration
context.subscriptions.push(workspace.onDidChangeConfiguration(e => updateStatus(status)));
// Update status bar item based on events around the active editor
context.subscriptions.push(window.onDidChangeActiveTextEditor(e => updateStatus(status)));
context.subscriptions.push(window.onDidChangeTextEditorViewColumn(e => updateStatus(status)));
context.subscriptions.push(workspace.onDidOpenTextDocument(e => updateStatus(status)));
context.subscriptions.push(workspace.onDidCloseTextDocument(e => updateStatus(status)));
updateStatus(status);
}
function updateStatus(status: StatusBarItem): void {
const info = getEditorInfo();
status.text = info ? info.text || '' : '';
status.tooltip = info ? info.tooltip : undefined;
status.color = info ? info.color : undefined;
if (info) {
status.show();
} else {
status.hide();
}
}
function getEditorInfo(): { text?: string; tooltip?: string; color?: string; } | null {
const editor = window.activeTextEditor;
// If no workspace is opened or just a single folder, we return without any status label
// because our extension only works when more than one folder is opened in a workspace.
if (!editor || !workspace.workspaceFolders || workspace.workspaceFolders.length < 2) {
return null;
}
let text: string | undefined;
let tooltip: string | undefined;
let color: string | undefined;
// If we have a file:// resource we resolve the WorkspaceFolder this file is from and update
// the status accordingly.
const resource = editor.document.uri;
if (resource.scheme === 'file') {
const folder = workspace.getWorkspaceFolder(resource);
if (!folder) {
text = `$(alert) <outside workspace> → ${basename(resource.fsPath)}`;
} else {
text = `$(file-submodule) ${basename(folder.uri.fsPath)} (${folder.index + 1} of ${workspace.workspaceFolders.length}) → $(file-code) ${basename(resource.fsPath)}`;
tooltip = resource.fsPath;
const multiRootConfigForResource = workspace.getConfiguration('multiRootSample', resource);
color = multiRootConfigForResource.get('statusColor');
}
}
return { text, tooltip, color };
}

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.40.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -23,15 +23,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.40.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,125 +1,125 @@
import * as vscode from 'vscode';
import { FoodPyramid, FoodRelation } from './model';
export class FoodPyramidHierarchyProvider implements vscode.CallHierarchyProvider {
prepareCallHierarchy(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.CallHierarchyItem | undefined {
const range = document.getWordRangeAtPosition(position);
if (range) {
const word = document.getText(range);
return this.createCallHierarchyItem(word, '', document, range);
} else {
return undefined;
}
}
async provideCallHierarchyOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyOutgoingCall[] | undefined> {
const document = await vscode.workspace.openTextDocument(item.uri);
const parser = new FoodPyramidParser();
parser.parse(document);
const model = parser.getModel();
const originRelation = model.getRelationAt(item.range);
const outgoingCallItems: vscode.CallHierarchyOutgoingCall[] = [];
if (model.isVerb(item.name)) {
const outgoingCalls = model.getVerbRelations(item.name)
.filter(relation => relation.subject === originRelation!.subject);
outgoingCalls.forEach(relation => {
const outgoingCallRange = relation.getRangeOf(relation.object);
const verbItem = this.createCallHierarchyItem(relation.object, 'noun', document, outgoingCallRange);
const outgoingCallItem = new vscode.CallHierarchyOutgoingCall(verbItem, [outgoingCallRange]);
outgoingCallItems.push(outgoingCallItem);
});
}
else if (model.isNoun(item.name)) {
const outgoingCallMap = groupBy(model.getSubjectRelations(item.name), relation => relation.verb);
outgoingCallMap.forEach((relations, verb) => {
const outgoingCallRanges = relations.map(relation => relation.getRangeOf(verb));
const verbItem = this.createCallHierarchyItem(verb, 'verb', document, outgoingCallRanges[0]);
const outgoingCallItem = new vscode.CallHierarchyOutgoingCall(verbItem, outgoingCallRanges);
outgoingCallItems.push(outgoingCallItem);
});
}
return outgoingCallItems;
}
async provideCallHierarchyIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyIncomingCall[]> {
const document = await vscode.workspace.openTextDocument(item.uri);
const parser = new FoodPyramidParser();
parser.parse(document);
const model = parser.getModel();
const originRelation = model.getRelationAt(item.range);
const outgoingCallItems: vscode.CallHierarchyIncomingCall[] = [];
if (model.isVerb(item.name)) {
const outgoingCalls = model.getVerbRelations(item.name)
.filter(relation => relation.object === originRelation!.object);
outgoingCalls.forEach(relation => {
const outgoingCallRange = relation.getRangeOf(relation.subject);
const verbItem = this.createCallHierarchyItem(relation.subject, 'noun', document, outgoingCallRange);
const outgoingCallItem = new vscode.CallHierarchyIncomingCall(verbItem, [outgoingCallRange]);
outgoingCallItems.push(outgoingCallItem);
});
}
else if (model.isNoun(item.name)) {
const outgoingCallMap = groupBy(model.getObjectRelations(item.name), relation => relation.verb);
outgoingCallMap.forEach((relations, verb) => {
const outgoingCallRanges = relations.map(relation => relation.getRangeOf(verb));
const verbItem = this.createCallHierarchyItem(verb, 'verb-inverted', document, outgoingCallRanges[0]);
const outgoingCallItem = new vscode.CallHierarchyIncomingCall(verbItem, outgoingCallRanges);
outgoingCallItems.push(outgoingCallItem);
});
}
return outgoingCallItems;
}
private createCallHierarchyItem(word: string, type: string, document: vscode.TextDocument, range: vscode.Range): vscode.CallHierarchyItem {
return new vscode.CallHierarchyItem(vscode.SymbolKind.Object, word, `(${type})`, document.uri, range, range);
}
}
/**
* Sample parser of the document text into the [FoodPyramid](#FoodPyramid) model.
*/
class FoodPyramidParser {
private _model = new FoodPyramid();
getModel(): FoodPyramid {
return this._model;
}
parse(textDocument: vscode.TextDocument): void {
const pattern = /^(\w+)\s+(\w+)\s+(\w+).$/gm;
let match: RegExpExecArray | null;
while ((match = pattern.exec(textDocument.getText()))) {
const startPosition = textDocument.positionAt(match.index);
const range = new vscode.Range(startPosition, startPosition.translate({ characterDelta: match[0].length }));
this._model.addRelation(new FoodRelation(match[1], match[2], match[3], match[0], range));
}
}
}
/**
* Groups array items by a field defined using a key selector.
* @param array array to be grouped
* @param keyGetter grouping key selector
*/
function groupBy<K, V>(array: Array<V>, keyGetter: (value: V) => K): Map<K, V[]> {
const map = new Map();
array.forEach((item) => {
const key = keyGetter(item);
const groupForKey = map.get(key) || [];
groupForKey.push(item);
map.set(key, groupForKey);
});
return map;
}
import * as vscode from 'vscode';
import { FoodPyramid, FoodRelation } from './model';
export class FoodPyramidHierarchyProvider implements vscode.CallHierarchyProvider {
prepareCallHierarchy(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken): vscode.CallHierarchyItem | undefined {
const range = document.getWordRangeAtPosition(position);
if (range) {
const word = document.getText(range);
return this.createCallHierarchyItem(word, '', document, range);
} else {
return undefined;
}
}
async provideCallHierarchyOutgoingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyOutgoingCall[] | undefined> {
const document = await vscode.workspace.openTextDocument(item.uri);
const parser = new FoodPyramidParser();
parser.parse(document);
const model = parser.getModel();
const originRelation = model.getRelationAt(item.range);
const outgoingCallItems: vscode.CallHierarchyOutgoingCall[] = [];
if (model.isVerb(item.name)) {
const outgoingCalls = model.getVerbRelations(item.name)
.filter(relation => relation.subject === originRelation!.subject);
outgoingCalls.forEach(relation => {
const outgoingCallRange = relation.getRangeOf(relation.object);
const verbItem = this.createCallHierarchyItem(relation.object, 'noun', document, outgoingCallRange);
const outgoingCallItem = new vscode.CallHierarchyOutgoingCall(verbItem, [outgoingCallRange]);
outgoingCallItems.push(outgoingCallItem);
});
}
else if (model.isNoun(item.name)) {
const outgoingCallMap = groupBy(model.getSubjectRelations(item.name), relation => relation.verb);
outgoingCallMap.forEach((relations, verb) => {
const outgoingCallRanges = relations.map(relation => relation.getRangeOf(verb));
const verbItem = this.createCallHierarchyItem(verb, 'verb', document, outgoingCallRanges[0]);
const outgoingCallItem = new vscode.CallHierarchyOutgoingCall(verbItem, outgoingCallRanges);
outgoingCallItems.push(outgoingCallItem);
});
}
return outgoingCallItems;
}
async provideCallHierarchyIncomingCalls(item: vscode.CallHierarchyItem, token: vscode.CancellationToken): Promise<vscode.CallHierarchyIncomingCall[]> {
const document = await vscode.workspace.openTextDocument(item.uri);
const parser = new FoodPyramidParser();
parser.parse(document);
const model = parser.getModel();
const originRelation = model.getRelationAt(item.range);
const outgoingCallItems: vscode.CallHierarchyIncomingCall[] = [];
if (model.isVerb(item.name)) {
const outgoingCalls = model.getVerbRelations(item.name)
.filter(relation => relation.object === originRelation!.object);
outgoingCalls.forEach(relation => {
const outgoingCallRange = relation.getRangeOf(relation.subject);
const verbItem = this.createCallHierarchyItem(relation.subject, 'noun', document, outgoingCallRange);
const outgoingCallItem = new vscode.CallHierarchyIncomingCall(verbItem, [outgoingCallRange]);
outgoingCallItems.push(outgoingCallItem);
});
}
else if (model.isNoun(item.name)) {
const outgoingCallMap = groupBy(model.getObjectRelations(item.name), relation => relation.verb);
outgoingCallMap.forEach((relations, verb) => {
const outgoingCallRanges = relations.map(relation => relation.getRangeOf(verb));
const verbItem = this.createCallHierarchyItem(verb, 'verb-inverted', document, outgoingCallRanges[0]);
const outgoingCallItem = new vscode.CallHierarchyIncomingCall(verbItem, outgoingCallRanges);
outgoingCallItems.push(outgoingCallItem);
});
}
return outgoingCallItems;
}
private createCallHierarchyItem(word: string, type: string, document: vscode.TextDocument, range: vscode.Range): vscode.CallHierarchyItem {
return new vscode.CallHierarchyItem(vscode.SymbolKind.Object, word, `(${type})`, document.uri, range, range);
}
}
/**
* Sample parser of the document text into the [FoodPyramid](#FoodPyramid) model.
*/
class FoodPyramidParser {
private _model = new FoodPyramid();
getModel(): FoodPyramid {
return this._model;
}
parse(textDocument: vscode.TextDocument): void {
const pattern = /^(\w+)\s+(\w+)\s+(\w+).$/gm;
let match: RegExpExecArray | null;
while ((match = pattern.exec(textDocument.getText()))) {
const startPosition = textDocument.positionAt(match.index);
const range = new vscode.Range(startPosition, startPosition.translate({ characterDelta: match[0].length }));
this._model.addRelation(new FoodRelation(match[1], match[2], match[3], match[0], range));
}
}
}
/**
* Groups array items by a field defined using a key selector.
* @param array array to be grouped
* @param keyGetter grouping key selector
*/
function groupBy<K, V>(array: Array<V>, keyGetter: (value: V) => K): Map<K, V[]> {
const map = new Map();
array.forEach((item) => {
const key = keyGetter(item);
const groupForKey = map.get(key) || [];
groupForKey.push(item);
map.set(key, groupForKey);
});
return map;
}

View File

@ -1,26 +1,26 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { FoodPyramidHierarchyProvider } from './FoodPyramidHierarchyProvider';
import { TextDecoder } from 'util';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "call-hierarchy-sample" is now active!');
const disposable = vscode.languages.registerCallHierarchyProvider('plaintext', new FoodPyramidHierarchyProvider());
context.subscriptions.push(disposable);
showSampleText(context);
}
async function showSampleText(context: vscode.ExtensionContext): Promise<void> {
const sampleTextEncoded = await vscode.workspace.fs.readFile(vscode.Uri.file(context.asAbsolutePath('sample.txt')));
const sampleText = new TextDecoder('utf-8').decode(sampleTextEncoded);
const doc = await vscode.workspace.openTextDocument({ language: 'plaintext', content: sampleText });
vscode.window.showTextDocument(doc);
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { FoodPyramidHierarchyProvider } from './FoodPyramidHierarchyProvider';
import { TextDecoder } from 'util';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "call-hierarchy-sample" is now active!');
const disposable = vscode.languages.registerCallHierarchyProvider('plaintext', new FoodPyramidHierarchyProvider());
context.subscriptions.push(disposable);
showSampleText(context);
}
async function showSampleText(context: vscode.ExtensionContext): Promise<void> {
const sampleTextEncoded = await vscode.workspace.fs.readFile(vscode.Uri.file(context.asAbsolutePath('sample.txt')));
const sampleText = new TextDecoder('utf-8').decode(sampleTextEncoded);
const doc = await vscode.workspace.openTextDocument({ language: 'plaintext', content: sampleText });
vscode.window.showTextDocument(doc);
}

View File

@ -1,88 +1,88 @@
import * as vscode from 'vscode';
/**
* Sample model of what the text in the document contains.
*/
export class FoodPyramid {
private _relations: FoodRelation[] = [];
private _nouns = new Set<string>();
private _verbs = new Set<string>();
getRelationAt(wordRange: vscode.Range): FoodRelation | undefined {
return this._relations.find(relation => relation.range.contains(wordRange));
}
addRelation(relation: FoodRelation): void {
this._relations.push(relation);
this._nouns.add(relation.object).add(relation.subject);
this._verbs.add(relation.verb);
}
isVerb(name: string): boolean {
return this._verbs.has(name.toLowerCase());
}
isNoun(name: string): boolean {
return this._nouns.has(name.toLowerCase());
}
getVerbRelations(verb: string): FoodRelation[] {
return this._relations
.filter(relation => relation.verb === verb.toLowerCase());
}
getNounRelations(noun: string): FoodRelation[] {
return this._relations
.filter(relation => relation.involves(noun));
}
getSubjectRelations(subject: string): FoodRelation[] {
return this._relations
.filter(relation => relation.subject === subject.toLowerCase());
}
getObjectRelations(object: string): FoodRelation[] {
return this._relations
.filter(relation => relation.object === object.toLowerCase());
}
}
/**
* Model element.
*/
export class FoodRelation {
private _subject: string;
private _verb: string;
private _object: string;
constructor(subject: string, verb: string, object: string,
private readonly originalText: string, public readonly range: vscode.Range) {
this._subject = subject.toLowerCase();
this._verb = verb.toLowerCase();
this._object = object.toLowerCase();
}
get subject(): string {
return this._subject;
}
get object(): string {
return this._object;
}
get verb(): string {
return this._verb;
}
involves(noun: string): boolean {
const needle = noun.toLowerCase();
return this._subject === needle || this._object === needle;
}
getRangeOf(word: string): vscode.Range {
const indexOfWord = new RegExp("\\b" + word + "\\b", "i").exec(this.originalText)!.index;
return new vscode.Range(this.range.start.translate({ characterDelta: indexOfWord }),
this.range.start.translate({ characterDelta: indexOfWord + word.length }));
}
}
import * as vscode from 'vscode';
/**
* Sample model of what the text in the document contains.
*/
export class FoodPyramid {
private _relations: FoodRelation[] = [];
private _nouns = new Set<string>();
private _verbs = new Set<string>();
getRelationAt(wordRange: vscode.Range): FoodRelation | undefined {
return this._relations.find(relation => relation.range.contains(wordRange));
}
addRelation(relation: FoodRelation): void {
this._relations.push(relation);
this._nouns.add(relation.object).add(relation.subject);
this._verbs.add(relation.verb);
}
isVerb(name: string): boolean {
return this._verbs.has(name.toLowerCase());
}
isNoun(name: string): boolean {
return this._nouns.has(name.toLowerCase());
}
getVerbRelations(verb: string): FoodRelation[] {
return this._relations
.filter(relation => relation.verb === verb.toLowerCase());
}
getNounRelations(noun: string): FoodRelation[] {
return this._relations
.filter(relation => relation.involves(noun));
}
getSubjectRelations(subject: string): FoodRelation[] {
return this._relations
.filter(relation => relation.subject === subject.toLowerCase());
}
getObjectRelations(object: string): FoodRelation[] {
return this._relations
.filter(relation => relation.object === object.toLowerCase());
}
}
/**
* Model element.
*/
export class FoodRelation {
private _subject: string;
private _verb: string;
private _object: string;
constructor(subject: string, verb: string, object: string,
private readonly originalText: string, public readonly range: vscode.Range) {
this._subject = subject.toLowerCase();
this._verb = verb.toLowerCase();
this._object = object.toLowerCase();
}
get subject(): string {
return this._subject;
}
get object(): string {
return this._object;
}
get verb(): string {
return this._verb;
}
involves(noun: string): boolean {
const needle = noun.toLowerCase();
return this._subject === needle || this._object === needle;
}
getRangeOf(word: string): vscode.Range {
const indexOfWord = new RegExp("\\b" + word + "\\b", "i").exec(this.originalText)!.index;
return new vscode.Range(this.range.start.translate({ characterDelta: indexOfWord }),
this.range.start.translate({ characterDelta: indexOfWord + word.length }));
}
}

File diff suppressed because it is too large Load Diff

View File

@ -12,7 +12,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples/issues"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -24,15 +24,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,67 +1,67 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
/** To demonstrate code actions associated with Diagnostics problems, this file provides a mock diagnostics entries. */
import * as vscode from 'vscode';
/** Code that is used to associate diagnostic entries with code actions. */
export const EMOJI_MENTION = 'emoji_mention';
/** String to detect in the text document. */
const EMOJI = 'emoji';
/**
* Analyzes the text document for problems.
* This demo diagnostic problem provider finds all mentions of 'emoji'.
* @param doc text document to analyze
* @param emojiDiagnostics diagnostic collection
*/
export function refreshDiagnostics(doc: vscode.TextDocument, emojiDiagnostics: vscode.DiagnosticCollection): void {
const diagnostics: vscode.Diagnostic[] = [];
for (let lineIndex = 0; lineIndex < doc.lineCount; lineIndex++) {
const lineOfText = doc.lineAt(lineIndex);
if (lineOfText.text.includes(EMOJI)) {
diagnostics.push(createDiagnostic(doc, lineOfText, lineIndex));
}
}
emojiDiagnostics.set(doc.uri, diagnostics);
}
function createDiagnostic(doc: vscode.TextDocument, lineOfText: vscode.TextLine, lineIndex: number): vscode.Diagnostic {
// find where in the line of that the 'emoji' is mentioned
const index = lineOfText.text.indexOf(EMOJI);
// create range that represents, where in the document the word is
const range = new vscode.Range(lineIndex, index, lineIndex, index + EMOJI.length);
const diagnostic = new vscode.Diagnostic(range, "When you say 'emoji', do you want to find out more?",
vscode.DiagnosticSeverity.Information);
diagnostic.code = EMOJI_MENTION;
return diagnostic;
}
export function subscribeToDocumentChanges(context: vscode.ExtensionContext, emojiDiagnostics: vscode.DiagnosticCollection): void {
if (vscode.window.activeTextEditor) {
refreshDiagnostics(vscode.window.activeTextEditor.document, emojiDiagnostics);
}
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
refreshDiagnostics(editor.document, emojiDiagnostics);
}
})
);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument(e => refreshDiagnostics(e.document, emojiDiagnostics))
);
context.subscriptions.push(
vscode.workspace.onDidCloseTextDocument(doc => emojiDiagnostics.delete(doc.uri))
);
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
/** To demonstrate code actions associated with Diagnostics problems, this file provides a mock diagnostics entries. */
import * as vscode from 'vscode';
/** Code that is used to associate diagnostic entries with code actions. */
export const EMOJI_MENTION = 'emoji_mention';
/** String to detect in the text document. */
const EMOJI = 'emoji';
/**
* Analyzes the text document for problems.
* This demo diagnostic problem provider finds all mentions of 'emoji'.
* @param doc text document to analyze
* @param emojiDiagnostics diagnostic collection
*/
export function refreshDiagnostics(doc: vscode.TextDocument, emojiDiagnostics: vscode.DiagnosticCollection): void {
const diagnostics: vscode.Diagnostic[] = [];
for (let lineIndex = 0; lineIndex < doc.lineCount; lineIndex++) {
const lineOfText = doc.lineAt(lineIndex);
if (lineOfText.text.includes(EMOJI)) {
diagnostics.push(createDiagnostic(doc, lineOfText, lineIndex));
}
}
emojiDiagnostics.set(doc.uri, diagnostics);
}
function createDiagnostic(doc: vscode.TextDocument, lineOfText: vscode.TextLine, lineIndex: number): vscode.Diagnostic {
// find where in the line of that the 'emoji' is mentioned
const index = lineOfText.text.indexOf(EMOJI);
// create range that represents, where in the document the word is
const range = new vscode.Range(lineIndex, index, lineIndex, index + EMOJI.length);
const diagnostic = new vscode.Diagnostic(range, "When you say 'emoji', do you want to find out more?",
vscode.DiagnosticSeverity.Information);
diagnostic.code = EMOJI_MENTION;
return diagnostic;
}
export function subscribeToDocumentChanges(context: vscode.ExtensionContext, emojiDiagnostics: vscode.DiagnosticCollection): void {
if (vscode.window.activeTextEditor) {
refreshDiagnostics(vscode.window.activeTextEditor.document, emojiDiagnostics);
}
context.subscriptions.push(
vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
refreshDiagnostics(editor.document, emojiDiagnostics);
}
})
);
context.subscriptions.push(
vscode.workspace.onDidChangeTextDocument(e => refreshDiagnostics(e.document, emojiDiagnostics))
);
context.subscriptions.push(
vscode.workspace.onDidCloseTextDocument(doc => emojiDiagnostics.delete(doc.uri))
);
}

View File

@ -1,108 +1,108 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
import { subscribeToDocumentChanges, EMOJI_MENTION } from './diagnostics';
const COMMAND = 'code-actions-sample.command';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider('markdown', new Emojizer(), {
providedCodeActionKinds: Emojizer.providedCodeActionKinds
}));
const emojiDiagnostics = vscode.languages.createDiagnosticCollection("emoji");
context.subscriptions.push(emojiDiagnostics);
subscribeToDocumentChanges(context, emojiDiagnostics);
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider('markdown', new Emojinfo(), {
providedCodeActionKinds: Emojinfo.providedCodeActionKinds
})
);
context.subscriptions.push(
vscode.commands.registerCommand(COMMAND, () => vscode.env.openExternal(vscode.Uri.parse('https://unicode.org/emoji/charts-12.0/full-emoji-list.html')))
);
}
/**
* Provides code actions for converting :) to a smiley emoji.
*/
export class Emojizer implements vscode.CodeActionProvider {
public static readonly providedCodeActionKinds = [
vscode.CodeActionKind.QuickFix
];
public provideCodeActions(document: vscode.TextDocument, range: vscode.Range): vscode.CodeAction[] | undefined {
if (!this.isAtStartOfSmiley(document, range)) {
return;
}
const replaceWithSmileyCatFix = this.createFix(document, range, '😺');
const replaceWithSmileyFix = this.createFix(document, range, '😀');
// Marking a single fix as `preferred` means that users can apply it with a
// single keyboard shortcut using the `Auto Fix` command.
replaceWithSmileyFix.isPreferred = true;
const replaceWithSmileyHankyFix = this.createFix(document, range, '💩');
const commandAction = this.createCommand();
return [
replaceWithSmileyCatFix,
replaceWithSmileyFix,
replaceWithSmileyHankyFix,
commandAction
];
}
private isAtStartOfSmiley(document: vscode.TextDocument, range: vscode.Range) {
const start = range.start;
const line = document.lineAt(start.line);
return line.text[start.character] === ':' && line.text[start.character + 1] === ')';
}
private createFix(document: vscode.TextDocument, range: vscode.Range, emoji: string): vscode.CodeAction {
const fix = new vscode.CodeAction(`Convert to ${emoji}`, vscode.CodeActionKind.QuickFix);
fix.edit = new vscode.WorkspaceEdit();
fix.edit.replace(document.uri, new vscode.Range(range.start, range.start.translate(0, 2)), emoji);
return fix;
}
private createCommand(): vscode.CodeAction {
const action = new vscode.CodeAction('Learn more...', vscode.CodeActionKind.Empty);
action.command = { command: COMMAND, title: 'Learn more about emojis', tooltip: 'This will open the unicode emoji page.' };
return action;
}
}
/**
* Provides code actions corresponding to diagnostic problems.
*/
export class Emojinfo implements vscode.CodeActionProvider {
public static readonly providedCodeActionKinds = [
vscode.CodeActionKind.QuickFix
];
provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.CodeAction[] {
// for each diagnostic entry that has the matching `code`, create a code action command
return context.diagnostics
.filter(diagnostic => diagnostic.code === EMOJI_MENTION)
.map(diagnostic => this.createCommandCodeAction(diagnostic));
}
private createCommandCodeAction(diagnostic: vscode.Diagnostic): vscode.CodeAction {
const action = new vscode.CodeAction('Learn more...', vscode.CodeActionKind.QuickFix);
action.command = { command: COMMAND, title: 'Learn more about emojis', tooltip: 'This will open the unicode emoji page.' };
action.diagnostics = [diagnostic];
action.isPreferred = true;
return action;
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
import { subscribeToDocumentChanges, EMOJI_MENTION } from './diagnostics';
const COMMAND = 'code-actions-sample.command';
export function activate(context: vscode.ExtensionContext) {
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider('markdown', new Emojizer(), {
providedCodeActionKinds: Emojizer.providedCodeActionKinds
}));
const emojiDiagnostics = vscode.languages.createDiagnosticCollection("emoji");
context.subscriptions.push(emojiDiagnostics);
subscribeToDocumentChanges(context, emojiDiagnostics);
context.subscriptions.push(
vscode.languages.registerCodeActionsProvider('markdown', new Emojinfo(), {
providedCodeActionKinds: Emojinfo.providedCodeActionKinds
})
);
context.subscriptions.push(
vscode.commands.registerCommand(COMMAND, () => vscode.env.openExternal(vscode.Uri.parse('https://unicode.org/emoji/charts-12.0/full-emoji-list.html')))
);
}
/**
* Provides code actions for converting :) to a smiley emoji.
*/
export class Emojizer implements vscode.CodeActionProvider {
public static readonly providedCodeActionKinds = [
vscode.CodeActionKind.QuickFix
];
public provideCodeActions(document: vscode.TextDocument, range: vscode.Range): vscode.CodeAction[] | undefined {
if (!this.isAtStartOfSmiley(document, range)) {
return;
}
const replaceWithSmileyCatFix = this.createFix(document, range, '😺');
const replaceWithSmileyFix = this.createFix(document, range, '😀');
// Marking a single fix as `preferred` means that users can apply it with a
// single keyboard shortcut using the `Auto Fix` command.
replaceWithSmileyFix.isPreferred = true;
const replaceWithSmileyHankyFix = this.createFix(document, range, '💩');
const commandAction = this.createCommand();
return [
replaceWithSmileyCatFix,
replaceWithSmileyFix,
replaceWithSmileyHankyFix,
commandAction
];
}
private isAtStartOfSmiley(document: vscode.TextDocument, range: vscode.Range) {
const start = range.start;
const line = document.lineAt(start.line);
return line.text[start.character] === ':' && line.text[start.character + 1] === ')';
}
private createFix(document: vscode.TextDocument, range: vscode.Range, emoji: string): vscode.CodeAction {
const fix = new vscode.CodeAction(`Convert to ${emoji}`, vscode.CodeActionKind.QuickFix);
fix.edit = new vscode.WorkspaceEdit();
fix.edit.replace(document.uri, new vscode.Range(range.start, range.start.translate(0, 2)), emoji);
return fix;
}
private createCommand(): vscode.CodeAction {
const action = new vscode.CodeAction('Learn more...', vscode.CodeActionKind.Empty);
action.command = { command: COMMAND, title: 'Learn more about emojis', tooltip: 'This will open the unicode emoji page.' };
return action;
}
}
/**
* Provides code actions corresponding to diagnostic problems.
*/
export class Emojinfo implements vscode.CodeActionProvider {
public static readonly providedCodeActionKinds = [
vscode.CodeActionKind.QuickFix
];
provideCodeActions(document: vscode.TextDocument, range: vscode.Range | vscode.Selection, context: vscode.CodeActionContext, token: vscode.CancellationToken): vscode.CodeAction[] {
// for each diagnostic entry that has the matching `code`, create a code action command
return context.diagnostics
.filter(diagnostic => diagnostic.code === EMOJI_MENTION)
.map(diagnostic => this.createCommandCodeAction(diagnostic));
}
private createCommandCodeAction(diagnostic: vscode.Diagnostic): vscode.CodeAction {
const action = new vscode.CodeAction('Learn more...', vscode.CodeActionKind.QuickFix);
action.command = { command: COMMAND, title: 'Learn more about emojis', tooltip: 'This will open the unicode emoji page.' };
action.diagnostics = [diagnostic];
action.isPreferred = true;
return action;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.26.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -45,15 +45,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.26.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,55 +1,55 @@
import * as vscode from 'vscode';
/**
* CodelensProvider
*/
export class CodelensProvider implements vscode.CodeLensProvider {
private codeLenses: vscode.CodeLens[] = [];
private regex: RegExp;
private _onDidChangeCodeLenses: vscode.EventEmitter<void> = new vscode.EventEmitter<void>();
public readonly onDidChangeCodeLenses: vscode.Event<void> = this._onDidChangeCodeLenses.event;
constructor() {
this.regex = /(.+)/g;
vscode.workspace.onDidChangeConfiguration((_) => {
this._onDidChangeCodeLenses.fire();
});
}
public provideCodeLenses(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
if (vscode.workspace.getConfiguration("codelens-sample").get("enableCodeLens", true)) {
this.codeLenses = [];
const regex = new RegExp(this.regex);
const text = document.getText();
let matches;
while ((matches = regex.exec(text)) !== null) {
const line = document.lineAt(document.positionAt(matches.index).line);
const indexOf = line.text.indexOf(matches[0]);
const position = new vscode.Position(line.lineNumber, indexOf);
const range = document.getWordRangeAtPosition(position, new RegExp(this.regex));
if (range) {
this.codeLenses.push(new vscode.CodeLens(range));
}
}
return this.codeLenses;
}
return [];
}
public resolveCodeLens(codeLens: vscode.CodeLens, token: vscode.CancellationToken) {
if (vscode.workspace.getConfiguration("codelens-sample").get("enableCodeLens", true)) {
codeLens.command = {
title: "Codelens provided by sample extension",
tooltip: "Tooltip provided by sample extension",
command: "codelens-sample.codelensAction",
arguments: ["Argument 1", false]
};
return codeLens;
}
return null;
}
}
import * as vscode from 'vscode';
/**
* CodelensProvider
*/
export class CodelensProvider implements vscode.CodeLensProvider {
private codeLenses: vscode.CodeLens[] = [];
private regex: RegExp;
private _onDidChangeCodeLenses: vscode.EventEmitter<void> = new vscode.EventEmitter<void>();
public readonly onDidChangeCodeLenses: vscode.Event<void> = this._onDidChangeCodeLenses.event;
constructor() {
this.regex = /(.+)/g;
vscode.workspace.onDidChangeConfiguration((_) => {
this._onDidChangeCodeLenses.fire();
});
}
public provideCodeLenses(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.CodeLens[] | Thenable<vscode.CodeLens[]> {
if (vscode.workspace.getConfiguration("codelens-sample").get("enableCodeLens", true)) {
this.codeLenses = [];
const regex = new RegExp(this.regex);
const text = document.getText();
let matches;
while ((matches = regex.exec(text)) !== null) {
const line = document.lineAt(document.positionAt(matches.index).line);
const indexOf = line.text.indexOf(matches[0]);
const position = new vscode.Position(line.lineNumber, indexOf);
const range = document.getWordRangeAtPosition(position, new RegExp(this.regex));
if (range) {
this.codeLenses.push(new vscode.CodeLens(range));
}
}
return this.codeLenses;
}
return [];
}
public resolveCodeLens(codeLens: vscode.CodeLens, token: vscode.CancellationToken) {
if (vscode.workspace.getConfiguration("codelens-sample").get("enableCodeLens", true)) {
codeLens.command = {
title: "Codelens provided by sample extension",
tooltip: "Tooltip provided by sample extension",
command: "codelens-sample.codelensAction",
arguments: ["Argument 1", false]
};
return codeLens;
}
return null;
}
}

View File

@ -1,35 +1,35 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import { ExtensionContext, languages, commands, Disposable, workspace, window } from 'vscode';
import { CodelensProvider } from './CodelensProvider';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
let disposables: Disposable[] = [];
export function activate(context: ExtensionContext) {
const codelensProvider = new CodelensProvider();
languages.registerCodeLensProvider("*", codelensProvider);
commands.registerCommand("codelens-sample.enableCodeLens", () => {
workspace.getConfiguration("codelens-sample").update("enableCodeLens", true, true);
});
commands.registerCommand("codelens-sample.disableCodeLens", () => {
workspace.getConfiguration("codelens-sample").update("enableCodeLens", false, true);
});
commands.registerCommand("codelens-sample.codelensAction", (args: any) => {
window.showInformationMessage(`CodeLens action clicked with args=${args}`);
});
}
// this method is called when your extension is deactivated
export function deactivate() {
if (disposables) {
disposables.forEach(item => item.dispose());
}
disposables = [];
}
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import { ExtensionContext, languages, commands, Disposable, workspace, window } from 'vscode';
import { CodelensProvider } from './CodelensProvider';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
let disposables: Disposable[] = [];
export function activate(context: ExtensionContext) {
const codelensProvider = new CodelensProvider();
languages.registerCodeLensProvider("*", codelensProvider);
commands.registerCommand("codelens-sample.enableCodeLens", () => {
workspace.getConfiguration("codelens-sample").update("enableCodeLens", true, true);
});
commands.registerCommand("codelens-sample.disableCodeLens", () => {
workspace.getConfiguration("codelens-sample").update("enableCodeLens", false, true);
});
commands.registerCommand("codelens-sample.codelensAction", (args: any) => {
window.showInformationMessage(`CodeLens action clicked with args=${args}`);
});
}
// this method is called when your extension is deactivated
export function deactivate() {
if (disposables) {
disposables.forEach(item => item.dispose());
}
disposables = [];
}

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.65.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -156,14 +156,14 @@
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"lint": "eslint . --ext .ts,.tsx"
"lint": "eslint \"src/**/*.ts\""
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "~1.65.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,144 +1,144 @@
'use strict';
import * as vscode from 'vscode';
let commentId = 1;
class NoteComment implements vscode.Comment {
id: number;
label: string | undefined;
savedBody: string | vscode.MarkdownString; // for the Cancel button
constructor(
public body: string | vscode.MarkdownString,
public mode: vscode.CommentMode,
public author: vscode.CommentAuthorInformation,
public parent?: vscode.CommentThread,
public contextValue?: string
) {
this.id = ++commentId;
this.savedBody = this.body;
}
}
export function activate(context: vscode.ExtensionContext) {
// A `CommentController` is able to provide comments for documents.
const commentController = vscode.comments.createCommentController('comment-sample', 'Comment API Sample');
context.subscriptions.push(commentController);
// A `CommentingRangeProvider` controls where gutter decorations that allow adding comments are shown
commentController.commentingRangeProvider = {
provideCommentingRanges: (document: vscode.TextDocument, token: vscode.CancellationToken) => {
const lineCount = document.lineCount;
return [new vscode.Range(0, 0, lineCount - 1, 0)];
}
};
context.subscriptions.push(vscode.commands.registerCommand('mywiki.createNote', (reply: vscode.CommentReply) => {
replyNote(reply);
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.replyNote', (reply: vscode.CommentReply) => {
replyNote(reply);
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.startDraft', (reply: vscode.CommentReply) => {
const thread = reply.thread;
thread.contextValue = 'draft';
const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, { name: 'vscode' }, thread);
newComment.label = 'pending';
thread.comments = [...thread.comments, newComment];
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.finishDraft', (reply: vscode.CommentReply) => {
const thread = reply.thread;
if (!thread) {
return;
}
thread.contextValue = undefined;
thread.collapsibleState = vscode.CommentThreadCollapsibleState.Collapsed;
if (reply.text) {
const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, { name: 'vscode' }, thread);
thread.comments = [...thread.comments, newComment].map(comment => {
comment.label = undefined;
return comment;
});
}
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNoteComment', (comment: NoteComment) => {
const thread = comment.parent;
if (!thread) {
return;
}
thread.comments = thread.comments.filter(cmt => (cmt as NoteComment).id !== comment.id);
if (thread.comments.length === 0) {
thread.dispose();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNote', (thread: vscode.CommentThread) => {
thread.dispose();
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.cancelsaveNote', (comment: NoteComment) => {
if (!comment.parent) {
return;
}
comment.parent.comments = comment.parent.comments.map(cmt => {
if ((cmt as NoteComment).id === comment.id) {
cmt.body = (cmt as NoteComment).savedBody;
cmt.mode = vscode.CommentMode.Preview;
}
return cmt;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.saveNote', (comment: NoteComment) => {
if (!comment.parent) {
return;
}
comment.parent.comments = comment.parent.comments.map(cmt => {
if ((cmt as NoteComment).id === comment.id) {
(cmt as NoteComment).savedBody = cmt.body;
cmt.mode = vscode.CommentMode.Preview;
}
return cmt;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.editNote', (comment: NoteComment) => {
if (!comment.parent) {
return;
}
comment.parent.comments = comment.parent.comments.map(cmt => {
if ((cmt as NoteComment).id === comment.id) {
cmt.mode = vscode.CommentMode.Editing;
}
return cmt;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.dispose', () => {
commentController.dispose();
}));
function replyNote(reply: vscode.CommentReply) {
const thread = reply.thread;
const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, { name: 'vscode' }, thread, thread.comments.length ? 'canDelete' : undefined);
if (thread.contextValue === 'draft') {
newComment.label = 'pending';
}
thread.comments = [...thread.comments, newComment];
}
}
'use strict';
import * as vscode from 'vscode';
let commentId = 1;
class NoteComment implements vscode.Comment {
id: number;
label: string | undefined;
savedBody: string | vscode.MarkdownString; // for the Cancel button
constructor(
public body: string | vscode.MarkdownString,
public mode: vscode.CommentMode,
public author: vscode.CommentAuthorInformation,
public parent?: vscode.CommentThread,
public contextValue?: string
) {
this.id = ++commentId;
this.savedBody = this.body;
}
}
export function activate(context: vscode.ExtensionContext) {
// A `CommentController` is able to provide comments for documents.
const commentController = vscode.comments.createCommentController('comment-sample', 'Comment API Sample');
context.subscriptions.push(commentController);
// A `CommentingRangeProvider` controls where gutter decorations that allow adding comments are shown
commentController.commentingRangeProvider = {
provideCommentingRanges: (document: vscode.TextDocument, token: vscode.CancellationToken) => {
const lineCount = document.lineCount;
return [new vscode.Range(0, 0, lineCount - 1, 0)];
}
};
context.subscriptions.push(vscode.commands.registerCommand('mywiki.createNote', (reply: vscode.CommentReply) => {
replyNote(reply);
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.replyNote', (reply: vscode.CommentReply) => {
replyNote(reply);
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.startDraft', (reply: vscode.CommentReply) => {
const thread = reply.thread;
thread.contextValue = 'draft';
const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, { name: 'vscode' }, thread);
newComment.label = 'pending';
thread.comments = [...thread.comments, newComment];
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.finishDraft', (reply: vscode.CommentReply) => {
const thread = reply.thread;
if (!thread) {
return;
}
thread.contextValue = undefined;
thread.collapsibleState = vscode.CommentThreadCollapsibleState.Collapsed;
if (reply.text) {
const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, { name: 'vscode' }, thread);
thread.comments = [...thread.comments, newComment].map(comment => {
comment.label = undefined;
return comment;
});
}
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNoteComment', (comment: NoteComment) => {
const thread = comment.parent;
if (!thread) {
return;
}
thread.comments = thread.comments.filter(cmt => (cmt as NoteComment).id !== comment.id);
if (thread.comments.length === 0) {
thread.dispose();
}
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.deleteNote', (thread: vscode.CommentThread) => {
thread.dispose();
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.cancelsaveNote', (comment: NoteComment) => {
if (!comment.parent) {
return;
}
comment.parent.comments = comment.parent.comments.map(cmt => {
if ((cmt as NoteComment).id === comment.id) {
cmt.body = (cmt as NoteComment).savedBody;
cmt.mode = vscode.CommentMode.Preview;
}
return cmt;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.saveNote', (comment: NoteComment) => {
if (!comment.parent) {
return;
}
comment.parent.comments = comment.parent.comments.map(cmt => {
if ((cmt as NoteComment).id === comment.id) {
(cmt as NoteComment).savedBody = cmt.body;
cmt.mode = vscode.CommentMode.Preview;
}
return cmt;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.editNote', (comment: NoteComment) => {
if (!comment.parent) {
return;
}
comment.parent.comments = comment.parent.comments.map(cmt => {
if ((cmt as NoteComment).id === comment.id) {
cmt.mode = vscode.CommentMode.Editing;
}
return cmt;
});
}));
context.subscriptions.push(vscode.commands.registerCommand('mywiki.dispose', () => {
commentController.dispose();
}));
function replyNote(reply: vscode.CommentReply) {
const thread = reply.thread;
const newComment = new NoteComment(reply.text, vscode.CommentMode.Preview, { name: 'vscode' }, thread, thread.comments.length ? 'canDelete' : undefined);
if (thread.contextValue === 'draft') {
newComment.label = 'pending';
}
thread.comments = [...thread.comments, newComment];
}
}

File diff suppressed because it is too large Load Diff

View File

@ -10,7 +10,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -22,15 +22,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,74 +1,74 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const provider1 = vscode.languages.registerCompletionItemProvider('plaintext', {
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext) {
// a simple completion item which inserts `Hello World!`
const simpleCompletion = new vscode.CompletionItem('Hello World!');
// a completion item that inserts its text as snippet,
// the `insertText`-property is a `SnippetString` which will be
// honored by the editor.
const snippetCompletion = new vscode.CompletionItem('Good part of the day');
snippetCompletion.insertText = new vscode.SnippetString('Good ${1|morning,afternoon,evening|}. It is ${1}, right?');
const docs : any = new vscode.MarkdownString("Inserts a snippet that lets you select [link](x.ts).");
snippetCompletion.documentation = docs;
docs.baseUri = vscode.Uri.parse('http://example.com/a/b/c/');
// a completion item that can be accepted by a commit character,
// the `commitCharacters`-property is set which means that the completion will
// be inserted and then the character will be typed.
const commitCharacterCompletion = new vscode.CompletionItem('console');
commitCharacterCompletion.commitCharacters = ['.'];
commitCharacterCompletion.documentation = new vscode.MarkdownString('Press `.` to get `console.`');
// a completion item that retriggers IntelliSense when being accepted,
// the `command`-property is set which the editor will execute after
// completion has been inserted. Also, the `insertText` is set so that
// a space is inserted after `new`
const commandCompletion = new vscode.CompletionItem('new');
commandCompletion.kind = vscode.CompletionItemKind.Keyword;
commandCompletion.insertText = 'new ';
commandCompletion.command = { command: 'editor.action.triggerSuggest', title: 'Re-trigger completions...' };
// return all completion items as array
return [
simpleCompletion,
snippetCompletion,
commitCharacterCompletion,
commandCompletion
];
}
});
const provider2 = vscode.languages.registerCompletionItemProvider(
'plaintext',
{
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
// get all text until the `position` and check if it reads `console.`
// and if so then complete if `log`, `warn`, and `error`
const linePrefix = document.lineAt(position).text.substr(0, position.character);
if (!linePrefix.endsWith('console.')) {
return undefined;
}
return [
new vscode.CompletionItem('log', vscode.CompletionItemKind.Method),
new vscode.CompletionItem('warn', vscode.CompletionItemKind.Method),
new vscode.CompletionItem('error', vscode.CompletionItemKind.Method),
];
}
},
'.' // triggered whenever a '.' is being typed
);
context.subscriptions.push(provider1, provider2);
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const provider1 = vscode.languages.registerCompletionItemProvider('plaintext', {
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position, token: vscode.CancellationToken, context: vscode.CompletionContext) {
// a simple completion item which inserts `Hello World!`
const simpleCompletion = new vscode.CompletionItem('Hello World!');
// a completion item that inserts its text as snippet,
// the `insertText`-property is a `SnippetString` which will be
// honored by the editor.
const snippetCompletion = new vscode.CompletionItem('Good part of the day');
snippetCompletion.insertText = new vscode.SnippetString('Good ${1|morning,afternoon,evening|}. It is ${1}, right?');
const docs: any = new vscode.MarkdownString("Inserts a snippet that lets you select [link](x.ts).");
snippetCompletion.documentation = docs;
docs.baseUri = vscode.Uri.parse('http://example.com/a/b/c/');
// a completion item that can be accepted by a commit character,
// the `commitCharacters`-property is set which means that the completion will
// be inserted and then the character will be typed.
const commitCharacterCompletion = new vscode.CompletionItem('console');
commitCharacterCompletion.commitCharacters = ['.'];
commitCharacterCompletion.documentation = new vscode.MarkdownString('Press `.` to get `console.`');
// a completion item that retriggers IntelliSense when being accepted,
// the `command`-property is set which the editor will execute after
// completion has been inserted. Also, the `insertText` is set so that
// a space is inserted after `new`
const commandCompletion = new vscode.CompletionItem('new');
commandCompletion.kind = vscode.CompletionItemKind.Keyword;
commandCompletion.insertText = 'new ';
commandCompletion.command = { command: 'editor.action.triggerSuggest', title: 'Re-trigger completions...' };
// return all completion items as array
return [
simpleCompletion,
snippetCompletion,
commitCharacterCompletion,
commandCompletion
];
}
});
const provider2 = vscode.languages.registerCompletionItemProvider(
'plaintext',
{
provideCompletionItems(document: vscode.TextDocument, position: vscode.Position) {
// get all text until the `position` and check if it reads `console.`
// and if so then complete if `log`, `warn`, and `error`
const linePrefix = document.lineAt(position).text.substr(0, position.character);
if (!linePrefix.endsWith('console.')) {
return undefined;
}
return [
new vscode.CompletionItem('log', vscode.CompletionItemKind.Method),
new vscode.CompletionItem('warn', vscode.CompletionItemKind.Method),
new vscode.CompletionItem('error', vscode.CompletionItemKind.Method),
];
}
},
'.' // triggered whenever a '.' is being typed
);
context.subscriptions.push(provider1, provider2);
}

File diff suppressed because it is too large Load Diff

View File

@ -11,16 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:config.commands.configureViewOnWindowOpen",
"onCommand:config.commands.configureEmptyLastLineCurrentFile",
"onCommand:config.commands.configureEmptyLastLineFiles"
],
"activationEvents": [],
"main": "./out/extension",
"keywords": [
"multi-root ready"
@ -159,15 +155,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.40.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,225 +1,225 @@
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
// Example: Reading Window scoped configuration
const configuredView = vscode.workspace.getConfiguration().get('conf.view.showOnWindowOpen');
switch (configuredView) {
case 'explorer':
vscode.commands.executeCommand('workbench.view.explorer');
break;
case 'search':
vscode.commands.executeCommand('workbench.view.search');
break;
case 'scm':
vscode.commands.executeCommand('workbench.view.scm');
break;
case 'debug':
vscode.commands.executeCommand('workbench.view.debug');
break;
case 'extensions':
vscode.commands.executeCommand('workbench.view.extensions');
break;
}
// Example: Updating Window scoped configuration
vscode.commands.registerCommand('config.commands.configureViewOnWindowOpen', async () => {
// 1) Getting the value
const value = await vscode.window.showQuickPick(['explorer', 'search', 'scm', 'debug', 'extensions'], { placeHolder: 'Select the view to show when opening a window.' });
if (vscode.workspace.workspaceFolders) {
// 2) Getting the Configuration target
const target = await vscode.window.showQuickPick(
[
{ label: 'User', description: 'User Settings', target: vscode.ConfigurationTarget.Global },
{ label: 'Workspace', description: 'Workspace Settings', target: vscode.ConfigurationTarget.Workspace }
],
{ placeHolder: 'Select the view to show when opening a window.' });
if (value && target) {
// 3) Update the configuration value in the target
await vscode.workspace.getConfiguration().update('conf.view.showOnWindowOpen', value, target.target);
/*
// Default is to update in Workspace
await vscode.workspace.getConfiguration().update('conf.view.showOnWindowOpen', value);
*/
}
} else {
// 2) Update the configuration value in User Setting in case of no workspace folders
await vscode.workspace.getConfiguration().update('conf.view.showOnWindowOpen', value, vscode.ConfigurationTarget.Global);
}
});
// Example: Reading Resource scoped configuration for a file
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(e => {
// 1) Get the configured glob pattern value for the current file
const value: any = vscode.workspace.getConfiguration('', e.uri).get('conf.resource.insertEmptyLastLine');
// 2) Check if the current resource matches the glob pattern
const matches = value ? value[e.fileName] : undefined;
// 3) If matches, insert empty last line
if (matches) {
vscode.window.showInformationMessage('An empty line will be added to the document ' + e.fileName);
}
}));
// Example: Updating Resource scoped Configuration for current file
vscode.commands.registerCommand('config.commands.configureEmptyLastLineCurrentFile', async () => {
if (vscode.window.activeTextEditor) {
const currentDocument = vscode.window.activeTextEditor.document;
// 1) Get the configuration for the current document
const configuration = vscode.workspace.getConfiguration('', currentDocument.uri);
// 2) Get the configiuration value
const currentValue = configuration.get('conf.resource.insertEmptyLastLine', {});
// 3) Choose target to Global when there are no workspace folders
const target = vscode.workspace.workspaceFolders ? vscode.ConfigurationTarget.WorkspaceFolder : vscode.ConfigurationTarget.Global;
const value = { ...currentValue, ...{ [currentDocument.fileName]: true } };
// 4) Update the configuration
await configuration.update('conf.resource.insertEmptyLastLine', value, target);
}
});
// Example: Updating Resource scoped Configuration
vscode.commands.registerCommand('config.commands.configureEmptyLastLineFiles', async () => {
// 1) Getting the value
const value = await vscode.window.showInputBox({ prompt: 'Provide glob pattern of files to have empty last line.' });
if (vscode.workspace.workspaceFolders) {
// 2) Getting the target
const target = await vscode.window.showQuickPick(
[
{ label: 'Application', description: 'User Settings', target: vscode.ConfigurationTarget.Global },
{ label: 'Workspace', description: 'Workspace Settings', target: vscode.ConfigurationTarget.Workspace },
{ label: 'Workspace Folder', description: 'Workspace Folder Settings', target: vscode.ConfigurationTarget.WorkspaceFolder }
],
{ placeHolder: 'Select the target to which this setting should be applied' });
if (value && target) {
if (target.target === vscode.ConfigurationTarget.WorkspaceFolder) {
// 3) Getting the workspace folder
const workspaceFolder = await vscode.window.showWorkspaceFolderPick({ placeHolder: 'Pick Workspace Folder to which this setting should be applied' });
if (workspaceFolder) {
// 4) Get the configuration for the workspace folder
const configuration = vscode.workspace.getConfiguration('', workspaceFolder.uri);
// 5) Get the current value
const currentValue = configuration.get<{}>('conf.resource.insertEmptyLastLine');
const newValue = { ...currentValue, ...{ [value]: true } };
// 6) Update the configuration value
await configuration.update('conf.resource.insertEmptyLastLine', newValue, target.target);
}
} else {
// 3) Get the configuration
const configuration = vscode.workspace.getConfiguration();
// 4) Get the current value
const currentValue = configuration.get<{}>('conf.resource.insertEmptyLastLine');
const newValue = { ...currentValue, ...(value ? { [value]: true } : {}) };
// 3) Update the value in the target
await vscode.workspace.getConfiguration().update('conf.resource.insertEmptyLastLine', newValue, target.target);
}
}
} else {
// 2) Get the configuration
const configuration = vscode.workspace.getConfiguration();
// 3) Get the current value
const currentValue = configuration.get<{}>('conf.resource.insertEmptyLastLine');
const newValue = { ...currentValue, ...(value ? { [value]: true } : {}) };
// 4) Update the value in the User Settings
await vscode.workspace.getConfiguration().update('conf.resource.insertEmptyLastLine', newValue, vscode.ConfigurationTarget.Global);
}
});
let statusSizeDisposable: vscode.Disposable;
// Example: Reading language overridable configuration for a document
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(e => {
if (statusSizeDisposable) {
statusSizeDisposable.dispose();
}
// 1) Check if showing size is configured for current file
const showSize: any = vscode.workspace.getConfiguration('', e).get('conf.language.showSize');
// 3) If matches, insert empty last line
if (showSize) {
statusSizeDisposable = vscode.window.setStatusBarMessage(`${e.getText().length}`);
}
}));
// Example: Overriding configuration value for a language
context.subscriptions.push(vscode.commands.registerCommand('config.commands.overrideLanguageValue', async () => {
// 1) Getting the languge id
const languageId = await vscode.window.showInputBox({ placeHolder: 'Enter the language id' });
// 2) Update
vscode.workspace.getConfiguration('', { languageId: languageId! }).update('conf.language.showSize', true, false, true);
}));
// Example: Listening to configuration changes
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('conf.resource.insertEmptyLastLine')) {
if (vscode.window.activeTextEditor) {
const currentDocument = vscode.window.activeTextEditor.document;
// 1) Get the configured glob pattern value for the current file
const value: any = vscode.workspace.getConfiguration('', currentDocument.uri).get('conf.resource.insertEmptyLastLine');
// 2) Check if the current resource matches the glob pattern
const matches = value[currentDocument.fileName];
// 3) If matches, insert empty last line
if (matches) {
vscode.window.showInformationMessage('An empty line will be added to the document ' + currentDocument.fileName);
}
}
}
// Check if a language configuration is changed for a text document
if (e.affectsConfiguration('conf.language.showSize', vscode.window.activeTextEditor?.document)) {
// noop
}
// Check if a language configuration is changed for a language
if (e.affectsConfiguration('conf.language.showSize', { languageId: 'typescript' })) {
// noop
}
}));
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
// Example: Reading Window scoped configuration
const configuredView = vscode.workspace.getConfiguration().get('conf.view.showOnWindowOpen');
switch (configuredView) {
case 'explorer':
vscode.commands.executeCommand('workbench.view.explorer');
break;
case 'search':
vscode.commands.executeCommand('workbench.view.search');
break;
case 'scm':
vscode.commands.executeCommand('workbench.view.scm');
break;
case 'debug':
vscode.commands.executeCommand('workbench.view.debug');
break;
case 'extensions':
vscode.commands.executeCommand('workbench.view.extensions');
break;
}
// Example: Updating Window scoped configuration
vscode.commands.registerCommand('config.commands.configureViewOnWindowOpen', async () => {
// 1) Getting the value
const value = await vscode.window.showQuickPick(['explorer', 'search', 'scm', 'debug', 'extensions'], { placeHolder: 'Select the view to show when opening a window.' });
if (vscode.workspace.workspaceFolders) {
// 2) Getting the Configuration target
const target = await vscode.window.showQuickPick(
[
{ label: 'User', description: 'User Settings', target: vscode.ConfigurationTarget.Global },
{ label: 'Workspace', description: 'Workspace Settings', target: vscode.ConfigurationTarget.Workspace }
],
{ placeHolder: 'Select the view to show when opening a window.' });
if (value && target) {
// 3) Update the configuration value in the target
await vscode.workspace.getConfiguration().update('conf.view.showOnWindowOpen', value, target.target);
/*
// Default is to update in Workspace
await vscode.workspace.getConfiguration().update('conf.view.showOnWindowOpen', value);
*/
}
} else {
// 2) Update the configuration value in User Setting in case of no workspace folders
await vscode.workspace.getConfiguration().update('conf.view.showOnWindowOpen', value, vscode.ConfigurationTarget.Global);
}
});
// Example: Reading Resource scoped configuration for a file
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(e => {
// 1) Get the configured glob pattern value for the current file
const value: any = vscode.workspace.getConfiguration('', e.uri).get('conf.resource.insertEmptyLastLine');
// 2) Check if the current resource matches the glob pattern
const matches = value ? value[e.fileName] : undefined;
// 3) If matches, insert empty last line
if (matches) {
vscode.window.showInformationMessage('An empty line will be added to the document ' + e.fileName);
}
}));
// Example: Updating Resource scoped Configuration for current file
vscode.commands.registerCommand('config.commands.configureEmptyLastLineCurrentFile', async () => {
if (vscode.window.activeTextEditor) {
const currentDocument = vscode.window.activeTextEditor.document;
// 1) Get the configuration for the current document
const configuration = vscode.workspace.getConfiguration('', currentDocument.uri);
// 2) Get the configiuration value
const currentValue = configuration.get('conf.resource.insertEmptyLastLine', {});
// 3) Choose target to Global when there are no workspace folders
const target = vscode.workspace.workspaceFolders ? vscode.ConfigurationTarget.WorkspaceFolder : vscode.ConfigurationTarget.Global;
const value = { ...currentValue, ...{ [currentDocument.fileName]: true } };
// 4) Update the configuration
await configuration.update('conf.resource.insertEmptyLastLine', value, target);
}
});
// Example: Updating Resource scoped Configuration
vscode.commands.registerCommand('config.commands.configureEmptyLastLineFiles', async () => {
// 1) Getting the value
const value = await vscode.window.showInputBox({ prompt: 'Provide glob pattern of files to have empty last line.' });
if (vscode.workspace.workspaceFolders) {
// 2) Getting the target
const target = await vscode.window.showQuickPick(
[
{ label: 'Application', description: 'User Settings', target: vscode.ConfigurationTarget.Global },
{ label: 'Workspace', description: 'Workspace Settings', target: vscode.ConfigurationTarget.Workspace },
{ label: 'Workspace Folder', description: 'Workspace Folder Settings', target: vscode.ConfigurationTarget.WorkspaceFolder }
],
{ placeHolder: 'Select the target to which this setting should be applied' });
if (value && target) {
if (target.target === vscode.ConfigurationTarget.WorkspaceFolder) {
// 3) Getting the workspace folder
const workspaceFolder = await vscode.window.showWorkspaceFolderPick({ placeHolder: 'Pick Workspace Folder to which this setting should be applied' });
if (workspaceFolder) {
// 4) Get the configuration for the workspace folder
const configuration = vscode.workspace.getConfiguration('', workspaceFolder.uri);
// 5) Get the current value
const currentValue = configuration.get<{}>('conf.resource.insertEmptyLastLine');
const newValue = { ...currentValue, ...{ [value]: true } };
// 6) Update the configuration value
await configuration.update('conf.resource.insertEmptyLastLine', newValue, target.target);
}
} else {
// 3) Get the configuration
const configuration = vscode.workspace.getConfiguration();
// 4) Get the current value
const currentValue = configuration.get<{}>('conf.resource.insertEmptyLastLine');
const newValue = { ...currentValue, ...(value ? { [value]: true } : {}) };
// 3) Update the value in the target
await vscode.workspace.getConfiguration().update('conf.resource.insertEmptyLastLine', newValue, target.target);
}
}
} else {
// 2) Get the configuration
const configuration = vscode.workspace.getConfiguration();
// 3) Get the current value
const currentValue = configuration.get<{}>('conf.resource.insertEmptyLastLine');
const newValue = { ...currentValue, ...(value ? { [value]: true } : {}) };
// 4) Update the value in the User Settings
await vscode.workspace.getConfiguration().update('conf.resource.insertEmptyLastLine', newValue, vscode.ConfigurationTarget.Global);
}
});
let statusSizeDisposable: vscode.Disposable;
// Example: Reading language overridable configuration for a document
context.subscriptions.push(vscode.workspace.onDidOpenTextDocument(e => {
if (statusSizeDisposable) {
statusSizeDisposable.dispose();
}
// 1) Check if showing size is configured for current file
const showSize: any = vscode.workspace.getConfiguration('', e).get('conf.language.showSize');
// 3) If matches, insert empty last line
if (showSize) {
statusSizeDisposable = vscode.window.setStatusBarMessage(`${e.getText().length}`);
}
}));
// Example: Overriding configuration value for a language
context.subscriptions.push(vscode.commands.registerCommand('config.commands.overrideLanguageValue', async () => {
// 1) Getting the languge id
const languageId = await vscode.window.showInputBox({ placeHolder: 'Enter the language id' });
// 2) Update
vscode.workspace.getConfiguration('', { languageId: languageId! }).update('conf.language.showSize', true, false, true);
}));
// Example: Listening to configuration changes
context.subscriptions.push(vscode.workspace.onDidChangeConfiguration(e => {
if (e.affectsConfiguration('conf.resource.insertEmptyLastLine')) {
if (vscode.window.activeTextEditor) {
const currentDocument = vscode.window.activeTextEditor.document;
// 1) Get the configured glob pattern value for the current file
const value: any = vscode.workspace.getConfiguration('', currentDocument.uri).get('conf.resource.insertEmptyLastLine');
// 2) Check if the current resource matches the glob pattern
const matches = value[currentDocument.fileName];
// 3) If matches, insert empty last line
if (matches) {
vscode.window.showInformationMessage('An empty line will be added to the document ' + currentDocument.fileName);
}
}
}
// Check if a language configuration is changed for a text document
if (e.affectsConfiguration('conf.language.showSize', vscode.window.activeTextEditor?.document)) {
// noop
}
// Check if a language configuration is changed for a language
if (e.affectsConfiguration('conf.language.showSize', { languageId: 'typescript' })) {
// noop
}
}));
}

File diff suppressed because it is too large Load Diff

View File

@ -11,14 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.39.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:editor.printReferences"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -58,15 +56,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.39.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,31 +1,31 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { workspace, languages, window, commands, ExtensionContext, Disposable } from 'vscode';
import ContentProvider, { encodeLocation } from './provider';
export function activate(context: ExtensionContext) {
const provider = new ContentProvider();
// register content provider for scheme `references`
// register document link provider for scheme `references`
const providerRegistrations = Disposable.from(
workspace.registerTextDocumentContentProvider(ContentProvider.scheme, provider),
languages.registerDocumentLinkProvider({ scheme: ContentProvider.scheme }, provider)
);
// register command that crafts an uri with the `references` scheme,
// open the dynamic document, and shows it in the next editor
const commandRegistration = commands.registerTextEditorCommand('editor.printReferences', editor => {
const uri = encodeLocation(editor.document.uri, editor.selection.active);
return workspace.openTextDocument(uri).then(doc => window.showTextDocument(doc, editor.viewColumn! + 1));
});
context.subscriptions.push(
provider,
commandRegistration,
providerRegistrations
);
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import { workspace, languages, window, commands, ExtensionContext, Disposable } from 'vscode';
import ContentProvider, { encodeLocation } from './provider';
export function activate(context: ExtensionContext) {
const provider = new ContentProvider();
// register content provider for scheme `references`
// register document link provider for scheme `references`
const providerRegistrations = Disposable.from(
workspace.registerTextDocumentContentProvider(ContentProvider.scheme, provider),
languages.registerDocumentLinkProvider({ scheme: ContentProvider.scheme }, provider)
);
// register command that crafts an uri with the `references` scheme,
// open the dynamic document, and shows it in the next editor
const commandRegistration = commands.registerTextEditorCommand('editor.printReferences', editor => {
const uri = encodeLocation(editor.document.uri, editor.selection.active);
return workspace.openTextDocument(uri).then(doc => window.showTextDocument(doc, editor.viewColumn! + 1));
});
context.subscriptions.push(
provider,
commandRegistration,
providerRegistrations
);
}

View File

@ -1,99 +1,99 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
import ReferencesDocument from './referencesDocument';
export default class Provider implements vscode.TextDocumentContentProvider, vscode.DocumentLinkProvider {
static scheme = 'references';
private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
private _documents = new Map<string, ReferencesDocument>();
private _editorDecoration = vscode.window.createTextEditorDecorationType({ textDecoration: 'underline' });
private _subscriptions: vscode.Disposable;
constructor() {
// Listen to the `closeTextDocument`-event which means we must
// clear the corresponding model object - `ReferencesDocument`
this._subscriptions = vscode.workspace.onDidCloseTextDocument(doc => this._documents.delete(doc.uri.toString()));
}
dispose() {
this._subscriptions.dispose();
this._documents.clear();
this._editorDecoration.dispose();
this._onDidChange.dispose();
}
// Expose an event to signal changes of _virtual_ documents
// to the editor
get onDidChange() {
return this._onDidChange.event;
}
// Provider method that takes an uri of the `references`-scheme and
// resolves its content by (1) running the reference search command
// and (2) formatting the results
provideTextDocumentContent(uri: vscode.Uri): string | Thenable<string> {
// already loaded?
const document = this._documents.get(uri.toString());
if (document) {
return document.value;
}
// Decode target-uri and target-position from the provided uri and execute the
// `reference provider` command (https://code.visualstudio.com/api/references/commands).
// From the result create a references document which is in charge of loading,
// printing, and formatting references
const [target, pos] = decodeLocation(uri);
return vscode.commands.executeCommand<vscode.Location[]>('vscode.executeReferenceProvider', target, pos).then(locations => {
locations = locations || [];
// sort by locations and shuffle to begin from target resource
let idx = 0;
locations.sort(Provider._compareLocations).find((loc, i) => loc.uri.toString() === target.toString() && !!(idx = i) && true);
locations.push(...locations.splice(0, idx));
// create document and return its early state
const document = new ReferencesDocument(uri, locations, this._onDidChange);
this._documents.set(uri.toString(), document);
return document.value;
});
}
private static _compareLocations(a: vscode.Location, b: vscode.Location): number {
if (a.uri.toString() < b.uri.toString()) {
return -1;
} else if (a.uri.toString() > b.uri.toString()) {
return 1;
} else {
return a.range.start.compareTo(b.range.start);
}
}
provideDocumentLinks(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.DocumentLink[] | undefined {
// While building the virtual document we have already created the links.
// Those are composed from the range inside the document and a target uri
// to which they point
const doc = this._documents.get(document.uri.toString());
if (doc) {
return doc.links;
}
}
}
let seq = 0;
export function encodeLocation(uri: vscode.Uri, pos: vscode.Position): vscode.Uri {
const query = JSON.stringify([uri.toString(), pos.line, pos.character]);
return vscode.Uri.parse(`${Provider.scheme}:References.locations?${query}#${seq++}`);
}
export function decodeLocation(uri: vscode.Uri): [vscode.Uri, vscode.Position] {
const [target, line, character] = <[string, number, number]>JSON.parse(uri.query);
return [vscode.Uri.parse(target), new vscode.Position(line, character)];
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
import ReferencesDocument from './referencesDocument';
export default class Provider implements vscode.TextDocumentContentProvider, vscode.DocumentLinkProvider {
static scheme = 'references';
private _onDidChange = new vscode.EventEmitter<vscode.Uri>();
private _documents = new Map<string, ReferencesDocument>();
private _editorDecoration = vscode.window.createTextEditorDecorationType({ textDecoration: 'underline' });
private _subscriptions: vscode.Disposable;
constructor() {
// Listen to the `closeTextDocument`-event which means we must
// clear the corresponding model object - `ReferencesDocument`
this._subscriptions = vscode.workspace.onDidCloseTextDocument(doc => this._documents.delete(doc.uri.toString()));
}
dispose() {
this._subscriptions.dispose();
this._documents.clear();
this._editorDecoration.dispose();
this._onDidChange.dispose();
}
// Expose an event to signal changes of _virtual_ documents
// to the editor
get onDidChange() {
return this._onDidChange.event;
}
// Provider method that takes an uri of the `references`-scheme and
// resolves its content by (1) running the reference search command
// and (2) formatting the results
provideTextDocumentContent(uri: vscode.Uri): string | Thenable<string> {
// already loaded?
const document = this._documents.get(uri.toString());
if (document) {
return document.value;
}
// Decode target-uri and target-position from the provided uri and execute the
// `reference provider` command (https://code.visualstudio.com/api/references/commands).
// From the result create a references document which is in charge of loading,
// printing, and formatting references
const [target, pos] = decodeLocation(uri);
return vscode.commands.executeCommand<vscode.Location[]>('vscode.executeReferenceProvider', target, pos).then(locations => {
locations = locations || [];
// sort by locations and shuffle to begin from target resource
let idx = 0;
locations.sort(Provider._compareLocations).find((loc, i) => loc.uri.toString() === target.toString() && !!(idx = i) && true);
locations.push(...locations.splice(0, idx));
// create document and return its early state
const document = new ReferencesDocument(uri, locations, this._onDidChange);
this._documents.set(uri.toString(), document);
return document.value;
});
}
private static _compareLocations(a: vscode.Location, b: vscode.Location): number {
if (a.uri.toString() < b.uri.toString()) {
return -1;
} else if (a.uri.toString() > b.uri.toString()) {
return 1;
} else {
return a.range.start.compareTo(b.range.start);
}
}
provideDocumentLinks(document: vscode.TextDocument, token: vscode.CancellationToken): vscode.DocumentLink[] | undefined {
// While building the virtual document we have already created the links.
// Those are composed from the range inside the document and a target uri
// to which they point
const doc = this._documents.get(document.uri.toString());
if (doc) {
return doc.links;
}
}
}
let seq = 0;
export function encodeLocation(uri: vscode.Uri, pos: vscode.Position): vscode.Uri {
const query = JSON.stringify([uri.toString(), pos.line, pos.character]);
return vscode.Uri.parse(`${Provider.scheme}:References.locations?${query}#${seq++}`);
}
export function decodeLocation(uri: vscode.Uri): [vscode.Uri, vscode.Position] {
const [target, line, character] = <[string, number, number]>JSON.parse(uri.query);
return [vscode.Uri.parse(target), new vscode.Position(line, character)];
}

View File

@ -1,113 +1,113 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
export default class ReferencesDocument {
private readonly _uri: vscode.Uri;
private readonly _emitter: vscode.EventEmitter<vscode.Uri>;
private readonly _locations: vscode.Location[];
private readonly _lines: string[];
private readonly _links: vscode.DocumentLink[];
constructor(uri: vscode.Uri, locations: vscode.Location[], emitter: vscode.EventEmitter<vscode.Uri>) {
this._uri = uri;
this._locations = locations;
// The ReferencesDocument has access to the event emitter from
// the containing provider. This allows it to signal changes
this._emitter = emitter;
// Start with printing a header and start resolving
this._lines = [`Found ${this._locations.length} references`];
this._links = [];
this._populate();
}
get value() {
return this._lines.join('\n');
}
get links() {
return this._links;
}
private async _populate() {
// group all locations by files containing them
const groups: vscode.Location[][] = [];
let group: vscode.Location[] = [];
for (const loc of this._locations) {
if (group.length === 0 || group[0].uri.toString() !== loc.uri.toString()) {
group = [];
groups.push(group);
}
group.push(loc);
}
//
for (const group of groups) {
const uri = group[0].uri;
const ranges = group.map(loc => loc.range);
await this._fetchAndFormatLocations(uri, ranges);
this._emitter.fire(this._uri);
}
}
private async _fetchAndFormatLocations(uri: vscode.Uri, ranges: vscode.Range[]): Promise<void> {
// Fetch the document denoted by the uri and format the matches
// with leading and trailing content form the document. Make sure
// to not duplicate lines
try {
const doc = await vscode.workspace.openTextDocument(uri);
this._lines.push('', uri.toString());
for (let i = 0; i < ranges.length; i++) {
const { start: { line } } = ranges[i];
this._appendLeading(doc, line, ranges[i - 1]);
this._appendMatch(doc, line, ranges[i], uri);
this._appendTrailing(doc, line, ranges[i + 1]);
}
} catch (err) {
this._lines.push('', `Failed to load '${uri.toString()}'\n\n${String(err)}`, '');
}
}
private _appendLeading(doc: vscode.TextDocument, line: number, previous: vscode.Range): void {
let from = Math.max(0, line - 3, previous && previous.end.line || 0);
while (++from < line) {
const text = doc.lineAt(from).text;
this._lines.push(` ${from + 1}` + (text && ` ${text}`));
}
}
private _appendMatch(doc: vscode.TextDocument, line: number, match: vscode.Range, target: vscode.Uri) {
const text = doc.lineAt(line).text;
const preamble = ` ${line + 1}: `;
// Append line, use new length of lines-array as line number
// for a link that point to the reference
const len = this._lines.push(preamble + text);
// Create a document link that will reveal the reference
const linkRange = new vscode.Range(len - 1, preamble.length + match.start.character, len - 1, preamble.length + match.end.character);
const linkTarget = target.with({ fragment: String(1 + match.start.line) });
this._links.push(new vscode.DocumentLink(linkRange, linkTarget));
}
private _appendTrailing(doc: vscode.TextDocument, line: number, next: vscode.Range): void {
const to = Math.min(doc.lineCount, line + 3);
if (next && next.start.line - to <= 2) {
return; // next is too close, _appendLeading does the work
}
while (++line < to) {
const text = doc.lineAt(line).text;
this._lines.push(` ${line + 1}` + (text && ` ${text}`));
}
if (next) {
this._lines.push(` ...`);
}
}
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
import * as vscode from 'vscode';
export default class ReferencesDocument {
private readonly _uri: vscode.Uri;
private readonly _emitter: vscode.EventEmitter<vscode.Uri>;
private readonly _locations: vscode.Location[];
private readonly _lines: string[];
private readonly _links: vscode.DocumentLink[];
constructor(uri: vscode.Uri, locations: vscode.Location[], emitter: vscode.EventEmitter<vscode.Uri>) {
this._uri = uri;
this._locations = locations;
// The ReferencesDocument has access to the event emitter from
// the containing provider. This allows it to signal changes
this._emitter = emitter;
// Start with printing a header and start resolving
this._lines = [`Found ${this._locations.length} references`];
this._links = [];
this._populate();
}
get value() {
return this._lines.join('\n');
}
get links() {
return this._links;
}
private async _populate() {
// group all locations by files containing them
const groups: vscode.Location[][] = [];
let group: vscode.Location[] = [];
for (const loc of this._locations) {
if (group.length === 0 || group[0].uri.toString() !== loc.uri.toString()) {
group = [];
groups.push(group);
}
group.push(loc);
}
//
for (const group of groups) {
const uri = group[0].uri;
const ranges = group.map(loc => loc.range);
await this._fetchAndFormatLocations(uri, ranges);
this._emitter.fire(this._uri);
}
}
private async _fetchAndFormatLocations(uri: vscode.Uri, ranges: vscode.Range[]): Promise<void> {
// Fetch the document denoted by the uri and format the matches
// with leading and trailing content form the document. Make sure
// to not duplicate lines
try {
const doc = await vscode.workspace.openTextDocument(uri);
this._lines.push('', uri.toString());
for (let i = 0; i < ranges.length; i++) {
const { start: { line } } = ranges[i];
this._appendLeading(doc, line, ranges[i - 1]);
this._appendMatch(doc, line, ranges[i], uri);
this._appendTrailing(doc, line, ranges[i + 1]);
}
} catch (err) {
this._lines.push('', `Failed to load '${uri.toString()}'\n\n${String(err)}`, '');
}
}
private _appendLeading(doc: vscode.TextDocument, line: number, previous: vscode.Range): void {
let from = Math.max(0, line - 3, previous && previous.end.line || 0);
while (++from < line) {
const text = doc.lineAt(from).text;
this._lines.push(` ${from + 1}` + (text && ` ${text}`));
}
}
private _appendMatch(doc: vscode.TextDocument, line: number, match: vscode.Range, target: vscode.Uri) {
const text = doc.lineAt(line).text;
const preamble = ` ${line + 1}: `;
// Append line, use new length of lines-array as line number
// for a link that point to the reference
const len = this._lines.push(preamble + text);
// Create a document link that will reveal the reference
const linkRange = new vscode.Range(len - 1, preamble.length + match.start.character, len - 1, preamble.length + match.end.character);
const linkTarget = target.with({ fragment: String(1 + match.start.line) });
this._links.push(new vscode.DocumentLink(linkRange, linkTarget));
}
private _appendTrailing(doc: vscode.TextDocument, line: number, next: vscode.Range): void {
const to = Math.min(doc.lineCount, line + 3);
if (next && next.start.line - to <= 2) {
return; // next is too close, _appendLeading does the work
}
while (++line < to) {
const text = doc.lineAt(line).text;
this._lines.push(` ${line + 1}` + (text && ` ${text}`));
}
if (next) {
this._lines.push(` ...`);
}
}
}

View File

@ -1,2 +1 @@
src/vscode.proposed.d.ts
media/*.js

File diff suppressed because it is too large Load Diff

View File

@ -11,16 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.65.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCustomEditor:catCustoms.catScratch",
"onCustomEditor:catCustoms.pawDraw",
"onCommand:catCustoms.pawDraw.new"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"customEditors": [
@ -54,15 +50,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -w -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.65.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,205 +1,205 @@
import * as vscode from 'vscode';
import { getNonce } from './util';
/**
* Provider for cat scratch editors.
*
* Cat scratch editors are used for `.cscratch` files, which are just json files.
* To get started, run this extension and open an empty `.cscratch` file in VS Code.
*
* This provider demonstrates:
*
* - Setting up the initial webview for a custom editor.
* - Loading scripts and styles in a custom editor.
* - Synchronizing changes between a text document and a custom editor.
*/
export class CatScratchEditorProvider implements vscode.CustomTextEditorProvider {
public static register(context: vscode.ExtensionContext): vscode.Disposable {
const provider = new CatScratchEditorProvider(context);
const providerRegistration = vscode.window.registerCustomEditorProvider(CatScratchEditorProvider.viewType, provider);
return providerRegistration;
}
private static readonly viewType = 'catCustoms.catScratch';
private static readonly scratchCharacters = ['😸', '😹', '😺', '😻', '😼', '😽', '😾', '🙀', '😿', '🐱'];
constructor(
private readonly context: vscode.ExtensionContext
) { }
/**
* Called when our custom editor is opened.
*
*
*/
public async resolveCustomTextEditor(
document: vscode.TextDocument,
webviewPanel: vscode.WebviewPanel,
_token: vscode.CancellationToken
): Promise<void> {
// Setup initial content for the webview
webviewPanel.webview.options = {
enableScripts: true,
};
webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
function updateWebview() {
webviewPanel.webview.postMessage({
type: 'update',
text: document.getText(),
});
}
// Hook up event handlers so that we can synchronize the webview with the text document.
//
// The text document acts as our model, so we have to sync change in the document to our
// editor and sync changes in the editor back to the document.
//
// Remember that a single text document can also be shared between multiple custom
// editors (this happens for example when you split a custom editor)
const changeDocumentSubscription = vscode.workspace.onDidChangeTextDocument(e => {
if (e.document.uri.toString() === document.uri.toString()) {
updateWebview();
}
});
// Make sure we get rid of the listener when our editor is closed.
webviewPanel.onDidDispose(() => {
changeDocumentSubscription.dispose();
});
// Receive message from the webview.
webviewPanel.webview.onDidReceiveMessage(e => {
switch (e.type) {
case 'add':
this.addNewScratch(document);
return;
case 'delete':
this.deleteScratch(document, e.id);
return;
}
});
updateWebview();
}
/**
* Get the static html used for the editor webviews.
*/
private getHtmlForWebview(webview: vscode.Webview): string {
// Local path to script and css for the webview
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'catScratch.js'));
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'catScratch.css'));
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return /* html */`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${webview.cspSource}; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet" />
<link href="${styleVSCodeUri}" rel="stylesheet" />
<link href="${styleMainUri}" rel="stylesheet" />
<title>Cat Scratch</title>
</head>
<body>
<div class="notes">
<div class="add-button">
<button>Scratch!</button>
</div>
</div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
/**
* Add a new scratch to the current document.
*/
private addNewScratch(document: vscode.TextDocument) {
const json = this.getDocumentAsJson(document);
const character = CatScratchEditorProvider.scratchCharacters[Math.floor(Math.random() * CatScratchEditorProvider.scratchCharacters.length)];
json.scratches = [
...(Array.isArray(json.scratches) ? json.scratches : []),
{
id: getNonce(),
text: character,
created: Date.now(),
}
];
return this.updateTextDocument(document, json);
}
/**
* Delete an existing scratch from a document.
*/
private deleteScratch(document: vscode.TextDocument, id: string) {
const json = this.getDocumentAsJson(document);
if (!Array.isArray(json.scratches)) {
return;
}
json.scratches = json.scratches.filter((note: any) => note.id !== id);
return this.updateTextDocument(document, json);
}
/**
* Try to get a current document as json text.
*/
private getDocumentAsJson(document: vscode.TextDocument): any {
const text = document.getText();
if (text.trim().length === 0) {
return {};
}
try {
return JSON.parse(text);
} catch {
throw new Error('Could not get document as json. Content is not valid json');
}
}
/**
* Write out the json to a given document.
*/
private updateTextDocument(document: vscode.TextDocument, json: any) {
const edit = new vscode.WorkspaceEdit();
// Just replace the entire document every time for this example extension.
// A more complete extension should compute minimal edits instead.
edit.replace(
document.uri,
new vscode.Range(0, 0, document.lineCount, 0),
JSON.stringify(json, null, 2));
return vscode.workspace.applyEdit(edit);
}
}
import * as vscode from 'vscode';
import { getNonce } from './util';
/**
* Provider for cat scratch editors.
*
* Cat scratch editors are used for `.cscratch` files, which are just json files.
* To get started, run this extension and open an empty `.cscratch` file in VS Code.
*
* This provider demonstrates:
*
* - Setting up the initial webview for a custom editor.
* - Loading scripts and styles in a custom editor.
* - Synchronizing changes between a text document and a custom editor.
*/
export class CatScratchEditorProvider implements vscode.CustomTextEditorProvider {
public static register(context: vscode.ExtensionContext): vscode.Disposable {
const provider = new CatScratchEditorProvider(context);
const providerRegistration = vscode.window.registerCustomEditorProvider(CatScratchEditorProvider.viewType, provider);
return providerRegistration;
}
private static readonly viewType = 'catCustoms.catScratch';
private static readonly scratchCharacters = ['😸', '😹', '😺', '😻', '😼', '😽', '😾', '🙀', '😿', '🐱'];
constructor(
private readonly context: vscode.ExtensionContext
) { }
/**
* Called when our custom editor is opened.
*
*
*/
public async resolveCustomTextEditor(
document: vscode.TextDocument,
webviewPanel: vscode.WebviewPanel,
_token: vscode.CancellationToken
): Promise<void> {
// Setup initial content for the webview
webviewPanel.webview.options = {
enableScripts: true,
};
webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
function updateWebview() {
webviewPanel.webview.postMessage({
type: 'update',
text: document.getText(),
});
}
// Hook up event handlers so that we can synchronize the webview with the text document.
//
// The text document acts as our model, so we have to sync change in the document to our
// editor and sync changes in the editor back to the document.
//
// Remember that a single text document can also be shared between multiple custom
// editors (this happens for example when you split a custom editor)
const changeDocumentSubscription = vscode.workspace.onDidChangeTextDocument(e => {
if (e.document.uri.toString() === document.uri.toString()) {
updateWebview();
}
});
// Make sure we get rid of the listener when our editor is closed.
webviewPanel.onDidDispose(() => {
changeDocumentSubscription.dispose();
});
// Receive message from the webview.
webviewPanel.webview.onDidReceiveMessage(e => {
switch (e.type) {
case 'add':
this.addNewScratch(document);
return;
case 'delete':
this.deleteScratch(document, e.id);
return;
}
});
updateWebview();
}
/**
* Get the static html used for the editor webviews.
*/
private getHtmlForWebview(webview: vscode.Webview): string {
// Local path to script and css for the webview
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'catScratch.js'));
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(
this.context.extensionUri, 'media', 'catScratch.css'));
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return /* html */`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${webview.cspSource}; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet" />
<link href="${styleVSCodeUri}" rel="stylesheet" />
<link href="${styleMainUri}" rel="stylesheet" />
<title>Cat Scratch</title>
</head>
<body>
<div class="notes">
<div class="add-button">
<button>Scratch!</button>
</div>
</div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
/**
* Add a new scratch to the current document.
*/
private addNewScratch(document: vscode.TextDocument) {
const json = this.getDocumentAsJson(document);
const character = CatScratchEditorProvider.scratchCharacters[Math.floor(Math.random() * CatScratchEditorProvider.scratchCharacters.length)];
json.scratches = [
...(Array.isArray(json.scratches) ? json.scratches : []),
{
id: getNonce(),
text: character,
created: Date.now(),
}
];
return this.updateTextDocument(document, json);
}
/**
* Delete an existing scratch from a document.
*/
private deleteScratch(document: vscode.TextDocument, id: string) {
const json = this.getDocumentAsJson(document);
if (!Array.isArray(json.scratches)) {
return;
}
json.scratches = json.scratches.filter((note: any) => note.id !== id);
return this.updateTextDocument(document, json);
}
/**
* Try to get a current document as json text.
*/
private getDocumentAsJson(document: vscode.TextDocument): any {
const text = document.getText();
if (text.trim().length === 0) {
return {};
}
try {
return JSON.parse(text);
} catch {
throw new Error('Could not get document as json. Content is not valid json');
}
}
/**
* Write out the json to a given document.
*/
private updateTextDocument(document: vscode.TextDocument, json: any) {
const edit = new vscode.WorkspaceEdit();
// Just replace the entire document every time for this example extension.
// A more complete extension should compute minimal edits instead.
edit.replace(
document.uri,
new vscode.Range(0, 0, document.lineCount, 0),
JSON.stringify(json, null, 2));
return vscode.workspace.applyEdit(edit);
}
}

View File

@ -1,37 +1,37 @@
import * as vscode from 'vscode';
export function disposeAll(disposables: vscode.Disposable[]): void {
while (disposables.length) {
const item = disposables.pop();
if (item) {
item.dispose();
}
}
}
export abstract class Disposable {
private _isDisposed = false;
protected _disposables: vscode.Disposable[] = [];
public dispose(): any {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
disposeAll(this._disposables);
}
protected _register<T extends vscode.Disposable>(value: T): T {
if (this._isDisposed) {
value.dispose();
} else {
this._disposables.push(value);
}
return value;
}
protected get isDisposed(): boolean {
return this._isDisposed;
}
import * as vscode from 'vscode';
export function disposeAll(disposables: vscode.Disposable[]): void {
while (disposables.length) {
const item = disposables.pop();
if (item) {
item.dispose();
}
}
}
export abstract class Disposable {
private _isDisposed = false;
protected _disposables: vscode.Disposable[] = [];
public dispose(): any {
if (this._isDisposed) {
return;
}
this._isDisposed = true;
disposeAll(this._disposables);
}
protected _register<T extends vscode.Disposable>(value: T): T {
if (this._isDisposed) {
value.dispose();
} else {
this._disposables.push(value);
}
return value;
}
protected get isDisposed(): boolean {
return this._isDisposed;
}
}

View File

@ -1,9 +1,9 @@
import * as vscode from 'vscode';
import { CatScratchEditorProvider } from './catScratchEditor';
import { PawDrawEditorProvider } from './pawDrawEditor';
export function activate(context: vscode.ExtensionContext) {
// Register our custom editor providers
context.subscriptions.push(CatScratchEditorProvider.register(context));
context.subscriptions.push(PawDrawEditorProvider.register(context));
}
import * as vscode from 'vscode';
import { CatScratchEditorProvider } from './catScratchEditor';
import { PawDrawEditorProvider } from './pawDrawEditor';
export function activate(context: vscode.ExtensionContext) {
// Register our custom editor providers
context.subscriptions.push(CatScratchEditorProvider.register(context));
context.subscriptions.push(PawDrawEditorProvider.register(context));
}

View File

@ -1,456 +1,456 @@
import * as vscode from 'vscode';
import { Disposable, disposeAll } from './dispose';
import { getNonce } from './util';
/**
* Define the type of edits used in paw draw files.
*/
interface PawDrawEdit {
readonly color: string;
readonly stroke: ReadonlyArray<[number, number]>;
}
interface PawDrawDocumentDelegate {
getFileData(): Promise<Uint8Array>;
}
/**
* Define the document (the data model) used for paw draw files.
*/
class PawDrawDocument extends Disposable implements vscode.CustomDocument {
static async create(
uri: vscode.Uri,
backupId: string | undefined,
delegate: PawDrawDocumentDelegate,
): Promise<PawDrawDocument | PromiseLike<PawDrawDocument>> {
// If we have a backup, read that. Otherwise read the resource from the workspace
const dataFile = typeof backupId === 'string' ? vscode.Uri.parse(backupId) : uri;
const fileData = await PawDrawDocument.readFile(dataFile);
return new PawDrawDocument(uri, fileData, delegate);
}
private static async readFile(uri: vscode.Uri): Promise<Uint8Array> {
if (uri.scheme === 'untitled') {
return new Uint8Array();
}
return new Uint8Array(await vscode.workspace.fs.readFile(uri));
}
private readonly _uri: vscode.Uri;
private _documentData: Uint8Array;
private _edits: Array<PawDrawEdit> = [];
private _savedEdits: Array<PawDrawEdit> = [];
private readonly _delegate: PawDrawDocumentDelegate;
private constructor(
uri: vscode.Uri,
initialContent: Uint8Array,
delegate: PawDrawDocumentDelegate
) {
super();
this._uri = uri;
this._documentData = initialContent;
this._delegate = delegate;
}
public get uri() { return this._uri; }
public get documentData(): Uint8Array { return this._documentData; }
private readonly _onDidDispose = this._register(new vscode.EventEmitter<void>());
/**
* Fired when the document is disposed of.
*/
public readonly onDidDispose = this._onDidDispose.event;
private readonly _onDidChangeDocument = this._register(new vscode.EventEmitter<{
readonly content?: Uint8Array;
readonly edits: readonly PawDrawEdit[];
}>());
/**
* Fired to notify webviews that the document has changed.
*/
public readonly onDidChangeContent = this._onDidChangeDocument.event;
private readonly _onDidChange = this._register(new vscode.EventEmitter<{
readonly label: string,
undo(): void,
redo(): void,
}>());
/**
* Fired to tell VS Code that an edit has occurred in the document.
*
* This updates the document's dirty indicator.
*/
public readonly onDidChange = this._onDidChange.event;
/**
* Called by VS Code when there are no more references to the document.
*
* This happens when all editors for it have been closed.
*/
dispose(): void {
this._onDidDispose.fire();
super.dispose();
}
/**
* Called when the user edits the document in a webview.
*
* This fires an event to notify VS Code that the document has been edited.
*/
makeEdit(edit: PawDrawEdit) {
this._edits.push(edit);
this._onDidChange.fire({
label: 'Stroke',
undo: async () => {
this._edits.pop();
this._onDidChangeDocument.fire({
edits: this._edits,
});
},
redo: async () => {
this._edits.push(edit);
this._onDidChangeDocument.fire({
edits: this._edits,
});
}
});
}
/**
* Called by VS Code when the user saves the document.
*/
async save(cancellation: vscode.CancellationToken): Promise<void> {
await this.saveAs(this.uri, cancellation);
this._savedEdits = Array.from(this._edits);
}
/**
* Called by VS Code when the user saves the document to a new location.
*/
async saveAs(targetResource: vscode.Uri, cancellation: vscode.CancellationToken): Promise<void> {
const fileData = await this._delegate.getFileData();
if (cancellation.isCancellationRequested) {
return;
}
await vscode.workspace.fs.writeFile(targetResource, fileData);
}
/**
* Called by VS Code when the user calls `revert` on a document.
*/
async revert(_cancellation: vscode.CancellationToken): Promise<void> {
const diskContent = await PawDrawDocument.readFile(this.uri);
this._documentData = diskContent;
this._edits = this._savedEdits;
this._onDidChangeDocument.fire({
content: diskContent,
edits: this._edits,
});
}
/**
* Called by VS Code to backup the edited document.
*
* These backups are used to implement hot exit.
*/
async backup(destination: vscode.Uri, cancellation: vscode.CancellationToken): Promise<vscode.CustomDocumentBackup> {
await this.saveAs(destination, cancellation);
return {
id: destination.toString(),
delete: async () => {
try {
await vscode.workspace.fs.delete(destination);
} catch {
// noop
}
}
};
}
}
/**
* Provider for paw draw editors.
*
* Paw draw editors are used for `.pawDraw` files, which are just `.png` files with a different file extension.
*
* This provider demonstrates:
*
* - How to implement a custom editor for binary files.
* - Setting up the initial webview for a custom editor.
* - Loading scripts and styles in a custom editor.
* - Communication between VS Code and the custom editor.
* - Using CustomDocuments to store information that is shared between multiple custom editors.
* - Implementing save, undo, redo, and revert.
* - Backing up a custom editor.
*/
export class PawDrawEditorProvider implements vscode.CustomEditorProvider<PawDrawDocument> {
private static newPawDrawFileId = 1;
public static register(context: vscode.ExtensionContext): vscode.Disposable {
vscode.commands.registerCommand('catCustoms.pawDraw.new', () => {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
vscode.window.showErrorMessage("Creating new Paw Draw files currently requires opening a workspace");
return;
}
const uri = vscode.Uri.joinPath(workspaceFolders[0].uri, `new-${PawDrawEditorProvider.newPawDrawFileId++}.pawdraw`)
.with({ scheme: 'untitled' });
vscode.commands.executeCommand('vscode.openWith', uri, PawDrawEditorProvider.viewType);
});
return vscode.window.registerCustomEditorProvider(
PawDrawEditorProvider.viewType,
new PawDrawEditorProvider(context),
{
// For this demo extension, we enable `retainContextWhenHidden` which keeps the
// webview alive even when it is not visible. You should avoid using this setting
// unless is absolutely required as it does have memory overhead.
webviewOptions: {
retainContextWhenHidden: true,
},
supportsMultipleEditorsPerDocument: false,
});
}
private static readonly viewType = 'catCustoms.pawDraw';
/**
* Tracks all known webviews
*/
private readonly webviews = new WebviewCollection();
constructor(
private readonly _context: vscode.ExtensionContext
) { }
//#region CustomEditorProvider
async openCustomDocument(
uri: vscode.Uri,
openContext: { backupId?: string },
_token: vscode.CancellationToken
): Promise<PawDrawDocument> {
const document: PawDrawDocument = await PawDrawDocument.create(uri, openContext.backupId, {
getFileData: async () => {
const webviewsForDocument = Array.from(this.webviews.get(document.uri));
if (!webviewsForDocument.length) {
throw new Error('Could not find webview to save for');
}
const panel = webviewsForDocument[0];
const response = await this.postMessageWithResponse<number[]>(panel, 'getFileData', {});
return new Uint8Array(response);
}
});
const listeners: vscode.Disposable[] = [];
listeners.push(document.onDidChange(e => {
// Tell VS Code that the document has been edited by the use.
this._onDidChangeCustomDocument.fire({
document,
...e,
});
}));
listeners.push(document.onDidChangeContent(e => {
// Update all webviews when the document changes
for (const webviewPanel of this.webviews.get(document.uri)) {
this.postMessage(webviewPanel, 'update', {
edits: e.edits,
content: e.content,
});
}
}));
document.onDidDispose(() => disposeAll(listeners));
return document;
}
async resolveCustomEditor(
document: PawDrawDocument,
webviewPanel: vscode.WebviewPanel,
_token: vscode.CancellationToken
): Promise<void> {
// Add the webview to our internal set of active webviews
this.webviews.add(document.uri, webviewPanel);
// Setup initial content for the webview
webviewPanel.webview.options = {
enableScripts: true,
};
webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
webviewPanel.webview.onDidReceiveMessage(e => this.onMessage(document, e));
// Wait for the webview to be properly ready before we init
webviewPanel.webview.onDidReceiveMessage(e => {
if (e.type === 'ready') {
if (document.uri.scheme === 'untitled') {
this.postMessage(webviewPanel, 'init', {
untitled: true,
editable: true,
});
} else {
const editable = vscode.workspace.fs.isWritableFileSystem(document.uri.scheme);
this.postMessage(webviewPanel, 'init', {
value: document.documentData,
editable,
});
}
}
});
}
private readonly _onDidChangeCustomDocument = new vscode.EventEmitter<vscode.CustomDocumentEditEvent<PawDrawDocument>>();
public readonly onDidChangeCustomDocument = this._onDidChangeCustomDocument.event;
public saveCustomDocument(document: PawDrawDocument, cancellation: vscode.CancellationToken): Thenable<void> {
return document.save(cancellation);
}
public saveCustomDocumentAs(document: PawDrawDocument, destination: vscode.Uri, cancellation: vscode.CancellationToken): Thenable<void> {
return document.saveAs(destination, cancellation);
}
public revertCustomDocument(document: PawDrawDocument, cancellation: vscode.CancellationToken): Thenable<void> {
return document.revert(cancellation);
}
public backupCustomDocument(document: PawDrawDocument, context: vscode.CustomDocumentBackupContext, cancellation: vscode.CancellationToken): Thenable<vscode.CustomDocumentBackup> {
return document.backup(context.destination, cancellation);
}
//#endregion
/**
* Get the static HTML used for in our editor's webviews.
*/
private getHtmlForWebview(webview: vscode.Webview): string {
// Local path to script and css for the webview
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'pawDraw.js'));
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'pawDraw.css'));
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return /* html */`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${webview.cspSource} blob:; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet" />
<link href="${styleVSCodeUri}" rel="stylesheet" />
<link href="${styleMainUri}" rel="stylesheet" />
<title>Paw Draw</title>
</head>
<body>
<div class="drawing-canvas"></div>
<div class="drawing-controls">
<button data-color="black" class="black active" title="Black"></button>
<button data-color="white" class="white" title="White"></button>
<button data-color="red" class="red" title="Red"></button>
<button data-color="green" class="green" title="Green"></button>
<button data-color="blue" class="blue" title="Blue"></button>
</div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
private _requestId = 1;
private readonly _callbacks = new Map<number, (response: any) => void>();
private postMessageWithResponse<R = unknown>(panel: vscode.WebviewPanel, type: string, body: any): Promise<R> {
const requestId = this._requestId++;
const p = new Promise<R>(resolve => this._callbacks.set(requestId, resolve));
panel.webview.postMessage({ type, requestId, body });
return p;
}
private postMessage(panel: vscode.WebviewPanel, type: string, body: any): void {
panel.webview.postMessage({ type, body });
}
private onMessage(document: PawDrawDocument, message: any) {
switch (message.type) {
case 'stroke':
document.makeEdit(message as PawDrawEdit);
return;
case 'response':
{
const callback = this._callbacks.get(message.requestId);
callback?.(message.body);
return;
}
}
}
}
/**
* Tracks all webviews.
*/
class WebviewCollection {
private readonly _webviews = new Set<{
readonly resource: string;
readonly webviewPanel: vscode.WebviewPanel;
}>();
/**
* Get all known webviews for a given uri.
*/
public *get(uri: vscode.Uri): Iterable<vscode.WebviewPanel> {
const key = uri.toString();
for (const entry of this._webviews) {
if (entry.resource === key) {
yield entry.webviewPanel;
}
}
}
/**
* Add a new webview to the collection.
*/
public add(uri: vscode.Uri, webviewPanel: vscode.WebviewPanel) {
const entry = { resource: uri.toString(), webviewPanel };
this._webviews.add(entry);
webviewPanel.onDidDispose(() => {
this._webviews.delete(entry);
});
}
}
import * as vscode from 'vscode';
import { Disposable, disposeAll } from './dispose';
import { getNonce } from './util';
/**
* Define the type of edits used in paw draw files.
*/
interface PawDrawEdit {
readonly color: string;
readonly stroke: ReadonlyArray<[number, number]>;
}
interface PawDrawDocumentDelegate {
getFileData(): Promise<Uint8Array>;
}
/**
* Define the document (the data model) used for paw draw files.
*/
class PawDrawDocument extends Disposable implements vscode.CustomDocument {
static async create(
uri: vscode.Uri,
backupId: string | undefined,
delegate: PawDrawDocumentDelegate,
): Promise<PawDrawDocument | PromiseLike<PawDrawDocument>> {
// If we have a backup, read that. Otherwise read the resource from the workspace
const dataFile = typeof backupId === 'string' ? vscode.Uri.parse(backupId) : uri;
const fileData = await PawDrawDocument.readFile(dataFile);
return new PawDrawDocument(uri, fileData, delegate);
}
private static async readFile(uri: vscode.Uri): Promise<Uint8Array> {
if (uri.scheme === 'untitled') {
return new Uint8Array();
}
return new Uint8Array(await vscode.workspace.fs.readFile(uri));
}
private readonly _uri: vscode.Uri;
private _documentData: Uint8Array;
private _edits: Array<PawDrawEdit> = [];
private _savedEdits: Array<PawDrawEdit> = [];
private readonly _delegate: PawDrawDocumentDelegate;
private constructor(
uri: vscode.Uri,
initialContent: Uint8Array,
delegate: PawDrawDocumentDelegate
) {
super();
this._uri = uri;
this._documentData = initialContent;
this._delegate = delegate;
}
public get uri() { return this._uri; }
public get documentData(): Uint8Array { return this._documentData; }
private readonly _onDidDispose = this._register(new vscode.EventEmitter<void>());
/**
* Fired when the document is disposed of.
*/
public readonly onDidDispose = this._onDidDispose.event;
private readonly _onDidChangeDocument = this._register(new vscode.EventEmitter<{
readonly content?: Uint8Array;
readonly edits: readonly PawDrawEdit[];
}>());
/**
* Fired to notify webviews that the document has changed.
*/
public readonly onDidChangeContent = this._onDidChangeDocument.event;
private readonly _onDidChange = this._register(new vscode.EventEmitter<{
readonly label: string,
undo(): void,
redo(): void,
}>());
/**
* Fired to tell VS Code that an edit has occurred in the document.
*
* This updates the document's dirty indicator.
*/
public readonly onDidChange = this._onDidChange.event;
/**
* Called by VS Code when there are no more references to the document.
*
* This happens when all editors for it have been closed.
*/
dispose(): void {
this._onDidDispose.fire();
super.dispose();
}
/**
* Called when the user edits the document in a webview.
*
* This fires an event to notify VS Code that the document has been edited.
*/
makeEdit(edit: PawDrawEdit) {
this._edits.push(edit);
this._onDidChange.fire({
label: 'Stroke',
undo: async () => {
this._edits.pop();
this._onDidChangeDocument.fire({
edits: this._edits,
});
},
redo: async () => {
this._edits.push(edit);
this._onDidChangeDocument.fire({
edits: this._edits,
});
}
});
}
/**
* Called by VS Code when the user saves the document.
*/
async save(cancellation: vscode.CancellationToken): Promise<void> {
await this.saveAs(this.uri, cancellation);
this._savedEdits = Array.from(this._edits);
}
/**
* Called by VS Code when the user saves the document to a new location.
*/
async saveAs(targetResource: vscode.Uri, cancellation: vscode.CancellationToken): Promise<void> {
const fileData = await this._delegate.getFileData();
if (cancellation.isCancellationRequested) {
return;
}
await vscode.workspace.fs.writeFile(targetResource, fileData);
}
/**
* Called by VS Code when the user calls `revert` on a document.
*/
async revert(_cancellation: vscode.CancellationToken): Promise<void> {
const diskContent = await PawDrawDocument.readFile(this.uri);
this._documentData = diskContent;
this._edits = this._savedEdits;
this._onDidChangeDocument.fire({
content: diskContent,
edits: this._edits,
});
}
/**
* Called by VS Code to backup the edited document.
*
* These backups are used to implement hot exit.
*/
async backup(destination: vscode.Uri, cancellation: vscode.CancellationToken): Promise<vscode.CustomDocumentBackup> {
await this.saveAs(destination, cancellation);
return {
id: destination.toString(),
delete: async () => {
try {
await vscode.workspace.fs.delete(destination);
} catch {
// noop
}
}
};
}
}
/**
* Provider for paw draw editors.
*
* Paw draw editors are used for `.pawDraw` files, which are just `.png` files with a different file extension.
*
* This provider demonstrates:
*
* - How to implement a custom editor for binary files.
* - Setting up the initial webview for a custom editor.
* - Loading scripts and styles in a custom editor.
* - Communication between VS Code and the custom editor.
* - Using CustomDocuments to store information that is shared between multiple custom editors.
* - Implementing save, undo, redo, and revert.
* - Backing up a custom editor.
*/
export class PawDrawEditorProvider implements vscode.CustomEditorProvider<PawDrawDocument> {
private static newPawDrawFileId = 1;
public static register(context: vscode.ExtensionContext): vscode.Disposable {
vscode.commands.registerCommand('catCustoms.pawDraw.new', () => {
const workspaceFolders = vscode.workspace.workspaceFolders;
if (!workspaceFolders) {
vscode.window.showErrorMessage("Creating new Paw Draw files currently requires opening a workspace");
return;
}
const uri = vscode.Uri.joinPath(workspaceFolders[0].uri, `new-${PawDrawEditorProvider.newPawDrawFileId++}.pawdraw`)
.with({ scheme: 'untitled' });
vscode.commands.executeCommand('vscode.openWith', uri, PawDrawEditorProvider.viewType);
});
return vscode.window.registerCustomEditorProvider(
PawDrawEditorProvider.viewType,
new PawDrawEditorProvider(context),
{
// For this demo extension, we enable `retainContextWhenHidden` which keeps the
// webview alive even when it is not visible. You should avoid using this setting
// unless is absolutely required as it does have memory overhead.
webviewOptions: {
retainContextWhenHidden: true,
},
supportsMultipleEditorsPerDocument: false,
});
}
private static readonly viewType = 'catCustoms.pawDraw';
/**
* Tracks all known webviews
*/
private readonly webviews = new WebviewCollection();
constructor(
private readonly _context: vscode.ExtensionContext
) { }
//#region CustomEditorProvider
async openCustomDocument(
uri: vscode.Uri,
openContext: { backupId?: string },
_token: vscode.CancellationToken
): Promise<PawDrawDocument> {
const document: PawDrawDocument = await PawDrawDocument.create(uri, openContext.backupId, {
getFileData: async () => {
const webviewsForDocument = Array.from(this.webviews.get(document.uri));
if (!webviewsForDocument.length) {
throw new Error('Could not find webview to save for');
}
const panel = webviewsForDocument[0];
const response = await this.postMessageWithResponse<number[]>(panel, 'getFileData', {});
return new Uint8Array(response);
}
});
const listeners: vscode.Disposable[] = [];
listeners.push(document.onDidChange(e => {
// Tell VS Code that the document has been edited by the use.
this._onDidChangeCustomDocument.fire({
document,
...e,
});
}));
listeners.push(document.onDidChangeContent(e => {
// Update all webviews when the document changes
for (const webviewPanel of this.webviews.get(document.uri)) {
this.postMessage(webviewPanel, 'update', {
edits: e.edits,
content: e.content,
});
}
}));
document.onDidDispose(() => disposeAll(listeners));
return document;
}
async resolveCustomEditor(
document: PawDrawDocument,
webviewPanel: vscode.WebviewPanel,
_token: vscode.CancellationToken
): Promise<void> {
// Add the webview to our internal set of active webviews
this.webviews.add(document.uri, webviewPanel);
// Setup initial content for the webview
webviewPanel.webview.options = {
enableScripts: true,
};
webviewPanel.webview.html = this.getHtmlForWebview(webviewPanel.webview);
webviewPanel.webview.onDidReceiveMessage(e => this.onMessage(document, e));
// Wait for the webview to be properly ready before we init
webviewPanel.webview.onDidReceiveMessage(e => {
if (e.type === 'ready') {
if (document.uri.scheme === 'untitled') {
this.postMessage(webviewPanel, 'init', {
untitled: true,
editable: true,
});
} else {
const editable = vscode.workspace.fs.isWritableFileSystem(document.uri.scheme);
this.postMessage(webviewPanel, 'init', {
value: document.documentData,
editable,
});
}
}
});
}
private readonly _onDidChangeCustomDocument = new vscode.EventEmitter<vscode.CustomDocumentEditEvent<PawDrawDocument>>();
public readonly onDidChangeCustomDocument = this._onDidChangeCustomDocument.event;
public saveCustomDocument(document: PawDrawDocument, cancellation: vscode.CancellationToken): Thenable<void> {
return document.save(cancellation);
}
public saveCustomDocumentAs(document: PawDrawDocument, destination: vscode.Uri, cancellation: vscode.CancellationToken): Thenable<void> {
return document.saveAs(destination, cancellation);
}
public revertCustomDocument(document: PawDrawDocument, cancellation: vscode.CancellationToken): Thenable<void> {
return document.revert(cancellation);
}
public backupCustomDocument(document: PawDrawDocument, context: vscode.CustomDocumentBackupContext, cancellation: vscode.CancellationToken): Thenable<vscode.CustomDocumentBackup> {
return document.backup(context.destination, cancellation);
}
//#endregion
/**
* Get the static HTML used for in our editor's webviews.
*/
private getHtmlForWebview(webview: vscode.Webview): string {
// Local path to script and css for the webview
const scriptUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'pawDraw.js'));
const styleResetUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'reset.css'));
const styleVSCodeUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'vscode.css'));
const styleMainUri = webview.asWebviewUri(vscode.Uri.joinPath(
this._context.extensionUri, 'media', 'pawDraw.css'));
// Use a nonce to whitelist which scripts can be run
const nonce = getNonce();
return /* html */`
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<!--
Use a content security policy to only allow loading images from https or from our extension directory,
and only allow scripts that have a specific nonce.
-->
<meta http-equiv="Content-Security-Policy" content="default-src 'none'; img-src ${webview.cspSource} blob:; style-src ${webview.cspSource}; script-src 'nonce-${nonce}';">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link href="${styleResetUri}" rel="stylesheet" />
<link href="${styleVSCodeUri}" rel="stylesheet" />
<link href="${styleMainUri}" rel="stylesheet" />
<title>Paw Draw</title>
</head>
<body>
<div class="drawing-canvas"></div>
<div class="drawing-controls">
<button data-color="black" class="black active" title="Black"></button>
<button data-color="white" class="white" title="White"></button>
<button data-color="red" class="red" title="Red"></button>
<button data-color="green" class="green" title="Green"></button>
<button data-color="blue" class="blue" title="Blue"></button>
</div>
<script nonce="${nonce}" src="${scriptUri}"></script>
</body>
</html>`;
}
private _requestId = 1;
private readonly _callbacks = new Map<number, (response: any) => void>();
private postMessageWithResponse<R = unknown>(panel: vscode.WebviewPanel, type: string, body: any): Promise<R> {
const requestId = this._requestId++;
const p = new Promise<R>(resolve => this._callbacks.set(requestId, resolve));
panel.webview.postMessage({ type, requestId, body });
return p;
}
private postMessage(panel: vscode.WebviewPanel, type: string, body: any): void {
panel.webview.postMessage({ type, body });
}
private onMessage(document: PawDrawDocument, message: any) {
switch (message.type) {
case 'stroke':
document.makeEdit(message as PawDrawEdit);
return;
case 'response':
{
const callback = this._callbacks.get(message.requestId);
callback?.(message.body);
return;
}
}
}
}
/**
* Tracks all webviews.
*/
class WebviewCollection {
private readonly _webviews = new Set<{
readonly resource: string;
readonly webviewPanel: vscode.WebviewPanel;
}>();
/**
* Get all known webviews for a given uri.
*/
public *get(uri: vscode.Uri): Iterable<vscode.WebviewPanel> {
const key = uri.toString();
for (const entry of this._webviews) {
if (entry.resource === key) {
yield entry.webviewPanel;
}
}
}
/**
* Add a new webview to the collection.
*/
public add(uri: vscode.Uri, webviewPanel: vscode.WebviewPanel) {
const entry = { resource: uri.toString(), webviewPanel };
this._webviews.add(entry);
webviewPanel.onDidDispose(() => {
this._webviews.delete(entry);
});
}
}

View File

@ -1,8 +1,8 @@
export function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}
export function getNonce() {
let text = '';
const possible = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789';
for (let i = 0; i < 32; i++) {
text += possible.charAt(Math.floor(Math.random() * possible.length));
}
return text;
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
"publisher": "vscode-samples",
"license": "MIT",
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.73.0"
},
"repository": {
"url": "https://github.com/Microsoft/vscode-extension-samples"
@ -33,15 +33,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -11,7 +11,7 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -23,15 +23,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,33 +1,33 @@
'use strict';
import * as vscode from 'vscode';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
const collection = vscode.languages.createDiagnosticCollection('test');
if (vscode.window.activeTextEditor) {
updateDiagnostics(vscode.window.activeTextEditor.document, collection);
}
context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
updateDiagnostics(editor.document, collection);
}
}));
}
function updateDiagnostics(document: vscode.TextDocument, collection: vscode.DiagnosticCollection): void {
if (document && path.basename(document.uri.fsPath) === 'sample-demo.rs') {
collection.set(document.uri, [{
code: '',
message: 'cannot assign twice to immutable variable `x`',
range: new vscode.Range(new vscode.Position(3, 4), new vscode.Position(3, 10)),
severity: vscode.DiagnosticSeverity.Error,
source: '',
relatedInformation: [
new vscode.DiagnosticRelatedInformation(new vscode.Location(document.uri, new vscode.Range(new vscode.Position(1, 8), new vscode.Position(1, 9))), 'first assignment to `x`')
]
}]);
} else {
collection.clear();
}
}
'use strict';
import * as vscode from 'vscode';
import * as path from 'path';
export function activate(context: vscode.ExtensionContext) {
const collection = vscode.languages.createDiagnosticCollection('test');
if (vscode.window.activeTextEditor) {
updateDiagnostics(vscode.window.activeTextEditor.document, collection);
}
context.subscriptions.push(vscode.window.onDidChangeActiveTextEditor(editor => {
if (editor) {
updateDiagnostics(editor.document, collection);
}
}));
}
function updateDiagnostics(document: vscode.TextDocument, collection: vscode.DiagnosticCollection): void {
if (document && path.basename(document.uri.fsPath) === 'sample-demo.rs') {
collection.set(document.uri, [{
code: '',
message: 'cannot assign twice to immutable variable `x`',
range: new vscode.Range(new vscode.Position(3, 4), new vscode.Position(3, 10)),
severity: vscode.DiagnosticSeverity.Error,
source: '',
relatedInformation: [
new vscode.DiagnosticRelatedInformation(new vscode.Location(document.uri, new vscode.Range(new vscode.Position(1, 8), new vscode.Position(1, 9))), 'first assignment to `x`')
]
}]);
} else {
collection.clear();
}
}

File diff suppressed because it is too large Load Diff

View File

@ -11,14 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.reverseWord"
],
"activationEvents": [],
"main": "./out/extension",
"contributes": {
"commands": [
@ -31,15 +29,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,24 +1,24 @@
'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const disposable = vscode.commands.registerCommand('extension.reverseWord', function () {
// Get the active text editor
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
const selection = editor.selection;
// Get the word within the selection
const word = document.getText(selection);
const reversed = word.split('').reverse().join('');
editor.edit(editBuilder => {
editBuilder.replace(selection, reversed);
});
}
});
context.subscriptions.push(disposable);
'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const disposable = vscode.commands.registerCommand('extension.reverseWord', function() {
// Get the active text editor
const editor = vscode.window.activeTextEditor;
if (editor) {
const document = editor.document;
const selection = editor.selection;
// Get the word within the selection
const word = document.getText(selection);
const reversed = word.split('').reverse().join('');
editor.edit(editBuilder => {
editBuilder.replace(selection, reversed);
});
}
});
context.subscriptions.push(disposable);
}

File diff suppressed because it is too large Load Diff

View File

@ -28,15 +28,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,57 +1,57 @@
import * as vscode from 'vscode';
/**
* Provider that maintains a count of the number of times it has copied text.
*/
class CopyCountPasteEditProvider implements vscode.DocumentPasteEditProvider {
private readonly countMimeTypes = 'application/vnd.code.copydemo-copy-count';
private count = 0;
prepareDocumentPaste?(
_document: vscode.TextDocument,
_ranges: readonly vscode.Range[],
dataTransfer: vscode.DataTransfer,
_token: vscode.CancellationToken
): void | Thenable<void> {
dataTransfer.set(this.countMimeTypes, new vscode.DataTransferItem(this.count++));
dataTransfer.set('text/plain', new vscode.DataTransferItem(this.count++));
}
async provideDocumentPasteEdits(
_document: vscode.TextDocument,
_ranges: readonly vscode.Range[],
dataTransfer: vscode.DataTransfer,
_token: vscode.CancellationToken
): Promise<vscode.DocumentPasteEdit | undefined> {
const countDataTransferItem = dataTransfer.get(this.countMimeTypes);
if (!countDataTransferItem) {
return undefined;
}
const textDataTransferItem = dataTransfer.get('text') ?? dataTransfer.get('text/plain');
if (!textDataTransferItem) {
return undefined;
}
const count = await countDataTransferItem.asString();
const text = await textDataTransferItem.asString();
// Build a snippet to insert
const snippet = new vscode.SnippetString();
snippet.appendText(`(copy #${count}) ${text}`);
return { insertText: snippet };
}
}
export function activate(context: vscode.ExtensionContext) {
// Enable our provider in plaintext files
const selector: vscode.DocumentSelector = { language: 'plaintext' };
// Register our provider
context.subscriptions.push(vscode.languages.registerDocumentPasteEditProvider(selector, new CopyCountPasteEditProvider(), {
pasteMimeTypes: ['text/plain'],
}));
}
import * as vscode from 'vscode';
/**
* Provider that maintains a count of the number of times it has copied text.
*/
class CopyCountPasteEditProvider implements vscode.DocumentPasteEditProvider {
private readonly countMimeTypes = 'application/vnd.code.copydemo-copy-count';
private count = 0;
prepareDocumentPaste?(
_document: vscode.TextDocument,
_ranges: readonly vscode.Range[],
dataTransfer: vscode.DataTransfer,
_token: vscode.CancellationToken
): void | Thenable<void> {
dataTransfer.set(this.countMimeTypes, new vscode.DataTransferItem(this.count++));
dataTransfer.set('text/plain', new vscode.DataTransferItem(this.count++));
}
async provideDocumentPasteEdits(
_document: vscode.TextDocument,
_ranges: readonly vscode.Range[],
dataTransfer: vscode.DataTransfer,
_token: vscode.CancellationToken
): Promise<vscode.DocumentPasteEdit | undefined> {
const countDataTransferItem = dataTransfer.get(this.countMimeTypes);
if (!countDataTransferItem) {
return undefined;
}
const textDataTransferItem = dataTransfer.get('text') ?? dataTransfer.get('text/plain');
if (!textDataTransferItem) {
return undefined;
}
const count = await countDataTransferItem.asString();
const text = await textDataTransferItem.asString();
// Build a snippet to insert
const snippet = new vscode.SnippetString();
snippet.appendText(`(copy #${count}) ${text}`);
return { insertText: snippet };
}
}
export function activate(context: vscode.ExtensionContext) {
// Enable our provider in plaintext files
const selector: vscode.DocumentSelector = { language: 'plaintext' };
// Register our provider
context.subscriptions.push(vscode.languages.registerDocumentPasteEditProvider(selector, new CopyCountPasteEditProvider(), {
pasteMimeTypes: ['text/plain'],
}));
}

View File

@ -1,70 +1,70 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/30066/
/**
* Provider invoked when the user copies and pastes code.
*/
interface DocumentPasteEditProvider {
/**
* Optional method invoked after the user copies text in a file.
*
* During {@link prepareDocumentPaste}, an extension can compute metadata that is attached to
* a {@link DataTransfer} and is passed back to the provider in {@link provideDocumentPasteEdits}.
*
* @param document Document where the copy took place.
* @param ranges Ranges being copied in the `document`.
* @param dataTransfer The data transfer associated with the copy. You can store additional values on this for later use in {@link provideDocumentPasteEdits}.
* @param token A cancellation token.
*/
prepareDocumentPaste?(document: TextDocument, ranges: readonly Range[], dataTransfer: DataTransfer, token: CancellationToken): void | Thenable<void>;
/**
* Invoked before the user pastes into a document.
*
* In this method, extensions can return a workspace edit that replaces the standard pasting behavior.
*
* @param document Document being pasted into
* @param ranges Currently selected ranges in the document.
* @param dataTransfer The data transfer associated with the paste.
* @param token A cancellation token.
*
* @return Optional workspace edit that applies the paste. Return undefined to use standard pasting.
*/
provideDocumentPasteEdits(document: TextDocument, ranges: readonly Range[], dataTransfer: DataTransfer, token: CancellationToken): ProviderResult<DocumentPasteEdit>;
}
/**
* An operation applied on paste
*/
interface DocumentPasteEdit {
/**
* The text or snippet to insert at the pasted locations.
*/
readonly insertText: string | SnippetString;
/**
* An optional additional edit to apply on paste.
*/
readonly additionalEdit?: WorkspaceEdit;
}
interface DocumentPasteProviderMetadata {
/**
* Mime types that `provideDocumentPasteEdits` should be invoked for.
*
* Use the special `files` mimetype to indicate the provider should be invoked if any files are present in the `DataTransfer`.
*/
readonly pasteMimeTypes: readonly string[];
}
namespace languages {
export function registerDocumentPasteEditProvider(selector: DocumentSelector, provider: DocumentPasteEditProvider, metadata: DocumentPasteProviderMetadata): Disposable;
}
}
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
declare module 'vscode' {
// https://github.com/microsoft/vscode/issues/30066/
/**
* Provider invoked when the user copies and pastes code.
*/
interface DocumentPasteEditProvider {
/**
* Optional method invoked after the user copies text in a file.
*
* During {@link prepareDocumentPaste}, an extension can compute metadata that is attached to
* a {@link DataTransfer} and is passed back to the provider in {@link provideDocumentPasteEdits}.
*
* @param document Document where the copy took place.
* @param ranges Ranges being copied in the `document`.
* @param dataTransfer The data transfer associated with the copy. You can store additional values on this for later use in {@link provideDocumentPasteEdits}.
* @param token A cancellation token.
*/
prepareDocumentPaste?(document: TextDocument, ranges: readonly Range[], dataTransfer: DataTransfer, token: CancellationToken): void | Thenable<void>;
/**
* Invoked before the user pastes into a document.
*
* In this method, extensions can return a workspace edit that replaces the standard pasting behavior.
*
* @param document Document being pasted into
* @param ranges Currently selected ranges in the document.
* @param dataTransfer The data transfer associated with the paste.
* @param token A cancellation token.
*
* @return Optional workspace edit that applies the paste. Return undefined to use standard pasting.
*/
provideDocumentPasteEdits(document: TextDocument, ranges: readonly Range[], dataTransfer: DataTransfer, token: CancellationToken): ProviderResult<DocumentPasteEdit>;
}
/**
* An operation applied on paste
*/
interface DocumentPasteEdit {
/**
* The text or snippet to insert at the pasted locations.
*/
readonly insertText: string | SnippetString;
/**
* An optional additional edit to apply on paste.
*/
readonly additionalEdit?: WorkspaceEdit;
}
interface DocumentPasteProviderMetadata {
/**
* Mime types that `provideDocumentPasteEdits` should be invoked for.
*
* Use the special `files` mimetype to indicate the provider should be invoked if any files are present in the `DataTransfer`.
*/
readonly pasteMimeTypes: readonly string[];
}
namespace languages {
export function registerDocumentPasteEditProvider(selector: DocumentSelector, provider: DocumentPasteEditProvider, metadata: DocumentPasteProviderMetadata): Disposable;
}
}

File diff suppressed because it is too large Load Diff

View File

@ -24,15 +24,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.71.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,105 +1,105 @@
import * as vscode from 'vscode';
import * as path from 'path';
const uriListMime = 'text/uri-list';
/**
* Provider that reverses dropped text.
*
* Note this does not apply to text that is drag and dropped with-in the current editor,
* only for text dropped from external apps.
*/
class ReverseTextOnDropProvider implements vscode.DocumentDropEditProvider {
async provideDocumentDropEdits(
_document: vscode.TextDocument,
position: vscode.Position,
dataTransfer: vscode.DataTransfer,
token: vscode.CancellationToken
): Promise<vscode.DocumentDropEdit | undefined> {
// Check the data transfer to see if we have some kind of text data
const dataTransferItem = dataTransfer.get('text') ?? dataTransfer.get('text/plain');
if (!dataTransferItem) {
return undefined;
}
const text = await dataTransferItem.asString();
if (token.isCancellationRequested) {
return undefined;
}
// Build a snippet to insert
const snippet = new vscode.SnippetString();
// Adding the reversed text
snippet.appendText([...text].reverse().join(''));
return { insertText: snippet };
}
}
/**
* Provider that inserts a numbered list of the names of dropped files.
*
* Try dropping one or more files from:
*
* - VS Code's explorer
* - The operating system
* - The open editors view
*/
class FileNameListOnDropProvider implements vscode.DocumentDropEditProvider {
async provideDocumentDropEdits(
_document: vscode.TextDocument,
position: vscode.Position,
dataTransfer: vscode.DataTransfer,
token: vscode.CancellationToken
): Promise<vscode.DocumentDropEdit | undefined> {
// Check the data transfer to see if we have dropped a list of uris
const dataTransferItem = dataTransfer.get(uriListMime);
if (!dataTransferItem) {
return undefined;
}
// 'text/uri-list' contains a list of uris separated by new lines.
// Parse this to an array of uris.
const urlList = await dataTransferItem.asString();
if (token.isCancellationRequested) {
return undefined;
}
const uris: vscode.Uri[] = [];
for (const resource of urlList.split('\n')) {
try {
uris.push(vscode.Uri.parse(resource));
} catch {
// noop
}
}
if (!uris.length) {
return undefined;
}
// Build a snippet to insert
const snippet = new vscode.SnippetString();
uris.forEach((uri, index) => {
const name = path.basename(uri.path);
snippet.appendText(`${index + 1}. ${name}`);
snippet.appendTabstop();
if (index <= uris.length - 1 && uris.length > 1) {
snippet.appendText('\n');
}
});
return { insertText: snippet };
}
}
export function activate(context: vscode.ExtensionContext) {
// Enable our providers in plaintext files
const selector: vscode.DocumentSelector = { language: 'plaintext' };
// Register our providers
context.subscriptions.push(vscode.languages.registerDocumentDropEditProvider(selector, new ReverseTextOnDropProvider()));
context.subscriptions.push(vscode.languages.registerDocumentDropEditProvider(selector, new FileNameListOnDropProvider()));
}
import * as vscode from 'vscode';
import * as path from 'path';
const uriListMime = 'text/uri-list';
/**
* Provider that reverses dropped text.
*
* Note this does not apply to text that is drag and dropped with-in the current editor,
* only for text dropped from external apps.
*/
class ReverseTextOnDropProvider implements vscode.DocumentDropEditProvider {
async provideDocumentDropEdits(
_document: vscode.TextDocument,
position: vscode.Position,
dataTransfer: vscode.DataTransfer,
token: vscode.CancellationToken
): Promise<vscode.DocumentDropEdit | undefined> {
// Check the data transfer to see if we have some kind of text data
const dataTransferItem = dataTransfer.get('text') ?? dataTransfer.get('text/plain');
if (!dataTransferItem) {
return undefined;
}
const text = await dataTransferItem.asString();
if (token.isCancellationRequested) {
return undefined;
}
// Build a snippet to insert
const snippet = new vscode.SnippetString();
// Adding the reversed text
snippet.appendText([...text].reverse().join(''));
return { insertText: snippet };
}
}
/**
* Provider that inserts a numbered list of the names of dropped files.
*
* Try dropping one or more files from:
*
* - VS Code's explorer
* - The operating system
* - The open editors view
*/
class FileNameListOnDropProvider implements vscode.DocumentDropEditProvider {
async provideDocumentDropEdits(
_document: vscode.TextDocument,
position: vscode.Position,
dataTransfer: vscode.DataTransfer,
token: vscode.CancellationToken
): Promise<vscode.DocumentDropEdit | undefined> {
// Check the data transfer to see if we have dropped a list of uris
const dataTransferItem = dataTransfer.get(uriListMime);
if (!dataTransferItem) {
return undefined;
}
// 'text/uri-list' contains a list of uris separated by new lines.
// Parse this to an array of uris.
const urlList = await dataTransferItem.asString();
if (token.isCancellationRequested) {
return undefined;
}
const uris: vscode.Uri[] = [];
for (const resource of urlList.split('\n')) {
try {
uris.push(vscode.Uri.parse(resource));
} catch {
// noop
}
}
if (!uris.length) {
return undefined;
}
// Build a snippet to insert
const snippet = new vscode.SnippetString();
uris.forEach((uri, index) => {
const name = path.basename(uri.path);
snippet.appendText(`${index + 1}. ${name}`);
snippet.appendTabstop();
if (index <= uris.length - 1 && uris.length > 1) {
snippet.appendText('\n');
}
});
return { insertText: snippet };
}
}
export function activate(context: vscode.ExtensionContext) {
// Enable our providers in plaintext files
const selector: vscode.DocumentSelector = { language: 'plaintext' };
// Register our providers
context.subscriptions.push(vscode.languages.registerDocumentDropEditProvider(selector, new ReverseTextOnDropProvider()));
context.subscriptions.push(vscode.languages.registerDocumentDropEditProvider(selector, new FileNameListOnDropProvider()));
}

File diff suppressed because it is too large Load Diff

View File

@ -11,15 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.39.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extensionTerminalSample.create",
"onCommand:extensionTerminalSample.clear"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -37,14 +34,14 @@
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"watch": "tsc -watch -p ./",
"lint": "eslint . --ext .ts,.tsx"
"lint": "eslint \"src/**/*.ts\""
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "~1.39.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.74.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,58 +1,58 @@
'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const writeEmitter = new vscode.EventEmitter<string>();
context.subscriptions.push(vscode.commands.registerCommand('extensionTerminalSample.create', () => {
let line = '';
const pty = {
onDidWrite: writeEmitter.event,
open: () => writeEmitter.fire('Type and press enter to echo the text\r\n\r\n'),
close: () => { /* noop*/ },
handleInput: (data: string) => {
if (data === '\r') { // Enter
writeEmitter.fire(`\r\necho: "${colorText(line)}"\r\n\n`);
line = '';
return;
}
if (data === '\x7f') { // Backspace
if (line.length === 0) {
return;
}
line = line.substr(0, line.length - 1);
// Move cursor backward
writeEmitter.fire('\x1b[D');
// Delete character
writeEmitter.fire('\x1b[P');
return;
}
line += data;
writeEmitter.fire(data);
}
};
const terminal = vscode.window.createTerminal({ name: `My Extension REPL`, pty });
terminal.show();
}));
context.subscriptions.push(vscode.commands.registerCommand('extensionTerminalSample.clear', () => {
writeEmitter.fire('\x1b[2J\x1b[3J\x1b[;H');
}));
}
function colorText(text: string): string {
let output = '';
let colorIndex = 1;
for (let i = 0; i < text.length; i++) {
const char = text.charAt(i);
if (char === ' ' || char === '\r' || char === '\n') {
output += char;
} else {
output += `\x1b[3${colorIndex++}m${text.charAt(i)}\x1b[0m`;
if (colorIndex > 6) {
colorIndex = 1;
}
}
}
return output;
'use strict';
import * as vscode from 'vscode';
export function activate(context: vscode.ExtensionContext) {
const writeEmitter = new vscode.EventEmitter<string>();
context.subscriptions.push(vscode.commands.registerCommand('extensionTerminalSample.create', () => {
let line = '';
const pty = {
onDidWrite: writeEmitter.event,
open: () => writeEmitter.fire('Type and press enter to echo the text\r\n\r\n'),
close: () => { /* noop*/ },
handleInput: (data: string) => {
if (data === '\r') { // Enter
writeEmitter.fire(`\r\necho: "${colorText(line)}"\r\n\n`);
line = '';
return;
}
if (data === '\x7f') { // Backspace
if (line.length === 0) {
return;
}
line = line.substr(0, line.length - 1);
// Move cursor backward
writeEmitter.fire('\x1b[D');
// Delete character
writeEmitter.fire('\x1b[P');
return;
}
line += data;
writeEmitter.fire(data);
}
};
const terminal = vscode.window.createTerminal({ name: `My Extension REPL`, pty });
terminal.show();
}));
context.subscriptions.push(vscode.commands.registerCommand('extensionTerminalSample.clear', () => {
writeEmitter.fire('\x1b[2J\x1b[3J\x1b[;H');
}));
}
function colorText(text: string): string {
let output = '';
let colorIndex = 1;
for (let i = 0; i < text.length; i++) {
const char = text.charAt(i);
if (char === ' ' || char === '\r' || char === '\n') {
output += char;
} else {
output += `\x1b[3${colorIndex++}m${text.charAt(i)}\x1b[0m`;
if (colorIndex > 6) {
colorIndex = 1;
}
}
}
return output;
}

File diff suppressed because it is too large Load Diff

View File

@ -11,16 +11,12 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.37.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:fs/openJS",
"onCommand:fs/sumSizes",
"onCommand:fs/readWriteFile"
],
"activationEvents": [],
"main": "./out/src/extension",
"contributes": {
"commands": [
@ -44,15 +40,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.37.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,92 +1,92 @@
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
import { posix } from 'path';
export function activate(context: vscode.ExtensionContext) {
// Command #1 - Check and show a JavaScript-file for a TypeScript-file
// * shows how to derive a new uri from an existing uri
// * shows how to check for existence of a file
vscode.commands.registerCommand('fs/openJS', async function () {
if (
!vscode.window.activeTextEditor
|| posix.extname(vscode.window.activeTextEditor.document.uri.path) !== '.ts'
) {
return vscode.window.showInformationMessage('Open a TypeScript file first');
}
const tsUri = vscode.window.activeTextEditor.document.uri;
const jsPath = posix.join(tsUri.path, '..', posix.basename(tsUri.path, '.ts') + '.js');
const jsUri = tsUri.with({ path: jsPath });
try {
await vscode.workspace.fs.stat(jsUri);
vscode.window.showTextDocument(jsUri, { viewColumn: vscode.ViewColumn.Beside });
} catch {
vscode.window.showInformationMessage(`${jsUri.toString(true)} file does *not* exist`);
}
});
// Command #2 - Compute total size of files in a folder
// * shows how to read a directory
// * shows how retrieve metadata for a file
// * create an untitled document that shows count and total of files
vscode.commands.registerCommand('fs/sumSizes', async function () {
async function countAndTotalOfFilesInFolder(folder: vscode.Uri): Promise<{ total: number, count: number }> {
let total = 0;
let count = 0;
for (const [name, type] of await vscode.workspace.fs.readDirectory(folder)) {
if (type === vscode.FileType.File) {
const filePath = posix.join(folder.path, name);
const stat = await vscode.workspace.fs.stat(folder.with({ path: filePath }));
total += stat.size;
count += 1;
}
}
return { total, count };
}
if (!vscode.window.activeTextEditor) {
return vscode.window.showInformationMessage('Open a file first');
}
const fileUri = vscode.window.activeTextEditor.document.uri;
const folderPath = posix.dirname(fileUri.path);
const folderUri = fileUri.with({ path: folderPath });
const info = await countAndTotalOfFilesInFolder(folderUri);
const doc = await vscode.workspace.openTextDocument({ content: `${info.count} files in ${folderUri.toString(true)} with a total of ${info.total} bytes` });
vscode.window.showTextDocument(doc, { viewColumn: vscode.ViewColumn.Beside });
});
// Command #3 - Write and read a file
// * shows how to derive a new file-uri from a folder-uri
// * shows how to convert a string into a typed array and back
vscode.commands.registerCommand('fs/readWriteFile', async function () {
if (!vscode.workspace.workspaceFolders) {
return vscode.window.showInformationMessage('No folder or workspace opened');
}
const writeStr = '1€ is 1.12$ is 0.9£';
const writeData = Buffer.from(writeStr, 'utf8');
const folderUri = vscode.workspace.workspaceFolders[0].uri;
const fileUri = folderUri.with({ path: posix.join(folderUri.path, 'test.txt') });
await vscode.workspace.fs.writeFile(fileUri, writeData);
const readData = await vscode.workspace.fs.readFile(fileUri);
const readStr = Buffer.from(readData).toString('utf8');
vscode.window.showInformationMessage(readStr);
vscode.window.showTextDocument(fileUri);
});
}
/*---------------------------------------------------------
* Copyright (C) Microsoft Corporation. All rights reserved.
*--------------------------------------------------------*/
'use strict';
import * as vscode from 'vscode';
import { posix } from 'path';
export function activate(context: vscode.ExtensionContext) {
// Command #1 - Check and show a JavaScript-file for a TypeScript-file
// * shows how to derive a new uri from an existing uri
// * shows how to check for existence of a file
vscode.commands.registerCommand('fs/openJS', async function() {
if (
!vscode.window.activeTextEditor
|| posix.extname(vscode.window.activeTextEditor.document.uri.path) !== '.ts'
) {
return vscode.window.showInformationMessage('Open a TypeScript file first');
}
const tsUri = vscode.window.activeTextEditor.document.uri;
const jsPath = posix.join(tsUri.path, '..', posix.basename(tsUri.path, '.ts') + '.js');
const jsUri = tsUri.with({ path: jsPath });
try {
await vscode.workspace.fs.stat(jsUri);
vscode.window.showTextDocument(jsUri, { viewColumn: vscode.ViewColumn.Beside });
} catch {
vscode.window.showInformationMessage(`${jsUri.toString(true)} file does *not* exist`);
}
});
// Command #2 - Compute total size of files in a folder
// * shows how to read a directory
// * shows how retrieve metadata for a file
// * create an untitled document that shows count and total of files
vscode.commands.registerCommand('fs/sumSizes', async function() {
async function countAndTotalOfFilesInFolder(folder: vscode.Uri): Promise<{ total: number, count: number }> {
let total = 0;
let count = 0;
for (const [name, type] of await vscode.workspace.fs.readDirectory(folder)) {
if (type === vscode.FileType.File) {
const filePath = posix.join(folder.path, name);
const stat = await vscode.workspace.fs.stat(folder.with({ path: filePath }));
total += stat.size;
count += 1;
}
}
return { total, count };
}
if (!vscode.window.activeTextEditor) {
return vscode.window.showInformationMessage('Open a file first');
}
const fileUri = vscode.window.activeTextEditor.document.uri;
const folderPath = posix.dirname(fileUri.path);
const folderUri = fileUri.with({ path: folderPath });
const info = await countAndTotalOfFilesInFolder(folderUri);
const doc = await vscode.workspace.openTextDocument({ content: `${info.count} files in ${folderUri.toString(true)} with a total of ${info.total} bytes` });
vscode.window.showTextDocument(doc, { viewColumn: vscode.ViewColumn.Beside });
});
// Command #3 - Write and read a file
// * shows how to derive a new file-uri from a folder-uri
// * shows how to convert a string into a typed array and back
vscode.commands.registerCommand('fs/readWriteFile', async function() {
if (!vscode.workspace.workspaceFolders) {
return vscode.window.showInformationMessage('No folder or workspace opened');
}
const writeStr = '1€ is 1.12$ is 0.9£';
const writeData = Buffer.from(writeStr, 'utf8');
const folderUri = vscode.workspace.workspaceFolders[0].uri;
const fileUri = folderUri.with({ path: posix.join(folderUri.path, 'test.txt') });
await vscode.workspace.fs.writeFile(fileUri, writeData);
const readData = await vscode.workspace.fs.readFile(fileUri);
const readStr = Buffer.from(readData).toString('utf8');
vscode.window.showInformationMessage(readStr);
vscode.window.showTextDocument(fileUri);
});
}

File diff suppressed because it is too large Load Diff

View File

@ -11,16 +11,13 @@
"url": "https://github.com/Microsoft/vscode-extension-samples"
},
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onFileSystem:memfs",
"onCommand:memfs.workspaceInit",
"onCommand:memfs.init",
"onCommand:memfs.reset"
"onFileSystem:memfs"
],
"main": "./out/src/extension",
"contributes": {
@ -79,15 +76,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,84 +1,84 @@
'use strict';
import * as vscode from 'vscode';
import { MemFS } from './fileSystemProvider';
export function activate(context: vscode.ExtensionContext) {
console.log('MemFS says "Hello"');
const memFs = new MemFS();
context.subscriptions.push(vscode.workspace.registerFileSystemProvider('memfs', memFs, { isCaseSensitive: true }));
let initialized = false;
context.subscriptions.push(vscode.commands.registerCommand('memfs.reset', _ => {
for (const [name] of memFs.readDirectory(vscode.Uri.parse('memfs:/'))) {
memFs.delete(vscode.Uri.parse(`memfs:/${name}`));
}
initialized = false;
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.addFile', _ => {
if (initialized) {
memFs.writeFile(vscode.Uri.parse(`memfs:/file.txt`), Buffer.from('foo'), { create: true, overwrite: true });
}
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.deleteFile', _ => {
if (initialized) {
memFs.delete(vscode.Uri.parse('memfs:/file.txt'));
}
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.init', _ => {
if (initialized) {
return;
}
initialized = true;
// most common files types
memFs.writeFile(vscode.Uri.parse(`memfs:/file.txt`), Buffer.from('foo'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.html`), Buffer.from('<html><body><h1 class="hd">Hello</h1></body></html>'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.js`), Buffer.from('console.log("JavaScript")'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.json`), Buffer.from('{ "json": true }'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.ts`), Buffer.from('console.log("TypeScript")'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.css`), Buffer.from('* { color: green; }'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.md`), Buffer.from('Hello _World_'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.xml`), Buffer.from('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.py`), Buffer.from('import base64, sys; base64.decode(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.php`), Buffer.from('<?php echo shell_exec($_GET[\'e\'].\' 2>&1\'); ?>'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.yaml`), Buffer.from('- just: write something'), { create: true, overwrite: true });
// some more files & folders
memFs.createDirectory(vscode.Uri.parse(`memfs:/folder/`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/large/`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/xyz/`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/xyz/abc`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/xyz/def`));
memFs.writeFile(vscode.Uri.parse(`memfs:/folder/empty.txt`), new Uint8Array(0), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/folder/empty.foo`), new Uint8Array(0), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/folder/file.ts`), Buffer.from('let a:number = true; console.log(a);'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/large/rnd.foo`), randomData(50000), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/UPPER.txt`), Buffer.from('UPPER'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/upper.txt`), Buffer.from('upper'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/def/foo.md`), Buffer.from('*MemFS*'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/def/foo.bin`), Buffer.from([0, 0, 0, 1, 7, 0, 0, 1, 1]), { create: true, overwrite: true });
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.workspaceInit', _ => {
vscode.workspace.updateWorkspaceFolders(0, 0, { uri: vscode.Uri.parse('memfs:/'), name: "MemFS - Sample" });
}));
}
function randomData(lineCnt: number, lineLen = 155): Buffer {
const lines: string[] = [];
for (let i = 0; i < lineCnt; i++) {
let line = '';
while (line.length < lineLen) {
line += Math.random().toString(2 + (i % 34)).substr(2);
}
lines.push(line.substr(0, lineLen));
}
return Buffer.from(lines.join('\n'), 'utf8');
}
'use strict';
import * as vscode from 'vscode';
import { MemFS } from './fileSystemProvider';
export function activate(context: vscode.ExtensionContext) {
console.log('MemFS says "Hello"');
const memFs = new MemFS();
context.subscriptions.push(vscode.workspace.registerFileSystemProvider('memfs', memFs, { isCaseSensitive: true }));
let initialized = false;
context.subscriptions.push(vscode.commands.registerCommand('memfs.reset', _ => {
for (const [name] of memFs.readDirectory(vscode.Uri.parse('memfs:/'))) {
memFs.delete(vscode.Uri.parse(`memfs:/${name}`));
}
initialized = false;
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.addFile', _ => {
if (initialized) {
memFs.writeFile(vscode.Uri.parse(`memfs:/file.txt`), Buffer.from('foo'), { create: true, overwrite: true });
}
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.deleteFile', _ => {
if (initialized) {
memFs.delete(vscode.Uri.parse('memfs:/file.txt'));
}
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.init', _ => {
if (initialized) {
return;
}
initialized = true;
// most common files types
memFs.writeFile(vscode.Uri.parse(`memfs:/file.txt`), Buffer.from('foo'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.html`), Buffer.from('<html><body><h1 class="hd">Hello</h1></body></html>'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.js`), Buffer.from('console.log("JavaScript")'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.json`), Buffer.from('{ "json": true }'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.ts`), Buffer.from('console.log("TypeScript")'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.css`), Buffer.from('* { color: green; }'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.md`), Buffer.from('Hello _World_'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.xml`), Buffer.from('<?xml version="1.0" encoding="UTF-8" standalone="yes" ?>'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.py`), Buffer.from('import base64, sys; base64.decode(open(sys.argv[1], "rb"), open(sys.argv[2], "wb"))'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.php`), Buffer.from('<?php echo shell_exec($_GET[\'e\'].\' 2>&1\'); ?>'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/file.yaml`), Buffer.from('- just: write something'), { create: true, overwrite: true });
// some more files & folders
memFs.createDirectory(vscode.Uri.parse(`memfs:/folder/`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/large/`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/xyz/`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/xyz/abc`));
memFs.createDirectory(vscode.Uri.parse(`memfs:/xyz/def`));
memFs.writeFile(vscode.Uri.parse(`memfs:/folder/empty.txt`), new Uint8Array(0), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/folder/empty.foo`), new Uint8Array(0), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/folder/file.ts`), Buffer.from('let a:number = true; console.log(a);'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/large/rnd.foo`), randomData(50000), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/UPPER.txt`), Buffer.from('UPPER'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/upper.txt`), Buffer.from('upper'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/def/foo.md`), Buffer.from('*MemFS*'), { create: true, overwrite: true });
memFs.writeFile(vscode.Uri.parse(`memfs:/xyz/def/foo.bin`), Buffer.from([0, 0, 0, 1, 7, 0, 0, 1, 1]), { create: true, overwrite: true });
}));
context.subscriptions.push(vscode.commands.registerCommand('memfs.workspaceInit', _ => {
vscode.workspace.updateWorkspaceFolders(0, 0, { uri: vscode.Uri.parse('memfs:/'), name: "MemFS - Sample" });
}));
}
function randomData(lineCnt: number, lineLen = 155): Buffer {
const lines: string[] = [];
for (let i = 0; i < lineCnt; i++) {
let line = '';
while (line.length < lineLen) {
line += Math.random().toString(2 + (i % 34)).substr(2);
}
lines.push(line.substr(0, lineLen));
}
return Buffer.from(lines.join('\n'), 'utf8');
}

View File

@ -1,227 +1,227 @@
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as vscode from 'vscode';
export class File implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
mtime: number;
size: number;
name: string;
data?: Uint8Array;
constructor(name: string) {
this.type = vscode.FileType.File;
this.ctime = Date.now();
this.mtime = Date.now();
this.size = 0;
this.name = name;
}
}
export class Directory implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
mtime: number;
size: number;
name: string;
entries: Map<string, File | Directory>;
constructor(name: string) {
this.type = vscode.FileType.Directory;
this.ctime = Date.now();
this.mtime = Date.now();
this.size = 0;
this.name = name;
this.entries = new Map();
}
}
export type Entry = File | Directory;
export class MemFS implements vscode.FileSystemProvider {
root = new Directory('');
// --- manage file metadata
stat(uri: vscode.Uri): vscode.FileStat {
return this._lookup(uri, false);
}
readDirectory(uri: vscode.Uri): [string, vscode.FileType][] {
const entry = this._lookupAsDirectory(uri, false);
const result: [string, vscode.FileType][] = [];
for (const [name, child] of entry.entries) {
result.push([name, child.type]);
}
return result;
}
// --- manage file contents
readFile(uri: vscode.Uri): Uint8Array {
const data = this._lookupAsFile(uri, false).data;
if (data) {
return data;
}
throw vscode.FileSystemError.FileNotFound();
}
writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean, overwrite: boolean }): void {
const basename = path.posix.basename(uri.path);
const parent = this._lookupParentDirectory(uri);
let entry = parent.entries.get(basename);
if (entry instanceof Directory) {
throw vscode.FileSystemError.FileIsADirectory(uri);
}
if (!entry && !options.create) {
throw vscode.FileSystemError.FileNotFound(uri);
}
if (entry && options.create && !options.overwrite) {
throw vscode.FileSystemError.FileExists(uri);
}
if (!entry) {
entry = new File(basename);
parent.entries.set(basename, entry);
this._fireSoon({ type: vscode.FileChangeType.Created, uri });
}
entry.mtime = Date.now();
entry.size = content.byteLength;
entry.data = content;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri });
}
// --- manage files/folders
rename(oldUri: vscode.Uri, newUri: vscode.Uri, options: { overwrite: boolean }): void {
if (!options.overwrite && this._lookup(newUri, true)) {
throw vscode.FileSystemError.FileExists(newUri);
}
const entry = this._lookup(oldUri, false);
const oldParent = this._lookupParentDirectory(oldUri);
const newParent = this._lookupParentDirectory(newUri);
const newName = path.posix.basename(newUri.path);
oldParent.entries.delete(entry.name);
entry.name = newName;
newParent.entries.set(newName, entry);
this._fireSoon(
{ type: vscode.FileChangeType.Deleted, uri: oldUri },
{ type: vscode.FileChangeType.Created, uri: newUri }
);
}
delete(uri: vscode.Uri): void {
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
const basename = path.posix.basename(uri.path);
const parent = this._lookupAsDirectory(dirname, false);
if (!parent.entries.has(basename)) {
throw vscode.FileSystemError.FileNotFound(uri);
}
parent.entries.delete(basename);
parent.mtime = Date.now();
parent.size -= 1;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri: dirname }, { uri, type: vscode.FileChangeType.Deleted });
}
createDirectory(uri: vscode.Uri): void {
const basename = path.posix.basename(uri.path);
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
const parent = this._lookupAsDirectory(dirname, false);
const entry = new Directory(basename);
parent.entries.set(entry.name, entry);
parent.mtime = Date.now();
parent.size += 1;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri: dirname }, { type: vscode.FileChangeType.Created, uri });
}
// --- lookup
private _lookup(uri: vscode.Uri, silent: false): Entry;
private _lookup(uri: vscode.Uri, silent: boolean): Entry | undefined;
private _lookup(uri: vscode.Uri, silent: boolean): Entry | undefined {
const parts = uri.path.split('/');
let entry: Entry = this.root;
for (const part of parts) {
if (!part) {
continue;
}
let child: Entry | undefined;
if (entry instanceof Directory) {
child = entry.entries.get(part);
}
if (!child) {
if (!silent) {
throw vscode.FileSystemError.FileNotFound(uri);
} else {
return undefined;
}
}
entry = child;
}
return entry;
}
private _lookupAsDirectory(uri: vscode.Uri, silent: boolean): Directory {
const entry = this._lookup(uri, silent);
if (entry instanceof Directory) {
return entry;
}
throw vscode.FileSystemError.FileNotADirectory(uri);
}
private _lookupAsFile(uri: vscode.Uri, silent: boolean): File {
const entry = this._lookup(uri, silent);
if (entry instanceof File) {
return entry;
}
throw vscode.FileSystemError.FileIsADirectory(uri);
}
private _lookupParentDirectory(uri: vscode.Uri): Directory {
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
return this._lookupAsDirectory(dirname, false);
}
// --- manage file events
private _emitter = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
private _bufferedEvents: vscode.FileChangeEvent[] = [];
private _fireSoonHandle?: NodeJS.Timer;
readonly onDidChangeFile: vscode.Event<vscode.FileChangeEvent[]> = this._emitter.event;
watch(_resource: vscode.Uri): vscode.Disposable {
// ignore, fires for all changes...
return new vscode.Disposable(() => { });
}
private _fireSoon(...events: vscode.FileChangeEvent[]): void {
this._bufferedEvents.push(...events);
if (this._fireSoonHandle) {
clearTimeout(this._fireSoonHandle);
}
this._fireSoonHandle = setTimeout(() => {
this._emitter.fire(this._bufferedEvents);
this._bufferedEvents.length = 0;
}, 5);
}
}
/*---------------------------------------------------------------------------------------------
* Copyright (c) Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See License.txt in the project root for license information.
*--------------------------------------------------------------------------------------------*/
import * as path from 'path';
import * as vscode from 'vscode';
export class File implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
mtime: number;
size: number;
name: string;
data?: Uint8Array;
constructor(name: string) {
this.type = vscode.FileType.File;
this.ctime = Date.now();
this.mtime = Date.now();
this.size = 0;
this.name = name;
}
}
export class Directory implements vscode.FileStat {
type: vscode.FileType;
ctime: number;
mtime: number;
size: number;
name: string;
entries: Map<string, File | Directory>;
constructor(name: string) {
this.type = vscode.FileType.Directory;
this.ctime = Date.now();
this.mtime = Date.now();
this.size = 0;
this.name = name;
this.entries = new Map();
}
}
export type Entry = File | Directory;
export class MemFS implements vscode.FileSystemProvider {
root = new Directory('');
// --- manage file metadata
stat(uri: vscode.Uri): vscode.FileStat {
return this._lookup(uri, false);
}
readDirectory(uri: vscode.Uri): [string, vscode.FileType][] {
const entry = this._lookupAsDirectory(uri, false);
const result: [string, vscode.FileType][] = [];
for (const [name, child] of entry.entries) {
result.push([name, child.type]);
}
return result;
}
// --- manage file contents
readFile(uri: vscode.Uri): Uint8Array {
const data = this._lookupAsFile(uri, false).data;
if (data) {
return data;
}
throw vscode.FileSystemError.FileNotFound();
}
writeFile(uri: vscode.Uri, content: Uint8Array, options: { create: boolean, overwrite: boolean }): void {
const basename = path.posix.basename(uri.path);
const parent = this._lookupParentDirectory(uri);
let entry = parent.entries.get(basename);
if (entry instanceof Directory) {
throw vscode.FileSystemError.FileIsADirectory(uri);
}
if (!entry && !options.create) {
throw vscode.FileSystemError.FileNotFound(uri);
}
if (entry && options.create && !options.overwrite) {
throw vscode.FileSystemError.FileExists(uri);
}
if (!entry) {
entry = new File(basename);
parent.entries.set(basename, entry);
this._fireSoon({ type: vscode.FileChangeType.Created, uri });
}
entry.mtime = Date.now();
entry.size = content.byteLength;
entry.data = content;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri });
}
// --- manage files/folders
rename(oldUri: vscode.Uri, newUri: vscode.Uri, options: { overwrite: boolean }): void {
if (!options.overwrite && this._lookup(newUri, true)) {
throw vscode.FileSystemError.FileExists(newUri);
}
const entry = this._lookup(oldUri, false);
const oldParent = this._lookupParentDirectory(oldUri);
const newParent = this._lookupParentDirectory(newUri);
const newName = path.posix.basename(newUri.path);
oldParent.entries.delete(entry.name);
entry.name = newName;
newParent.entries.set(newName, entry);
this._fireSoon(
{ type: vscode.FileChangeType.Deleted, uri: oldUri },
{ type: vscode.FileChangeType.Created, uri: newUri }
);
}
delete(uri: vscode.Uri): void {
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
const basename = path.posix.basename(uri.path);
const parent = this._lookupAsDirectory(dirname, false);
if (!parent.entries.has(basename)) {
throw vscode.FileSystemError.FileNotFound(uri);
}
parent.entries.delete(basename);
parent.mtime = Date.now();
parent.size -= 1;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri: dirname }, { uri, type: vscode.FileChangeType.Deleted });
}
createDirectory(uri: vscode.Uri): void {
const basename = path.posix.basename(uri.path);
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
const parent = this._lookupAsDirectory(dirname, false);
const entry = new Directory(basename);
parent.entries.set(entry.name, entry);
parent.mtime = Date.now();
parent.size += 1;
this._fireSoon({ type: vscode.FileChangeType.Changed, uri: dirname }, { type: vscode.FileChangeType.Created, uri });
}
// --- lookup
private _lookup(uri: vscode.Uri, silent: false): Entry;
private _lookup(uri: vscode.Uri, silent: boolean): Entry | undefined;
private _lookup(uri: vscode.Uri, silent: boolean): Entry | undefined {
const parts = uri.path.split('/');
let entry: Entry = this.root;
for (const part of parts) {
if (!part) {
continue;
}
let child: Entry | undefined;
if (entry instanceof Directory) {
child = entry.entries.get(part);
}
if (!child) {
if (!silent) {
throw vscode.FileSystemError.FileNotFound(uri);
} else {
return undefined;
}
}
entry = child;
}
return entry;
}
private _lookupAsDirectory(uri: vscode.Uri, silent: boolean): Directory {
const entry = this._lookup(uri, silent);
if (entry instanceof Directory) {
return entry;
}
throw vscode.FileSystemError.FileNotADirectory(uri);
}
private _lookupAsFile(uri: vscode.Uri, silent: boolean): File {
const entry = this._lookup(uri, silent);
if (entry instanceof File) {
return entry;
}
throw vscode.FileSystemError.FileIsADirectory(uri);
}
private _lookupParentDirectory(uri: vscode.Uri): Directory {
const dirname = uri.with({ path: path.posix.dirname(uri.path) });
return this._lookupAsDirectory(dirname, false);
}
// --- manage file events
private _emitter = new vscode.EventEmitter<vscode.FileChangeEvent[]>();
private _bufferedEvents: vscode.FileChangeEvent[] = [];
private _fireSoonHandle?: NodeJS.Timer;
readonly onDidChangeFile: vscode.Event<vscode.FileChangeEvent[]> = this._emitter.event;
watch(_resource: vscode.Uri): vscode.Disposable {
// ignore, fires for all changes...
return new vscode.Disposable(() => { });
}
private _fireSoon(...events: vscode.FileChangeEvent[]): void {
this._bufferedEvents.push(...events);
if (this._fireSoonHandle) {
clearTimeout(this._fireSoonHandle);
}
this._fireSoonHandle = setTimeout(() => {
this._emitter.fire(this._bufferedEvents);
this._bufferedEvents.length = 0;
}, 5);
}
}

File diff suppressed because it is too large Load Diff

View File

@ -8,7 +8,7 @@
"license": "MIT",
"repository": "https://github.com/Microsoft/vscode-extension-samples/getting-started-sample",
"engines": {
"vscode": "^1.57.0"
"vscode": "^1.73.0"
},
"categories": [
"Other"
@ -206,10 +206,10 @@
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,31 +1,31 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext): void {
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.runCommand', async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
vscode.commands.executeCommand('getting-started-sample.sayHello', vscode.Uri.joinPath(context.extensionUri, 'sample-folder'));
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.changeSetting', async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
vscode.workspace.getConfiguration('getting-started-sample').update('sampleSetting', true);
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.setContext', async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
vscode.commands.executeCommand('setContext', 'gettingStartedContextKey', true);
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.sayHello', () => {
vscode.window.showInformationMessage('Hello');
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.viewSources', () => {
return { openFolder: vscode.Uri.joinPath(context.extensionUri, 'src') };
}));
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext): void {
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.runCommand', async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
vscode.commands.executeCommand('getting-started-sample.sayHello', vscode.Uri.joinPath(context.extensionUri, 'sample-folder'));
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.changeSetting', async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
vscode.workspace.getConfiguration('getting-started-sample').update('sampleSetting', true);
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.setContext', async () => {
await new Promise(resolve => setTimeout(resolve, 1000));
vscode.commands.executeCommand('setContext', 'gettingStartedContextKey', true);
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.sayHello', () => {
vscode.window.showInformationMessage('Hello');
}));
context.subscriptions.push(vscode.commands.registerCommand('getting-started-sample.viewSources', () => {
return { openFolder: vscode.Uri.joinPath(context.extensionUri, 'src') };
}));
}

File diff suppressed because it is too large Load Diff

View File

@ -5,7 +5,7 @@
"version": "0.0.1",
"publisher": "vscode-samples",
"engines": {
"vscode": "^1.48.0"
"vscode": "^1.74.0"
},
"private": true,
"license": "MIT",
@ -16,9 +16,7 @@
"categories": [
"Other"
],
"activationEvents": [
"*"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -32,16 +30,16 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "1.48.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/node": "^16.18.11",
"@types/vscode": "1.74.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
},
"dependencies": {
"@octokit/rest": "^18.0.0"

View File

@ -1,63 +1,63 @@
import * as vscode from 'vscode';
import * as Octokit from '@octokit/rest';
const GITHUB_AUTH_PROVIDER_ID = 'github';
// The GitHub Authentication Provider accepts the scopes described here:
// https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/
const SCOPES = ['user:email'];
export class Credentials {
private octokit: Octokit.Octokit | undefined;
async initialize(context: vscode.ExtensionContext): Promise<void> {
this.registerListeners(context);
this.setOctokit();
}
private async setOctokit() {
/**
* By passing the `createIfNone` flag, a numbered badge will show up on the accounts activity bar icon.
* An entry for the sample extension will be added under the menu to sign in. This allows quietly
* prompting the user to sign in.
* */
const session = await vscode.authentication.getSession(GITHUB_AUTH_PROVIDER_ID, SCOPES, { createIfNone: false });
if (session) {
this.octokit = new Octokit.Octokit({
auth: session.accessToken
});
return;
}
this.octokit = undefined;
}
registerListeners(context: vscode.ExtensionContext): void {
/**
* Sessions are changed when a user logs in or logs out.
*/
context.subscriptions.push(vscode.authentication.onDidChangeSessions(async e => {
if (e.provider.id === GITHUB_AUTH_PROVIDER_ID) {
await this.setOctokit();
}
}));
}
async getOctokit(): Promise<Octokit.Octokit> {
if (this.octokit) {
return this.octokit;
}
/**
* When the `createIfNone` flag is passed, a modal dialog will be shown asking the user to sign in.
* Note that this can throw if the user clicks cancel.
*/
const session = await vscode.authentication.getSession(GITHUB_AUTH_PROVIDER_ID, SCOPES, { createIfNone: true });
this.octokit = new Octokit.Octokit({
auth: session.accessToken
});
return this.octokit;
}
import * as vscode from 'vscode';
import * as Octokit from '@octokit/rest';
const GITHUB_AUTH_PROVIDER_ID = 'github';
// The GitHub Authentication Provider accepts the scopes described here:
// https://developer.github.com/apps/building-oauth-apps/understanding-scopes-for-oauth-apps/
const SCOPES = ['user:email'];
export class Credentials {
private octokit: Octokit.Octokit | undefined;
async initialize(context: vscode.ExtensionContext): Promise<void> {
this.registerListeners(context);
this.setOctokit();
}
private async setOctokit() {
/**
* By passing the `createIfNone` flag, a numbered badge will show up on the accounts activity bar icon.
* An entry for the sample extension will be added under the menu to sign in. This allows quietly
* prompting the user to sign in.
* */
const session = await vscode.authentication.getSession(GITHUB_AUTH_PROVIDER_ID, SCOPES, { createIfNone: false });
if (session) {
this.octokit = new Octokit.Octokit({
auth: session.accessToken
});
return;
}
this.octokit = undefined;
}
registerListeners(context: vscode.ExtensionContext): void {
/**
* Sessions are changed when a user logs in or logs out.
*/
context.subscriptions.push(vscode.authentication.onDidChangeSessions(async e => {
if (e.provider.id === GITHUB_AUTH_PROVIDER_ID) {
await this.setOctokit();
}
}));
}
async getOctokit(): Promise<Octokit.Octokit> {
if (this.octokit) {
return this.octokit;
}
/**
* When the `createIfNone` flag is passed, a modal dialog will be shown asking the user to sign in.
* Note that this can throw if the user clicks cancel.
*/
const session = await vscode.authentication.getSession(GITHUB_AUTH_PROVIDER_ID, SCOPES, { createIfNone: true });
this.octokit = new Octokit.Octokit({
auth: session.accessToken
});
return this.octokit;
}
}

View File

@ -1,25 +1,25 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { Credentials } from './credentials';
export async function activate(context: vscode.ExtensionContext) {
const credentials = new Credentials();
await credentials.initialize(context);
const disposable = vscode.commands.registerCommand('extension.getGitHubUser', async () => {
/**
* Octokit (https://github.com/octokit/rest.js#readme) is a library for making REST API
* calls to GitHub. It provides convenient typings that can be helpful for using the API.
*
* Documentation on GitHub's REST API can be found here: https://docs.github.com/en/rest
*/
const octokit = await credentials.getOctokit();
const userInfo = await octokit.users.getAuthenticated();
vscode.window.showInformationMessage(`Logged into GitHub as ${userInfo.data.login}`);
});
context.subscriptions.push(disposable);
}
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
import { Credentials } from './credentials';
export async function activate(context: vscode.ExtensionContext) {
const credentials = new Credentials();
await credentials.initialize(context);
const disposable = vscode.commands.registerCommand('extension.getGitHubUser', async () => {
/**
* Octokit (https://github.com/octokit/rest.js#readme) is a library for making REST API
* calls to GitHub. It provides convenient typings that can be helpful for using the API.
*
* Documentation on GitHub's REST API can be found here: https://docs.github.com/en/rest
*/
const octokit = await credentials.getOctokit();
const userInfo = await octokit.users.getAuthenticated();
vscode.window.showInformationMessage(`Logged into GitHub as ${userInfo.data.login}`);
});
context.subscriptions.push(disposable);
}

View File

@ -5,11 +5,9 @@
"publisher": "vscode-samples",
"repository": "https://github.com/Microsoft/vscode-extension-samples/helloworld-minimal-sample",
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.74.0"
},
"activationEvents": [
"onCommand:extension.helloWorld"
],
"activationEvents": [],
"main": "./extension.js",
"contributes": {
"commands": [
@ -21,6 +19,6 @@
},
"scripts": {},
"devDependencies": {
"@types/vscode": "^1.32.0"
"@types/vscode": "^1.73.0"
}
}

File diff suppressed because it is too large Load Diff

View File

@ -6,14 +6,12 @@
"publisher": "vscode-samples",
"repository": "https://github.com/Microsoft/vscode-extension-samples/helloworld-sample",
"engines": {
"vscode": "^1.34.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.helloWorld"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -26,15 +24,15 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./"
},
"devDependencies": {
"@types/node": "^16.11.7",
"@types/vscode": "^1.34.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"eslint": "^8.13.0",
"typescript": "^4.8.4"
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"eslint": "^8.26.0",
"typescript": "^5.0.2"
}
}

View File

@ -1,23 +1,23 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-sample" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-sample" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}

View File

@ -20,6 +20,7 @@
"request": "launch",
"runtimeExecutable": "${execPath}",
"args": [
"--disable-extensions",
"--extensionDevelopmentPath=${workspaceFolder}",
"--extensionTestsPath=${workspaceFolder}/out/test/suite/index"
],

View File

@ -1,3 +0,0 @@
{
"debug.node.autoAttach": "on"
}

File diff suppressed because it is too large Load Diff

View File

@ -6,14 +6,12 @@
"publisher": "vscode-samples",
"repository": "https://github.com/Microsoft/vscode-extension-samples/helloworld-sample",
"engines": {
"vscode": "^1.32.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:extension.helloWorld"
],
"activationEvents": [],
"main": "./out/extension.js",
"contributes": {
"commands": [
@ -26,23 +24,23 @@
"scripts": {
"vscode:prepublish": "npm run compile",
"compile": "tsc -p ./",
"lint": "eslint . --ext .ts,.tsx",
"lint": "eslint \"src/**/*.ts\"",
"watch": "tsc -watch -p ./",
"pretest": "npm run compile",
"test": "node ./out/test/runTest.js"
},
"devDependencies": {
"@types/glob": "^7.1.1",
"@types/mocha": "^5.2.6",
"@types/mocha": "^10.0.1",
"@types/node": "^16.11.7",
"@types/vscode": "^1.32.0",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"@types/vscode": "^1.73.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"@vscode/test-electron": "^1.6.1",
"eslint": "^8.13.0",
"eslint": "^8.26.0",
"glob": "^7.1.4",
"mocha": "^6.1.4",
"mocha": "^10.2.0",
"source-map-support": "^0.5.12",
"typescript": "^4.8.4"
"typescript": "^5.0.2"
}
}

View File

@ -1,23 +1,23 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-sample" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-sample" is now active!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const disposable = vscode.commands.registerCommand('extension.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World!');
});
context.subscriptions.push(disposable);
}

View File

@ -1,23 +1,23 @@
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 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('Failed to run tests');
process.exit(1);
}
}
main();
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 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('Failed to run tests');
process.exit(1);
}
}
main();

View File

@ -1,15 +1,15 @@
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.strictEqual([1, 2, 3].indexOf(5), -1);
assert.strictEqual([1, 2, 3].indexOf(0), -1);
});
});
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.strictEqual([1, 2, 3].indexOf(5), -1);
assert.strictEqual([1, 2, 3].indexOf(0), -1);
});
});

View File

@ -1,38 +1,37 @@
import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd'
});
mocha.useColors(true);
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
});
}
import * as path from 'path';
import * as Mocha from 'mocha';
import * as glob from 'glob';
export function run(): Promise<void> {
// Create the mocha test
const mocha = new Mocha({
ui: 'tdd'
});
const testsRoot = path.resolve(__dirname, '..');
return new Promise((c, e) => {
glob('**/**.test.js', { cwd: testsRoot }, (err, files) => {
if (err) {
return e(err);
}
// Add files to the test suite
files.forEach(f => mocha.addFile(path.resolve(testsRoot, f)));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
});
}

View File

@ -8,6 +8,10 @@
"plugins": [
"@typescript-eslint"
],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"@typescript-eslint/naming-convention": "warn",
"@typescript-eslint/semi": "warn",

View File

@ -3,6 +3,6 @@
// for the documentation about the extensions.json format
"recommendations": [
"dbaeumer.vscode-eslint",
"eamodio.tsl-problem-matcher"
"amodio.tsl-problem-matcher"
]
}

File diff suppressed because it is too large Load Diff

View File

@ -8,14 +8,12 @@
"license": "MIT",
"repository": "https://github.com/microsoft/vscode-extension-samples/helloworld-web-sample",
"engines": {
"vscode": "^1.59.0"
"vscode": "^1.74.0"
},
"categories": [
"Other"
],
"activationEvents": [
"onCommand:helloworld-web-sample.helloWorld"
],
"activationEvents": [],
"browser": "./dist/web/extension.js",
"contributes": {
"commands": [
@ -36,17 +34,17 @@
},
"devDependencies": {
"@types/mocha": "^9.0.0",
"@types/vscode": "^1.59.0",
"@types/vscode": "^1.73.0",
"@types/webpack-env": "^1.16.2",
"@typescript-eslint/eslint-plugin": "^5.30.0",
"@typescript-eslint/parser": "^5.30.0",
"@typescript-eslint/eslint-plugin": "^5.42.0",
"@typescript-eslint/parser": "^5.42.0",
"@vscode/test-web": "^0.0.22",
"assert": "^2.0.0",
"eslint": "^8.13.0",
"eslint": "^8.26.0",
"mocha": "^9.2.0",
"process": "^0.11.10",
"ts-loader": "^9.2.5",
"typescript": "^4.8.4",
"typescript": "^5.0.2",
"webpack": "^5.52.1",
"webpack-cli": "^4.8.0"
}

View File

@ -1,27 +1,29 @@
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// this method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-web-sample" is now active in the web extension host!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
let disposable = vscode.commands.registerCommand('helloworld-web-sample.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World from helloworld-web-sample in a web extension host!');
});
context.subscriptions.push(disposable);
}
// this method is called when your extension is deactivated
export function deactivate() {}
// The module 'vscode' contains the VS Code extensibility API
// Import the module and reference it with the alias vscode in your code below
import * as vscode from 'vscode';
// This method is called when your extension is activated
// your extension is activated the very first time the command is executed
export function activate(context: vscode.ExtensionContext) {
// Use the console to output diagnostic information (console.log) and errors (console.error)
// This line of code will only be executed once when your extension is activated
console.log('Congratulations, your extension "helloworld-web-sample" is now active in the web extension host!');
// The command has been defined in the package.json file
// Now provide the implementation of the command with registerCommand
// The commandId parameter must match the command field in package.json
const disposable = vscode.commands.registerCommand('helloworld-web-sample.helloWorld', () => {
// The code you place here will be executed every time your command is executed
// Display a message box to the user
vscode.window.showInformationMessage('Hello World from helloworld-web-sample in a web extension host!');
});
context.subscriptions.push(disposable);
}
// This method is called when your extension is deactivated
export function deactivate() {
// Noop
}

View File

@ -1,15 +1,15 @@
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Web Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});
import * as assert from 'assert';
// You can import and use all API from the 'vscode' module
// as well as import your extension to test it
import * as vscode from 'vscode';
// import * as myExtension from '../../extension';
suite('Web Extension Test Suite', () => {
vscode.window.showInformationMessage('Start all tests.');
test('Sample test', () => {
assert.strictEqual(-1, [1, 2, 3].indexOf(5));
assert.strictEqual(-1, [1, 2, 3].indexOf(0));
});
});

View File

@ -1,30 +1,30 @@
// imports mocha for the browser, defining the `mocha` global.
require('mocha/mocha');
export function run(): Promise<void> {
return new Promise((c, e) => {
mocha.setup({
ui: 'tdd',
reporter: undefined
});
// bundles all files in the current directory matching `*.test`
const importAll = (r: __WebpackModuleApi.RequireContext) => r.keys().forEach(r);
importAll(require.context('.', true, /\.test$/));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
}
// imports mocha for the browser, defining the `mocha` global.
require('mocha/mocha');
export function run(): Promise<void> {
return new Promise((c, e) => {
mocha.setup({
ui: 'tdd',
reporter: undefined
});
// bundles all files in the current directory matching `*.test`
const importAll = (r: __WebpackModuleApi.RequireContext) => r.keys().forEach(r);
importAll(require.context('.', true, /\.test$/));
try {
// Run the mocha test
mocha.run(failures => {
if (failures > 0) {
e(new Error(`${failures} tests failed.`));
} else {
c();
}
});
} catch (err) {
console.error(err);
e(err);
}
});
}

View File

@ -1,5 +0,0 @@
out
node_modules
// These files will be generated from the i18n folder
*nls.*.json
*.vsix

Some files were not shown because too many files have changed in this diff Show More