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...
... 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.
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 Selection
by 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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With