Search code examples
regexvisual-studio-codevscode-snippets

Visual Studio Snippet: Can I use TM_FILENAME to get a namespace from RELATIVE_FILEPATH?


I am toying with Visual Studio Snippets for a while now, and wonder if/how I can use TM_FILENAME to get a namespace from RELATIVE_FILEPATH. For example, I have:

RELATIVE_FILEPATH = src\model\RegisterModel.php

TM_FILENAME = RegisterModel.php

I want to strip the latter from the first, and the last \ as well, so I will end up with src\model

I can get it working if I use RegisterModel.php as a string, but not if I use TM_FILENAME as a variable. Is that even possible?

This is what works: ${RELATIVE_FILEPATH/(RegisterModel.php)//gi}

But I want something like this: ${RELATIVE_FILEPATH/(TM_FILENAME )//gi}

Thanks in advance!


Solution

  • This will get you what you want:

    "filepath": {
      "prefix": "rfp",
      "body": [
        "${RELATIVE_FILEPATH/(\\\\[^\\\\]*)$//i}",  // with lots of escapes
      ],
      "description": "directories of current file"
    }
    

    ${RELATIVE_FILEPATH/${TM_FILENAME}//gi} will not work as according to the grammar only a regex can go into that ${TM_FILENAME} spot in the transform. See snippet grammar.

    Relevant part of the grammar: transform ::= '/' regex '/' (format | text)+ '/' options


    ${RELATIVE_FILEPATH/[${TM_FILENAME}]//gi} results in:

    src\od\Rgsrod.php because [${TM_FILENAME}] is treated as a regex (just a alternate list of those characters literally) and so each of those characters is removed from the RELATIVE_FILEPATH.