Maxim Yefremov
Maxim Yefremov

Reputation: 14165

api: how to get selected text from object sublime.Selection

How to get selected text in sublime text 3 plugin:

import sublime, sublime_plugin

class plugin_window__go_to_relative_plugin__Command(sublime_plugin.WindowCommand):
    def run(self):            
        window = self.window
        view = window.active_view()
        sel = view.sel()
        sublime.status_message("selection: "+sel)

My code throws error:

     sublime.status_message("selection: "+sel)
TypeError: Can't convert 'Selection' object to str implicitly

view.sel() returns sublime.Selection object. But I don't know how to get selected text from there.

This plugin must work as following: When I call it on view...

sublime text selection

... it should set text "dow = self.w" to variable sel

When I do str(sel) it returns <sublime.Selection object at 0x1047fd8d0>

Docs are not very clear for me.

Upvotes: 4

Views: 4723

Answers (3)

gzhegow
gzhegow

Reputation: 53

Use it in console and then append in python view.substr((view.sel())[0])

Upvotes: 1

martineau
martineau

Reputation: 123473

My understanding of what the documentation means is this:

It sounds like the sel() method of a sublime.View object returns a sublime.Selection object, which is a container of regions—so you should be able to iterate over its contents (the regions it contains) or index into them using the [] operation.

You can get the text associated with each sublime.Region in a Selectionby calling the substr(region) method of a sublime.View object. This makes sense as this editor allows there to be multiple simultaneous selections—one of its cooler features, IMHO.

Hope this helps.

Upvotes: 8

Maxim Yefremov
Maxim Yefremov

Reputation: 14165

In case of single selection:

import sublime, sublime_plugin

class selection_plugin__Command(sublime_plugin.WindowCommand):
    def run(self):            
        print('selection_plugin__ called')
        window = self.window
        view = window.active_view()
        sel = view.sel()

        region1 = sel[0]
        selectionText = view.substr(region1)
        print(selectionText)

Upvotes: 6

Related Questions