Sublime Forum

Snippet, process each line of selection?

#1

Does anyone know if it is possible in a snippet to process each line of a selection in a loop?

I’d like to do something like

var1
var2
var3

and if I select those lines and run my snippet I want to produce:

$var1 = mysql_real_escape_string($record->{‘var1’});
$var2 = mysql_real_escape_string($record->{‘var2’});
$var3 = mysql_real_escape_string($record->{‘var3’});

of course the number of variables would be unknown though.

And then if thats possible I’d like to be able to create a snippet that could produce insert statements the same way:

mysql_query(“INSERT INTO myTable ( var1, var2, var3 )
VALUES ( ‘{$var1}’, ‘{$var2}’, ‘{$var3}’)”);

anyways for now I was just wondering if I could grab multiple lines like that and manipulate each of them

0 Likes

#2

It might be possible with something like this:

${TM_SELECTED_TEXT/(var([0-9]+))/?1:\$var$2 = etc/gm}

You would need to use \x27 for the apostrophes’. You might also be able to delete the selection (if it isn’t already overwritten?) with \b or \x08 (back-space) but I haven’t tested any of this. But presumably you would want to replace var with [a-zA-z_]{1,8}? or something similar.

Your second request might be approached in a different way. You could catch upto, say, 9 variables and not use the /gm modifiers.

0 Likes

#3

It may be simpler to use “Selection/Split into Lines”, and then use a simple snippet that operates on each selection in parallel

0 Likes

#4

Thanks for the replies,
how do you run a snippet in parallel?

in php I would do something like this:

foreach(preg_split("/(\r?\n)/", $selection) as $line){
    // do stuff with $line
}

I was hoping something similar was possible here. But it might not be an option.

0 Likes

#5

Change the selection position to the end of the line ( for each line) and run the snippet.

for line in selection.split("\n"):
    // do stuff with line
0 Likes