hidao’s blog

IT系とか読書ログとか。

How to identify the editor who dragged and dropped a file in VS Code extension

I posted this article on Qiita, but I had a hard time finding the information even in English, so I will post it in English on my personal blog (just a machine translation).

TL;DR

export class HogehogeDropProvider
    implements vscode.DocumentDropEditProvider
{
    async provideDocumentDropEdits(
        _document: vscode.TextDocument,
    ): Promise<vscode.DocumentDropEdit> {
        // Identify the editor to drop to from the list of open editors.
        // Find the editor that matches the contents of the TextDocument returned by the provider.
        // If there are multiple editors, the first editor is assumed to be the dropped editor.
        const editor = vscode.window.visibleTextEditors.filter(v => v.document === _document)[0];

        // Insert at the drop position and at the end of the file at the same time.
        editor?.edit((editBuilder: vscode.TextEditorEdit) => {
            // Insert at the end of the file.
            editBuilder.insert(new vscode.Position(editor.document.lineCount, 0), "This is the EOF");
        });

        // The above process shifts the insertion position and activeEditor,
        // so an empty string should be returned here.
        return {
            insertText: ""
        };
    }
}