Skip to content

Bring along imports when copy and pasting code across files #50187

Closed
@mjbvz

Description

@mjbvz

Feature request

From microsoft/vscode#66236

When copy and pasting code between two TS/JS files, we should support adding the required imports on paste. For example, with the following code:

import fs from 'fs';
import http from 'http';

http.createServer((req, res) => {
    const data = fs.readFileSync('bla');
    res.write(data);
    res.end()
})

If I copy fs.readFileSync('bla') and paste it into a new file, an import for fs should also be added to the top of that file:

TS Server Protocol changes

VS Code is actively working on an API that lets extensions hook into copy and paste: microsoft/vscode#30066

Using this api, here's what I imagine the flow between VS Code and TS server would look like:

  1. User copies code

  2. VS Code tells TS Server about the copied range

  3. TS Server goes and writes whatever state it needs to re-create the imports. This state needs to be JSON serializable (so that TS Server can send it to VS Code). Just as an example, this could be something like (note! just for demonstration purposes, not intended to be what this actually looks like):

    {
        "referencedSymbols": [
             {"name": "default", "from": "node:fs"},
             {"name": "mySymbol", "from": "/full/path/to/file"}
        ]
    }
  4. TS Server returns this state to the VS Code extension which attaches it to the copied text (this can happen asynchronously)

  5. The user now pastes the code in another file

  6. VS Code sends TS Server a request with the following:

    • The paste location
    • The saved off state from step 3 / 4 (note that we may actually have to await this data if the server was slow to return here
  7. TS Server returns a text edit that adds the imports to the file

Metadata

Metadata

Assignees

Labels

CommittedThe team has roadmapped this issueFix AvailableA PR has been opened for this issueSuggestionAn idea for TypeScript

Type

No type

Projects

No projects

Relationships

None yet

Development

No branches or pull requests

Issue actions