Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

sublime plugin: find and select text

I got plugin for sublime text 3 that let me move cursor to line by its number:

import sublime, sublime_plugin

class prompt_goto_lineCommand(sublime_plugin.WindowCommand):

    def run(self):
        self.window.show_input_panel("Goto Line:", "", self.on_done, None, None)
        pass

    def on_done(self, text):
        try:
            line = int(text)
            if self.window.active_view():
                self.window.active_view().run_command("goto_line", {"line": line} )
        except ValueError:
            pass

class go_to_lineCommand(sublime_plugin.TextCommand):

    def run(self, edit, line):
        # Convert from 1 based to a 0 based line number
        line = int(line) - 1

        # Negative line numbers count from the end of the buffer
        if line < 0:
            lines, _ = self.view.rowcol(self.view.size())
            line = lines + line + 1

        pt = self.view.text_point(line, 0)

        self.view.sel().clear()
        self.view.sel().add(sublime.Region(pt))

        self.view.show(pt)

I want to improve it to let me move cursor to first line containing the specified string. It is like a search on file: For example if pass to it string "class go_to_lineCommand" plugin must move cursor to line 17 :

select line by text

and possibly select string class go_to_lineCommand.

The problem is reduced to finding regionWithGivenString, and then I can select it:

self.view.sel().add(regionWithGivenString)

But don't know method to get regionWithGivenString.

I tried to

  1. find on google: sublime plugin find and select text
  2. check api

But still no result.

like image 966
Maxim Yefremov Avatar asked Oct 28 '25 08:10

Maxim Yefremov


2 Answers

I am not sure about the typical way. However, you can achieve this in following way:

  1. Get the content of current doc.
  2. Search target string to find out its start and end position. Now you have the start and end point.
  3. Add the Region(start, end) to selections.

Example:

def run(self, edit, target):
    if not target or target == "":
        return

    content = self.view.substr(sublime.Region(0, self.view.size()))
    begin = content.find(target)
    if begin == -1:
        return
    end = begin + len(target)
    target_region = sublime.Region(begin, end)
    self.view.sel().clear()
    self.view.sel().add(target_region)
like image 123
longhua Avatar answered Oct 31 '25 07:10

longhua


there you have it in the API, use the view.find(regex,pos) method.

s = self.view.find("go_to_lineCommand", 0)
self.view.sel().add(s)

http://www.sublimetext.com/docs/3/api_reference.html

like image 38
Ivan Ferrer Villa Avatar answered Oct 31 '25 09:10

Ivan Ferrer Villa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!