Sublime Forum

How can I receive selected text in my plugin?

#1

hello,

I tried to make use of $SELECTION in my plugin. Using it directly does not work.

based on this example, found in the keymap:

{ "keys": ["\""], "command": "insert_snippet", "args": {"contents": "\"${0:$SELECTION}\""}, "context":
	[
		{ "key": "setting.auto_match_enabled", "operator": "equal", "operand": true },
		{ "key": "selection_empty", "operator": "equal", "operand": false, "match_all": true }
	]
},

It should be possible.

The plugin works fine and accepts the input argument.

if I print the arguments to the console, it shows:

${0:$SELECTION}

so it is literally receiving this string, instead of text selection. My guess is that I have to process SELECTION afterwards. Maybe the plugin InsertSnippet could reveal how this is done but I don’t know where it is located.

thank you

0 Likes

#2

You could get the selected text through the plugin like this.

import sublime
import sublime_plugin

class GetTextCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        sel = self.view.sel()[0]
        selected = self.view.substr(sel)
        print(selected)
0 Likes

#3

$SELECTION is a snippet feature and interpreted by the insert_snippet command. That’s why it doesn’t work as you expected.

1 Like