Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 590
Maxim Yefremov Avatar asked Dec 09 '22 11:12

Maxim Yefremov


2 Answers

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.

like image 152
martineau Avatar answered Jan 16 '23 13:01

martineau


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)
like image 44
Maxim Yefremov Avatar answered Jan 16 '23 12:01

Maxim Yefremov