Stofke
Stofke

Reputation: 2958

Setting up a snippet in Visual Studio Code with regex

{
    "Comment": {
        "prefix": "#",
        "body":  "<!-- ${TM_FILEPATH/([^/]*\/[^/]*)$/$1/} -->"
    }
}

I have set up the about code snippet, the purpose is to add a comment that adds the file's base directory and file name <!-- templates/base.html --> like this but discards the rest of the path. I believe this is originally based on TextMate snippets.

enter image description here

I have tried everything but I can't get it to work, it's probably something silly but I don't see what I'm doing wrong.

Using just TM_FILEPATH
without the regex results in <!-- /Users/johndoe/Sites/blog/blog/templates/base.html -->

I used this https://code.visualstudio.com/docs/editor/userdefinedsnippets to find an example to base my code on. The example is this one:

${TM_FILENAME/(.*)\\..+$/$1/}
  |           |        | |
  |           |        | |-> no options
  |           |        |
  |           |        |-> references the contents of the first
  |           |             capture group
  |           |
  |           |-> regex to capture everything before
  |               the final `.suffix`
  |
  |-> resolves to the filename

Thanks to the ideas of the 2 commenters I was finally able to get it to work.

One commenter put me on track with the double backslashes to catch both Windows and Unix style slashes.

The other commenter suggested the square brackets.

Final result:

{
    "Comment": {
        "prefix": "#",
        "body":  "<!-- ${TM_FILEPATH/.*[\\/](.*[\\/].*)$/$1/} -->",
    }
}

Upvotes: 2

Views: 5356

Answers (2)

wp78de
wp78de

Reputation: 18950

Let's try it with a character class that takes account of both path separator types and helps us to escape properly at the same time:

{
    "Comment": {
        "prefix": "#",
        "body":  [  
            "<!-- ${TM_FILEPATH/.*[\\/](.*[\\/].*)$$/$1/} -->",
        ]
    },
}

Upvotes: 0

Mark
Mark

Reputation: 181379

Try something like this:

"Comment": {
    "prefix": "#",
    "body":  [

      "<!-- ${TM_FILEPATH/.*\\\\(.*\\\\.*)$$/$1/} -->",

      "<!-- ${TM_DIRECTORY/.*\\\\(.*)$/$1/}/${TM_FILENAME} -->",
    ]
},

Those two lines in the body should be equivalent. That works for the Windows directory style, like :

 c:\Users\Mark\asdf\experimental\src\js\main.js

Since your path.separators are / try something like:

"<!-- ${TM_FILEPATH/.*\/(.*\.*)$/$1/} -->", 
"<!-- ${TM_FILEPATH/.*\\/(.*\\.*)$/$1/} -->",
"<!-- ${TM_FILEPATH/.*\\\/(.*\\\.*)$/$1/} -->",
"<!-- ${TM_FILEPATH/.*\\\\/(.*\\\\.*)$/$1/} -->",

I just don't know how many backslashes you will need (and I can't test it here) for your OS.

Upvotes: 1

Related Questions