Home Download Buy Blog Forum Support

How to wrap code block in IF condition in sublime text 2?

How to wrap code block in IF condition in sublime text 2?

Postby WhosSatoshi on Sun Jan 26, 2014 8:01 am

Hi,

I often want to wrap some code block to an if statement. Example:

Code: Select all
echo "XY";
$var = "something;


into

Code: Select all
if (condition) {
    echo "XY";
    $var = "something;
}


Can I do that in Sublime Text 2 by a simple keyboard shortcut? I tried to create a sublime snippet (see below) but the $SELECTION variable contains beginning spaces so the indentation is wrong after applying the snippet.

Code: Select all
<snippet>
    <content><![CDATA[
if ($1) {

$SELECTION
}

]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>php.if</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.php</scope>
</snippet>


Thank you!
WhosSatoshi
 
Posts: 1
Joined: Sun Jan 26, 2014 7:59 am

Re: How to wrap code block in IF condition in sublime text 2?

Postby ntenney on Thu Jan 30, 2014 5:55 pm

Your snippet seems to do the right thing if you indent the variable in the snippet, and only select up to the first non whitespace character in the block you wish to indent. For example, if I have the following in a file:
Code: Select all
    some stuff
    some other stuff
    even more stuff

and my selection is starts at the s on the first line and includes all subsequent lines, then I get:
Code: Select all
    if () {
        some stuff
        some other stuff
        even more stuff
    }

Note that the if is indented as far as the original lines, and that the lines are indented properly from the if.

Here is how I modified your snippet
Code: Select all
<snippet>
    <content><![CDATA[
if ($1) {
    $SELECTION
}

]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <tabTrigger>php.if</tabTrigger>
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source.php</scope>
</snippet>
ntenney
 
Posts: 66
Joined: Thu May 03, 2012 9:10 pm


Return to General Discussion

Who is online

Users browsing this forum: Exabot [Bot], Yahoo [Bot] and 19 guests