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

VsCode Snippet PlaceHolder default value File_Name_Base + uppercase


In the aim to gain some time in the future, I'm trying to create some snippets for VsCode.

There is the context. I have a tmp.hpp file in which I want to have

#ifndef TMP_HPP_
    #define TMP_HPP

#endif

My problem is, I want to be able to modify TMP by whatever I want. To do so I want it to be a default value Finaly, if i decide to modify TMP by WHATEVER I want to force WHATEVER to be upcase.

To be more precise, i want my ${1} to have default value : ${TM_FILE_BASE} and I also want ${1} and/or my ${TM_FILE_BASE} to be ${/upper}

Here is what i got for the moment :

"Creates a ifndef": {
    "prefix": "ifndef",
    "body": [
      "#ifndef ${${1:TM_FILENAME_BASE/(.*)/${1:/upcase}/}}_HPP_",
      "  #define ${${1:TM_FILENAME_BASE/(.*)/${1:/upcase}/}_HPP_",
      "",
      "#endif"
    ],
    "description": "Creates a basic ifndef"
}

Thanks


Solution

  • You need to use nested variables:

    "Creates a ifndef": {
        "prefix": "ifndef",
        "body": [
          "#ifndef ${1:${TM_FILENAME_BASE/(.*)/${1:/upcase}/}}_HPP_",
          "  #define ${1:${TM_FILENAME_BASE/(.*)/${1:/upcase}/}}_HPP_",
          "",
          "#endif"
        ],
        "description": "Creates a basic ifndef"
    }
    

    Pay attention to the ${1:${TM_FILENAME_BASE/(.*)/${1:/upcase}/}} part. Here, ${1:...} is the syntax for the placeholder, and thr ${TM_FILENAME_BASE/(.*)/${1:/upcase}/} inside it specifies the variable that is modified with a regex-based replacement (all the contents are matched and captured into Group 1 with /(.*)/ and replaced with the uppercased variant using ${1:/upcase}/} (here, $1 is the Group 1 value placeholder)).