Search code examples
visual-studio-codecode-snippetsvscode-snippets

VSCode Snippet syntax for duplicating snippet lines


Let's say I want to create a VSCode snippet for a typescript interface, one that looks like this:

interface MyInterface{ 
  prop1: string; 
  prop2: string;
  prop3: string
}

Now I could just create the following snippet:

"myinterface": {
  "prefix": "myinterface",
  "body": [
    "interface MyInterface{ ",
    "  prop1: string; ",
    "  prop2: string;",
    "  prop3: string",
    "}"
  ],
  "description": "not smart interface creator"
}

But what if I wanted to have a prop4, prop5, or prop6 in my interface? Is there anyway to conditionally extend the snippet, so that by hitting Tab I would be prompted to add another prop field to the interface with the format ${1:propX}: ${2:string};?

Another use case is writing out an array:

const myArray = [val1, val2, val3]

Solution

  • I don't think there is any way to directly do what you want. But you can come pretty close with method 2 below.

    Method 1

    "PS3": {
      "prefix": "ps3",
      "body": [
        "interface MyInterface{",  
        "${1/([^,]+)([,\\s]*|)/\t$1: string;${2:+\n}/g}",
        "}"
      ]
    },
    

    This is similar to the technique I use in snippets with variable number of arguments. Here is a demo of the above:

    add multiple props to a snippet

    But you can't select and easily edit the variables or types with this method.


    Method 2

    This is trickier, but will result in the keys and types selected for easier changing. You need 2 snippets"

    "myinterface": {
      "prefix": "myinterface",
      "body": [
        "interface MyInterface{ ",
    
        // I jazzed it up by adding a choice transform
        "\t${1:propX}: ${0:${2|string,int,bool|}};",
        "}"
      ],
      "description": "sorta smart interface creator"
    },
    
    "addProps": {
      "prefix": "[int, bool, string]",  // note multiple prefixes
      "body": [
        "$TM_SELECTED_TEXT;",
        "${1:propX}: ${0:${2|string,int,bool|}}",
      ],
      "description": "add props to interface"
    },
    

    Basically, this uses the end of the first snippet as the prefix for the additional key: type pairs. Demo:

    add choices to snippet

    After tabbing to select your choice of int/bool/string tab again to move to the end - that will automatically select what you choose from int/bool/string.

    Now you can trigger the suggestion of the second snippet with Ctrl+Space to insert one key: type pair at a time. And note that that second snippet has three prefixes to match your type choice, reinserts your choice at the end of the line and adds another key: type line below.