Hi there I am trying to make an sublime text snippet and i would like to convert an camelCase word to snake_case. I do know there are plugins that allow you to convert string to snake_case but i want to do it through sublime text snippets.
I have a snippet like below.
<snippet>
<content><![CDATA[
/**
* ${TM_FILEPATH/^.+\/(\w+)\.php$/${1}/} belongs to many (many-to-many) ${1/^((.+)ies)|(.+[^s])s$/\u(?1$2y:$3)/}.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function $1()
{
return \$this->belongsToMany('App\\${1/^((.+)ies)|(.+[^s])s$/\u(?1$2y:$3)/}', '${TM_FILEPATH/^.+\/(\w+)\.php$/\l${1}/}_$1', '${TM_FILEPATH/^.+\/(\w+)\.php$/\l${1}/}_id', '${1/^((.+)ies)|(.+[^s])s$/\l(?1$2y:$3)/}_id');
}
]]></content>
<!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
<tabTrigger>btm</tabTrigger>
<!-- Optional: Set a scope to limit where the snippet will trigger -->
<scope>source.php</scope>
<description>Eloquent belongsToMany() (pivot) relation</description>
</snippet>
And as an output it gives me.
/**
* UserMessages belongs to many (many-to-many) Role.
*
* @return \Illuminate\Database\Eloquent\Relations\BelongsToMany
*/
public function roles()
{
return $this->belongsToMany('App\Role', 'userMessages_roles', 'userMessages_id', 'role_id');
}
What i want to end up is the userMessages to be user_messages. Any idea how to accomplish that.
Many thanks.
An example of a snippet that does something like this is the following, based on your example but shortened up for clarity (also I changed the scope to embedding.php
so it would trigger with the syntax that I use for PHP). You should be able to adapt this to your needs in your larger snippet example.
<snippet>
<content><![CDATA[
// ${1/^([A-Z])|(?:([A-Z]))/(?1\l$1:)(?2_\l$2:)/g}
public function ${1}()
{
$0
}
]]></content>
<tabTrigger>btm</tabTrigger>
<scope>embedding.php</scope>
<description>Eloquent belongsToMany() (pivot) relation</description>
</snippet>
The basis of this can be seen in the snippets page in the unofficial documentation. The expansion of a variable in a snippet takes the form ${variable/regex/format_string/options}
. The regex uses the boost library regular expressions and format strings.
Boost supports conditional replacement in the form of (?Ntrue:false)
, where for capture group N
the replacement text is true
if the match captured something or false
if it did not.
Here we use an alternation in the regular expression to have two capture groups, so that we can supply two different replacements depending on which of the items matches. The first capture group captures a leading uppercase character and just transforms it to lower case, while the second one (not anchored to the start of the line) does the same and also precedes the match with an underscore.