How to get the base directory in visual studio code snippet?
Asked Answered
D

3

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? :)

Deathwatch answered 21/1, 2018 at 10:53 Comment(0)
D
45

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

Deathwatch answered 21/1, 2018 at 11:37 Comment(3)
How to escape \Volumes\my-project-path\ParentFolder\MyFolder ?Luker
Nevermind found it too: ${TM_DIRECTORY/^.+\\\\(.*)$/$1/}Luker
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 regex101.com/r/kc7oNF/1Pending
E
13

This supports Windows & Unix:

${TM_DIRECTORY/^.+[\\/\\\\]+(.*)$/$1/}
Eyepiece answered 9/8, 2021 at 9:20 Comment(0)
Q
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/}
Qp answered 22/12, 2020 at 15:59 Comment(6)
What is this language called? I'd like to understand it to use it on my own.Legg
@Legg I think it's just plain JavaScript. It's just escaping the strings due to parsing.Qp
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?Legg
@Legg are you using Linux/WSL or Windows? That code works only for Windows.Qp
@Legg I'm sorry, it's not plain JavaScript. VSCode follows the TextMate syntax macromates.com/manual/en/snippets. You can learn more about it here: code.visualstudio.com/docs/editor/userdefinedsnippetsQp
Big help! Thanks! I'm on linux btw, is there some keyword I should look out for?Legg

© 2022 - 2024 — McMap. All rights reserved.