24

I am trying to get the file current directory in a snippet for visual studio code.

VSCode has a variable: TM_DIRECTORY, which is the fullpath.

eg:

{folder: "$TM_DIRECTORY"}

would be replaced by

{folder: "/Volumes/my-project-path/ParentFolder/MyFolder"}

But I want only MyFolder.

Normally, we can use a transform as indicated in the docs. Sublime Text works in the same way. But for as much as I try, the snippet simply outputs the whole regex.

Could someone answer with the magical variable/transform? :)

Kev
  • 5,049
  • 5
  • 32
  • 53

3 Answers3

42

Ok, finally found it.

${TM_DIRECTORY/^.+\\/(.*)$/$1/} gives the base directory.

The part I didn't get was the "double escape" of the directory separator / -> \\/.

Kev
  • 5,049
  • 5
  • 32
  • 53
  • How to escape \Volumes\my-project-path\ParentFolder\MyFolder ? – pungggi Mar 24 '18 at 19:38
  • 9
    Nevermind found it too: `${TM_DIRECTORY/^.+\\\\(.*)$/$1/}` – pungggi Mar 24 '18 at 19:40
  • 1
    I dont get how vscode snippets are working but definitely it differ from regex101. I tried this `${TM_DIRECTORY/(\\w+)$/$1/}` and it just doesnt work, thought I expected it to take last word before end of string as it does here https://regex101.com/r/kc7oNF/1 – godblessstrawberry May 27 '20 at 12:07
11

This supports Windows & Unix:

${TM_DIRECTORY/^.+[\\/\\\\]+(.*)$/$1/}
Pluveto
  • 456
  • 5
  • 9
8

I wanted to add that in Windows the code above will print the entire directory.

You need to add a quadruple backslash vs the forward-slash:

${TM_DIRECTORY/^.+\\\\(.*)$/$1/}
Jose A
  • 10,053
  • 11
  • 75
  • 108
  • What is this language called? I'd like to understand it to use it on my own. – sayandcode Nov 22 '22 at 07:25
  • @sayandcode I think it's just plain JavaScript. It's just escaping the strings due to parsing. – Jose A Nov 22 '22 at 14:50
  • Plain JS? I tried using this snippet in Neovim, and its not working at all. I assumed it was some kind of regex. What do you mean by plain JS? – sayandcode Nov 23 '22 at 06:39
  • @sayandcode are you using Linux/WSL or Windows? That code works only for Windows. – Jose A Nov 23 '22 at 13:40
  • 1
    @sayandcode I'm sorry, it's not plain JavaScript. VSCode follows the TextMate syntax https://macromates.com/manual/en/snippets. You can learn more about it here: https://code.visualstudio.com/docs/editor/userdefinedsnippets – Jose A Nov 23 '22 at 13:42
  • Big help! Thanks! I'm on linux btw, is there some keyword I should look out for? – sayandcode Nov 23 '22 at 13:53