Search code examples
sublimetext2keyboard-shortcutssublimetextsublime-text-plugin

"Find all" through command in Sublime plugin?


I thought it would be:

window.run_command("find_all", {"pattern": "a"})

to find all the "a" characters in the current buffer (I mean the same effect as using "find all" from the find panel; end up with a multi-selection of every "a" character in the buffer), but it just does nothing.

(I tested that replacing it with something like:

window.run_command("move", {"by": "lines", "forward": True})

does work, so I at least got the context for the code right.)


Solution

  • According to the Sublime Text 2 API docs (also the same in ST3), find() and find_all() are methods of sublime.View, so you should call them on a view, not on a window. Here's a sample plugin to search for and select all occurrences of python:

    import sublime
    import sublime_plugin
    
    
    class HighlightPythonCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            count = 0
            for rgn in self.view.find_all('python'):
                self.view.sel().add(rgn)
                count += 1
    
            sublime.status_message('Added ' + str(count) + ' regions.')
    

    After saving it in your Packages/User directory, you can run it from the console (Ctrl`) using

    view.run_command("highlight_python")
    

    For searching for your character, try this version:

    import sublime
    import sublime_plugin
    
    
    class HighlightTripleEqualsCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            search = unichr(0x2261) # your character in hex
            self.view.sel().clear() # clear any existing selections - ideally we'd
                                    # save them and reinstate them afterwards...
            count = 0
            for rgn in self.view.find_all(search):
                self.view.sel().add(rgn)
                count += 1
    
            sublime.status_message('Added ' + str(count) + ' regions.')