首页 > 解决方案 > VS Code:在编辑器的当前目录中创建文件

问题描述

ctrl是否可以在按下键盘快捷键+ nfor时在与编辑器中处于活动状态的文件相同的文件夹中创建一个新文件explorer.newFile

我可以通过查看面包屑来判断它是否是正确的文件夹,并且大多数情况下都关闭了文件资源管理器。但是,该命令似乎在文件资源管理器打开或聚焦的最后一个文件夹中创建了一个文件。

标签: visual-studio-codevscode-settingsvscode-tasks

解决方案


您可以通过重载该explorer.newFile命令的默认键绑定来运行任务来执行此操作。这是键绑定:

{
  "key": "ctrl+n",
  "command": "workbench.action.tasks.runTask",
  "args": "newFile",
  "when": "editorFocus"  // must have an editor focused
},

和任务(在tasks.json中):

{
  // See https://go.microsoft.com/fwlink/?LinkId=733558
  // for the documentation about the tasks.json format
  "version": "2.0.0",

  "tasks": [
    {
      "label": "newFile",

      "command": "touch '${fileDirname}/${input:fileName}' && code '${fileDirname}/${input:fileName}'",

      "type": "shell",
      "problemMatcher": [],
    },
   ],

  "inputs": [
    {
      "type": "promptString",
      "id": "fileName",
      "description": "Complete my file name.",
      "default": "new file name"
    }
  ]
}

这将在与活动编辑器目录相同的目录中创建一个文件——它会询问你文件名——然后打开它。

我使用 bash 命令touch创建文件(如果它不存在),如果您使用不同的 shell,则需要touch.


推荐阅读