Markus Mauch
Markus Mauch

Reputation: 1283

How to get the module id from TM_FILEPATH in a vscode snippet?

Is there a way to convert the value of the TM_FILEPATH variable to a module id?

I would like to create a snippet that resolves the module id:

d:\myrepo\client\store\calc.ts => <amd-module name="store/calc" />

{
    "prefix": "amd-module-name",
    "body": [
        "/// <amd-module name=\"${TM_FILEPATH/.*client\\\\(.*)\\..*$/$1/}\" />\n"
    ]
}

The snipped above gives me <amd-module name="store\calc" /> but how do I get rid of the back slash?

Upvotes: 1

Views: 259

Answers (1)

Mark
Mark

Reputation: 182141

Try this:

"someName" : {
    "prefix": "amd-module-name",
    "body": [
        "/// <amd-module name=\"${TM_DIRECTORY/(.*client[\\\\\\/])?([^\\/\\\\]*)([\\/\\\\])?/$2${3:+\/}/g}\/$TM_FILENAME_BASE\" />\n",
    ]
  },

It is lengthy but fairly powerful (and all those necessary double-escapings!).

This will handle directories with \ or / path separators.

[\\\\\\/] means either a \ or a / (you just need 3 escaping backslashes before a \ in an vscode snippet and two before a /)!!

So [^\\/\\\\]* means get characters until you hit a slash.

This regex will work with any number of directories under "client". Thanks in part to the global regex modifier g .

d:\myrepo\client\store\subStore\calc.ts => <amd-module name="store/subStore/calc" />

This part is nice: $2${3:+\/} that means insert matching group 2 and only if there is a matching group 3 add a backslash /. This comes into play accounting for the last directory with the file in it and changing the captured group 3 \ to a / as you want.

Upvotes: 2

Related Questions