Sublime Forum

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

#1

Hi,

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

echo "XY"; $var = "something;

into

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]
<![CDATA[
if ($1) {

$SELECTION
}

]]>

php.if

source.php
[/code]

Thank you!

0 Likes

#2

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:

    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:

    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

<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>
0 Likes