sublime-text-plugin

Grabbing Text from Sublime Text Regions


I'm new to creating Sublime Text 3 Plugins and I'm trying to understand the Plugin API that's offered. I want to be able to "grab" text I highlight with my mouse and move it somewhere else. Is there a way I can do this using the Sublime Text Plugin API?

So far, all I've done is be able to create a whole region:

allcontent = sublime.Region(0, self.view.size())

I've tried to grab all of the text in the region and put it into a lot file:

logfile = open("logfile.txt", "w")
logfile.write(allcontent)

But unsuccessfully of course as the log file is blank after it runs.

I've looked over google and there is not a lot of documentation, except for the unofficial documentation, in which I can't find a way to grab the text. Nor are there many tutorials on this.

Any help is greatly appreciated!


Solution

  • A Region just represents a region of text (i.e. from position 0 to position 10), and isn't tied to any specific view.

    To get the underlying text from the view's buffer, you need to call the view.substr method with the region as a parameter.

    import os
    logpath = os.path.join(sublime.cache_path(), 'logfile.txt')
    allcontent = self.view.substr(sublime.Region(0, self.view.size()))
    with open(logpath, 'w') as logfile:
        logfile.write(allcontent)
    print('written buffer contents to', logpath)
    

    To get the region represented by the first selection, you can use self.view.sel()[0] in place of sublime.Region(0, self.view.size()).