Search code examples
javascriptphpvisual-studio-codeshortcutcode-snippets

VS Code how to create custom shortcut / snippet?


What is the simpliest way to create custom shortcuts for methods I'm using everydays?
Like dd() Log::info() or console.log().

Let me explain exactly what behavior I want for my shortcut:

  1. I want to select my variable
  2. Press keyboard shorcut
  3. Break a line
  4. Passt the code I want with the selected variable

Solution

  • I came up with this solution, thanks to @Mark in comments, related to this thread : How can I insert a snippet on a new line with vscode?

    1. Install Multi-command VSCode extension

    2. Open the settings of the extension and click on Edit in settings.json enter image description here

    3. Implement your shortcut code (e.g console.log())

       "multiCommand.commands": [
      
           {
               "command": "multiCommand.console.log",
      
               "sequence": [
                   "editor.action.clipboardCopyAction",
                   "editor.action.insertLineAfter",
                   {
                   "command": "editor.action.insertSnippet",
                   "args": {
                       "snippet": "console.log(\"$CLIPBOARD: \", $$CLIPBOARD)\n$0"
                   }
                   },
               ]
           },
      
    4. Then in VSCode go to Preferences -> Keyboard Shortcuts, open keybindings.json keybindings.json location

    5. Add the path binding command

      // (new version)
      {
          "key": "ctrl+1", 
          "command": "multiCommand.console.log" 
      }
      
      // (old version)
      {
          "key": "ctrl+1",
          "command": "extension.multiCommand.execute",
          "args": { "command": "multiCommand.console.log" }
      }