Home > database >  how to paste a constant block of code in vscode
how to paste a constant block of code in vscode

Time:04-10

The requirement is to create a constant and save it in vscode and assign a shortcut to it and whenever the shortcut is used the stored block of code gets pasted automatically.

For example: the below code is something that i need to add in multiple files

if __name__ == "__main__":
    s = [1,2,3,4,5]
    print(fun(s))

So, i need to store this in one place just once in vscode and assign a shortcut key to it, next time using the shortcut key the codeblock should get pasted as it is. Also, would not want the content currently copied on clipboard to be affected.

Is there a way to do this?

CodePudding user response:

You can go with the Snippets. Create any code snippet you like, then add a keyboard shortcut to it. It gives the ability to not only insert snippet by a shortcut but also with a prefix (for example 'ifmain').

First, you create code snippet. Navigate to File > Preferences > User snippets > python.json (or ctrl shift p 'configure user snippets'). Create any snippet here (in json syntax), then save the file. Example of snippet for code you provided:

{
  "if name main": {
    "prefix": "ifmain",
    "body": [
      "if __name__ == '__main__':",
      "    s = [1, 2, 3, 4, 5]",
      "    print(fun(s))"
    ],
    "description": "my cool snippet"
  }
}

Secondly, you add a keyboard shortcut to snippet. File > Preferences > Keyboard shortcuts (ctrl k ctrl s). Then click small icon located on top right corner named 'Open Keyboard Shortcuts', as shown here:

Screenshot

Add shortcut to the insert snippet command then save the file. Example:

{
  "key": "ctrl k 1",
  "command": "editor.action.insertSnippet",
  "when": "editorTextFocus",
  "args": {
    "langId": "python",
    "name": "if name main"
}

Press ctrl k 1 > it will insert snippet. Start typing 'ifmain' then smash Tab > it will insert snippet.

  • Related