Search code examples
sublimetext3sublimetext-snippet

Access Project Root Path in Sublime Text 3 Snippet


I'm trying to work out a way to access just the file path from the root of my project in a snippet.

I can access the full file path with ${TM_FILEPATH} but I'm trying to set up a file documentation snippet that will automatically get the path to add to the documentation block like so:

/**
 * app/Controllers/MyClass.php
 *
 * Class summary here.
 *
 * @author Author Name <[email protected]>
 * @copyright  2016 Company Name
 * @package  MyClass
 */

with just TM_FILEPATH I get this:

/**
 * /Users/username/Code/project/app/Controllers/MyClass.php
 *
 * Class summary here.
 *
 * @author Author Name <[email protected]>
 * @copyright  2016 Company Name
 * @package  MyClass
 */

Is there a way to parse ${TM_FILEPATH} to get just the part I need, or is it possible to set up a variable I can use myself like ${ROOT_PATH} or similar?


Solution

  • Snippets support PCRE-compatible regular expression-based substitutions. The following substitution should do what you're looking for, assuming that the part of the path you want to keep always starts with app:

    <snippet>
        <content><![CDATA[${TM_FILEPATH/^\/.*\/(?=\bapp\b)//}]]></content>
        <tabTrigger>filepath</tabTrigger>
        <description>path to current file</description>
        <scope>source.php</scope>
    </snippet>
    

    To break it down, our input is TM_FILEPATH, then our capture sequence (delimited by /) is ^\/.*\/(?=app) (^ matches the beginning of the string, \/ is the literal / character, .* matches any sequence of any characters (.) of any length (*). The capture sequence end with a literal /. The (?=\bapp\b) group is a positive lookahead, asserting that app can be matched ahead, but doesn't actually capture it. The \b escape characters before and after app indicate that app should be surrounded by word break characters (which include /). This is to protect against matching a path like this:

    /Users/username/Code/company_web_app/app/Controllers/SomeClass.php
    

    where app is in the project's name.

    Finally, the format string section // is empty, as we just want to discard the match, and leave the rest.

    Here is an example explaining in more detail how it all works.