numlock
numlock

Reputation: 3

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'?

Upvotes: 0

Views: 904

Answers (2)

Mark
Mark

Reputation: 182141

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 \\/.

Upvotes: 1

rioV8
rioV8

Reputation: 28763

With the extension File Templates you can insert a "snippet" that contains a variable and multiple find-replace operations.

With a key binding:

  {
    "key": "ctrl+alt+f",  // or any other combo
    "command": "templates.pasteTemplate",
    "args": {
      "text": [
        "${relativeFile#find=.*?src/(.*)#replace=$1#find=[\\\\/]#flags=g#replace=.#}"
      ]
    }
  }

At the moment only possible with a key binding or via multi command (or similar). Will add an issue to also make it possible by prefix.

Also some of the standard variables are missing.

Upvotes: 0

Related Questions