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

vs code snippet: how to use variable transforms twice in a row


See the following snippet:

    "srcPath":{
    "prefix": "getSrcPath",
    "body": [
        "$TM_FILEPATH",
        "${1:${TM_FILEPATH/(.*)src.(.*)/${2}/i}}",
        "${TM_FILEPATH/[\\\\]/./g}"
    ]
},

The output of lines 1-3 is :

D:\root\src\view\test.lua
view\test.lua
D:.root.src.view.test.lua

How can I get output like 'view/test.lua'?


Solution

  • Try this snippet:

    "srcPath":{
      "prefix": "getSrcPath",
      "body": [
          "$TM_FILEPATH",
          "${TM_FILEPATH/.*src.|(\\\\)/${1:+/}/g}",
          "${TM_FILEPATH/[\\\\]/\\//g}"
      ]
    }
    

    transform on path snippet

    .*src.|(\\\\) will match everything up to and including the ...src\ path information. We don't save it in a capture group because we aren't using it in the replacement part of the transform.

    The (\\\\) matches any \ in the rest of the path - need the g flag to get them all.

    Replace: ${1:+/} which means if there is a capture group 1 in .*src.|(\\\\) then replace it with a /. Note we don't match the rest of the path after src\ only the \'s that might follow it. So, not matching those other path parts just allows them to remain in the result.


    You were close on this one:

    "${TM_FILEPATH/[\\\\]/\\//g}" just replace any \\\\ with \\/.