Sublime Forum

Conditional logic in snippets?

#1

In short: Is it possible to use a conditional (an “if” statement) within a Sublime Text 2 snippet?

My goal: Detect if the selection has single quotes. If so, remove the single quotes and change the first field marker value.

In Detail:

I currently have this simple snippet:

<snippet> <content><![CDATA[ <cfqueryparam cfsqltype="cf_sql_${1:integer}" value="$SELECTION"> ]]></content> </snippet>

It works great. I highlight some text, and then it puts the ColdFusion cfQueryParam tag around it:

Before: #someVariable# After: <cfqueryparam cfsqltype="cf_sql_integer" value="#someVariable#">

This accounts for 60% of its uses. Almost all of the other 40% are for strings. In these cases I need to type out the correct field type and manually remove the single quotes:

Before: '#someVariable#' After: <cfqueryparam cfsqltype="cf_sql_integer" value="'#someVariable#'"> Manual: <cfqueryparam cfsqltype="cf_sql_varchar" value="#someVariable#">

This adds 20-30 seconds onto a 15 second process of updating each query. And after several thousand uses of this snippet, and many times that number to go before I finish this project, that manual process is getting tiresome. So I’d like to insert some conditional logic that looks for single quotes in the selection and then alters the snippet based on that so that the above “Manual” step is automated for me. Is this possible?

I looked around online and found one tutorial explaining how to do a find/replace with Regex that looked like it might work to remove the single quotes. However, unless I can automate changing the field marker value as well that won’t help, as I need to see the single quotes to know which lines to manually change after I apply the snippet (I usually apply it to many lines at once).

Any help would be greatly appreciated.

0 Likes

Snippets with functions and multiple values - is that possible?
#2

Not possible with snippets, but might be worth looking into creating some macros to do this for you.

0 Likes

#3

This is perfectly feasable with:

<cfqueryparam cfsqltype="cf_sql_${SELECTION/(\d+$)|(.*)/?1:integer:?2:varchar/}" value="$SELECTION">

You may change both SELECTION with 1, so that you may enter the value and the tag will refresh.

1 Like

#4

 
Do you know of any documentation or other resources related to this functionality?

0 Likes

#5

http://sublime-text-unofficial-documentation.readthedocs.io/en/latest/extensibility/snippets.html#substitutions

2 Likes

#6

The syntax may be a little scary first, but actually it is just regex replace after all, if you master regular expressions it will be just as easy to create those advanced snippets.

0 Likes