Search code examples
visual-studio-codevscode-snippets

How can I select a part of TM_DIRECTORY variable?


I want to select a part of the TM_DIRECTORY variable on VScode snippet. I mean I want to select Tests\Setup of the d:\Projects\Hakhsin\hakhsin\tests\Setup in code-snippet file. Look at this:

// On snippet file
"PHP Class": {
        "scope": "",
        "prefix": ["phpClass"],
        "body": [
            "<?php\n\nnamespace ${TM_DIRECTORY/(?<=(?:[\w:\\]hakhsin\\)).+(?=\\)//};\n\nclass ${TM_FILENAME_BASE} {\n\t$2\n}"
        ],
        "description": "New PHP Class"
    },

And I want to get this result:


namespace Tests\Setup;

class StorageFactory {

}

But I get this result:

<?php

namespace d:\Projects\Hakhsin\hakhsin\tests\Setup;

class StorageFactory {

}

Solution

  • It doesn't appear you can use variables inside of other variables in a snippet transform.

    You can try this code which is more "dynamic" than yours but not perfect:

    "${TM_DIRECTORY/([^\\\\]*\\\\){4}(.*)/${2:/capitalize}/}",
    

    The {4} in that is if you have 4 segments in the directory structure before the part you want, like d:\Projects\Hakhsin\hakhsin\tests\Setup The segments are d:\, Projects\, Hakhsin\ and hakhsin\. If that number of segments is known and stable than the snippet I showed works well.

    I doubt the number of those segments would vary within a project but might very well between projects - you would just have to change the {x} item for each project if so.