Mikey
Mikey

Reputation: 3017

VS Code: Create file inside the current directory of the editor

Is it possible to create a new file inside the same folder as the file that is active in the editor by the time the keyboard shortcut ctrl+n for explorer.newFile is hit?

I can tell if it's the correct folder by looking at the breadcrumbs and mostly have the file explorer toggled off. The command, however, seems to create a file inside the last folder opened or focused by the file explorer.

Upvotes: 1

Views: 1592

Answers (1)

Mark
Mark

Reputation: 182421

You can do this by overloading that explorer.newFile command's default keybinding to run a task instead. Here is the keybinding:

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

And the task (in 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"
    }
  ]
}

That will create a file in the same directory as the active editor's directory - it will ask you for the filename - and then open it.

I used the bash command touch to create the file (if it doesn't already exist), if you are using a different shell you will need the equivalent of touch.

Upvotes: 3

Related Questions