Sublime Forum

How do I insert a snippet with $PARAMn variables from a plugin?

#1

I didn’t find the answer to this anywhere else, and I just discovered what it was tonight, so I thought I would share.

I’m creating a package that I want my users to be able create their own (possibly massive) Snippet files with their own dynamic ${PARAMn} placeholders to be filled by a single command. I finally figured out how to do it, and from what I can see, this information isn’t anywhere else to be found, including in the Unofficial Documentation, which, at this writing, only mentions “not covered here” on the Snippets page.

Here is the solution.

This Snippet in Packages/User/test_with_args.sublime-snippet:

<snippet>
    <content><![CDATA[
Hello, param1 = [${PARAM1}] param2 = [${PARAM2}] and param3 = [${PARAM3}].
Today's subject is:  $my_custom_param_name
]]></content>
    <!-- Optional: Set a tabTrigger to define how to trigger the snippet -->
    <!-- <tabTrigger>hello</tabTrigger> -->
    <!-- Optional: Set a scope to limit where the snippet will trigger -->
    <scope>source comment</scope>
</snippet>

with this in your command:

args = {
    'name': 'Packages/User/test_with_args.sublime-snippet',
    'PARAM1': "alpha",
    'PARAM2': "bravo",
    'PARAM3': "charlie",
    'my_custom_param_name':  my_dynamic_subject_func()
}
self.view.run_command("insert_snippet", args)

Produces this output:

Hello, param1 = [alpha] param2 = [bravo] and param3 = [charlie].
Today's subject is:  Adding Features to Sublime Text.

Notes:

  • Parameter names can be any combination of letters or numbers, including things like “1” which would provide the string for the first numbered parameter.
  • The call to my_dynamic_subject_func() happens when Python evaluates the args dictionary to pass it to the self.view.run_command() function. Naming a function from within an external Snippet file doesn’t do anything.
  • The curly braces are optional and are only needed when there is surrounding text or punctuation that could confuse the Snippet parser about the boundaries of the parameter name. You can also use them for code readability if you wish.

That opens the door to a LARGE number of possibilities for dynamic content. :slight_smile:

0 Likes

#2

from what I remember, it is not limited to PARAMn, you can pass any named dictionary key and refer to it from the snippet

1 Like

#3

Excellent! I will try it out! Then it would seem you can make up your own names and use them? I will try it.

0 Likes

#4

You can indeed do that; that is the basis of EnhancedSnippets for example.

1 Like

#5

Sweet!! I’m sure that Package’s source code will be able to teach me a lot!

Hiya, Terence!! Honored to be in touch with you! 2 things:

  • there is a recent “thank you” post aimed in your direction, and
  • I am also very interested in getting help with this post if you haven’t already seen it.
0 Likes