Sublime Forum

Usage of $TM_SELECTED_TEXT

#1

hello,

how can I make use of $SELECTION? A similar question has been asked here.

When I select a text in the editor, then go to Tools / Snippets… and select my snippet the selected text is not inserted.

My snippet:

<snippet>
    <content><![CDATA[
---------------
$TM_SELECTION
---------------
]]></content>
    <tabTrigger>fancySnippet</tabTrigger>
</snippet>

the output:

---------------

---------------

I don’t understand why it is not working. According to the other thread, it works in the console with

>>> view.run_command('insert_snippet', {'name':'Packages/User/fancy_snippet.sublime-snippet'})

but even that is not working.

Can anyone explain how $SELECTION should be used?

thank you

0 Likes

#2

I believe that this is not working for you because the variable that represents the selection is $TM_SELECTED_TEXT (or $SELECTION) and not $TM_SELECTION. Something like the following should work for you:

<snippet>
    <content><![CDATA[
--------------------
${TM_SELECTED_TEXT}
--------------------
]]></content>
    <tabTrigger>fancySnippet</tabTrigger>
</snippet>
2 Likes

#3

It seems that snippets though can be launched from plugins, can’t receive their usual $1, $2… $0 user interactive input… so, the only way is having both an interactive snippet with its $1, $2… $0 active parameters and besides a plugin taking the selection and inserting it in the text of the same snippet.

I have don these but needed to repeat the snipped for each syntax as with each syntax you have to determine the comment char:

,{ "keys": ["f5"], "command": "toggle_comment", "args": { "block": false } }
,{ "keys": ["shift+f5"], "command": "comm_insert" }

And then:

import sublime, sublime_plugin

class commInsertCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        s = view.sel()[0]
        start = s.a
        end = s.b
        sel = view.substr(sublime.Region(start, end))

        commC = ';'
        syntax = view.settings().get('syntax').split('/')[-1].split('.')[0]
        if 'LaTeX' in syntax:
            commC = '%'
        elif 'Bib' in syntax:
            commC = '%'
        elif 'Plain' in syntax:
            commC = '='
        elif 'Python' in syntax or 'Ruby' in syntax:
            commC = '#'

        block = f'''\
{commC} {'='*len(sel)} {commC}
{commC} {sel} {commC}
{commC} {'='*len(sel)} {commC}
'''
        view.replace(edit, sublime.Region(start, end), block)

And the snippets…

<snippet>
	<content>
		<![CDATA[
====${1/./=/g}
= ${1:Your Comment Goes here} =
====${1/./=/g}
$0]]>
	</content>
	<tabTrigger>
		comm
	</tabTrigger>
	<scope>text.plain</scope>
</snippet>

but one snippet for each scope you want it:

<snippet>
	<content>
		<![CDATA[
# ${1/./=/g} #
# ${1:Your Comment Goes here} #
# ${1/./=/g} #
$0]]>
	</content>
	<tabTrigger>
		comm
	</tabTrigger>
	<scope>source.python, source.ruby</scope>
</snippet>
0 Likes