Implementing a VS Code feature: registerDocumentPasteEditProvider [2/2]

This is the second article in a series where we’ll implement “Copy with Imports” in VS Code’s TypeScript extension.

Previous article: Research & Planning

In the last article, we decided that the first step would be to implement the registerDocumentPasteEditProvider API.

I was able to find an example usage for this in the markdown-language-features extension.

I copied that structure and replaced it with console.log statements.

Here’s what I ended up with:

/*---------------------------------------------------------------------------------------------
 *  Copyright (c) Microsoft Corporation. All rights reserved.
 *  Licensed under the MIT License. See License.txt in the project root for license information.
 *--------------------------------------------------------------------------------------------*/

import * as vscode from "vscode";
import { DocumentSelector } from "../configuration/documentSelector";

class PasteEditProvider implements vscode.DocumentPasteEditProvider {
  async prepareDocumentPaste(
    document: vscode.TextDocument,
    ranges: readonly vscode.Range[],
    dataTransfer: vscode.DataTransfer,
    token: vscode.CancellationToken
  ): Promise<void> {
    console.log("prepareDocumentPaste", document, ranges, dataTransfer, token);
    return undefined;
  }

  async provideDocumentPasteEdits(
    document: vscode.TextDocument,
    ranges: readonly vscode.Range[],
    dataTransfer: vscode.DataTransfer,
    token: vscode.CancellationToken
  ): Promise<vscode.DocumentPasteEdit | undefined> {
    console.log(
      "provideDocumentPasteEdits",
      document,
      ranges,
      dataTransfer,
      token
    );
    return undefined;
  }
}

export function register(selector: DocumentSelector) {
  console.log("registering paste provider");
  return vscode.languages.registerDocumentPasteEditProvider(
    selector.syntax,
    new PasteEditProvider(),
    {
      pasteMimeTypes: [
        "*", // Try all for now
      ],
    }
  );
}

In the next article, we’ll change our prepareDocumentPaste function to copy the imports along with the copied text.