RobertJoseph
RobertJoseph

Reputation: 8158

Sublime Text 2 plugin: capture the selected text

I am trying to write my first ST2 plugin (I'm also new to Python). What I want to do is capture the currently selected text. This is what I have thus far. I thought this would save all the selected text into the text variable but it looks like I'm only capturing the beginning and ending indices of the selection. Thus, if I select the first character in the buffer, my plugin callback prints "01". What I want is the text between index 0 and index 1.

import sublime, sublime_plugin

class CopyOnSelectListener(sublime_plugin.EventListener):
    def on_selection_modified(self, view):
        selections = view.sel()
        text = ""
        for s in selections:
            text += str(s.begin())
            if not s.empty():
                text += str(s.end())
        print(text)

Upvotes: 1

Views: 320

Answers (1)

MattDMo
MattDMo

Reputation: 102862

The ST2 API reference is here. view.sel() returns a RegionSet, an object containing the Region of each selection. Region.a and Region.b are the integers referring to the beginning and ending, respectively, of the region. So, if your view contains

This is some text.

and you have selected text, Region.a would be 13 and Region.b would be 17. To actually get the contents of a Region, you need to use view.substr(region). The following code will print the contents of each selection to the console:

import sublime_plugin

class PrintSelectionTextCommand(sublime_plugin.TextCommand):
    def run(self, edit):
        view = self.view
        for region in view.sel():
            print(view.substr(region))

You can run it by opening the console with Ctrl`, making one or more selections in the open file, then running

view.run_command("print_selection_text")

from the console (assuming you've saved it as Packages/User/print_selection_text.py).

Upvotes: 2

Related Questions