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

Visual studio code snippet choices and variables


I am writing my own snippet to console.log

{  
  "Print to console": {
    "scope": "javascript,typescript",
    "prefix": "debug",
    "body": [
      "console.log('${1|[Debug],[Server],[$TM_FILENAME]|}','${2:~Line: $TM_LINE_NUMBER ~ File:$TM_FILENAME}',${3:$TM_SELECTED_TEXT}); //debug",
      "$4"
    ],
    "description": "Log output to console"
  }
}

Everything is ok except instead of file name static text TM_FILENAME is getting displayed in choices for placeholder '$1' ${1|[Debug],[Server],[$TM_FILENAME]|}. How can I make filename to be displayed here? Thanks for suggestions


Solution

  • Although you cannot directly use variables in a snippet choice, you can workaround it like this:

      "Print to console": {
        "scope": "javascript,typescript",
        "prefix": "debug",
        "body": [
    
          // moved brackets in the choice
          "console.log('[${1|Debug,Server],fileName|}]','${2:~Line: $TM_LINE_NUMBER ~ File:$TM_FILENAME}',${3:$TM_SELECTED_TEXT}); //debug",
          "$4"
        ],
        "description": "Log output to console"
      },
    
      "getfileName": {
        "scope": "javascript,typescript",
        "prefix": "fileName",   // <= same exact prefix as appears in the choice above
        "body": [
          "$TM_FILENAME"
        ],
        "description": "get the file name"
      }
    

    The idea being that the fileName choice is actually another snippet that you can trigger after making the choice. After you select fileName you will have to Ctrl+Space to bring up the second snippet. It is a little more work but it does allow you to get "variable-like" behaviour in a snippet choice. And in the second snippet you can add or modify the file name however you like.

    Also, sometimes you have to modify the choice a bit. I modified yours but the output is the same. Otherwise [fileName] is printed and that won't be seen as a match for the other fileName prefix. Although in your case, you could leave it as :

    "console.log('${1|[Debug],[Server],[fileName]|}','${2:~Line: $TM_LINE_NUMBER ~ File:$TM_FILENAME}',${3:$TM_SELECTED_TEXT}); //debug",
    

    in the first snippet and then make the second prefix like so:

    "prefix": "fileName]",  // note the trailing bracket
    

    Same result, just be aware to adjust the second prefix to match what is actually printed out by the choice selection or it won't work.

    snippet choice variable