问题
I work with large html files that I would like to fragment into separate files. The process of doing this is quite tedious as it requires copying the code, creating a new file, pasting it in the new file, and then selecting a folder and a new name to save it under.
Is there a built-in shortcut, macro or extension for VS Code for making this easier?
回答1:
Here is a macro which does what you want. I am using the macro extension multi-command but there are others.
In settings.json:
"multiCommand.commands": [
{
"command": "multiCommand.newFileWithContent",
"sequence": [
// choose which one you want
"editor.action.clipboardCutAction",
// "editor.action.clipboardCopyAction",
"workbench.action.files.newUntitledFile",
"editor.action.clipboardPasteAction",
// prompt for save immediately?
"workbench.action.files.saveAs",
]
},
Then trigger it either through the command palette (search for "multi") or with a keybinding (keybindings.json):
{
"key": "strl+alt+b", // your keybinding choice
"command": "extension.multiCommand.execute",
"args": { "command": "multiCommand.newFileWithContent" }
},
I don't know how to automate the "selecting a folder and a new name to save it under" part of your question. I think you are still going to have to do that manually, but there is some handy "intellisense" for that in the "saveAs" dialog.
Update in 2020
After I came up with this answer, see in vscode how can I quickly generate a new file with datetime in the name?
I thought there might be a better way to handle creating the file with a task and prompting for a folder and filename in one go. You lose the saveAs
intellisense on your folder structure, but it is a pretty good technique to know in any case. And a macro isn't needed. In a bash
shell:
{
"version": "2.0.0",
"tasks": [
{
"label": "newFile",
// assuming your folder name isn't static
"command": "echo '${selectedText}' > ${input:folderName}/${input:fileName}.html",
"type": "shell",
"problemMatcher": [],
"presentation": { // terminal handling which you may not care about and could delete
"echo": false,
"reveal": "silent",
"focus": false,
"panel": "shared",
"showReuseMessage": false,
"clear": true
},
"promptOnClose": false
}
],
"inputs": [
{
"type": "promptString",
"id": "folderName",
"description": "Complete my folder name.",
"default": "folder"
},
{
"type": "promptString",
"id": "fileName",
"description": "Complete my file name.",
"default": "new file name"
}
]
}
Some keybinding to run that task (or just run it from the command palette Run Task
command):
{
"key": "alt+r", // whatever you choose
"command": "workbench.action.tasks.runTask",
"args": "newFile"
},
That's it, select your task, and run the task Alt+R.
来源:https://stackoverflow.com/questions/57611402/is-there-a-vs-code-shortcut-for-creating-a-new-file-from-selected-or-clipboard-c