Sublime Forum

How to enter text and set cursor to the first occurrence for all open files

#1

See the rough code of what I have atm. It currently searches the current doc and sets the cursor to the correct position.

How can I modify this to:

  1. Ask for input for the search string.
  2. Set the position of the cursor on all currently open files.
import sublime, sublime_plugin

class AllOpenFilesScrollToFoundText(sublime_plugin.TextCommand):
    def run(self, edit):

        # 1. I would like to loop over the open files which I cannot get to work.
        # for view in self.window.views():

          view = self.view
          contents = view.substr(sublime.Region(0, view.size()))  # https://stackoverflow.com/questions/20182008/sublime-text-3-api-get-all-text-from-a-file

          # 2. Here I would like a prompt to enter the text to find.
          # Using something like this which I cannot get to work.
          # searchStr = self.window.show_input_panel("Enter text to scroll to on all open windows:", '', None, None, None)
          searchStr = contents.find('TODO')

          cursors = view.sel()
          cursors.clear()
          location = sublime.Region(searchStr, searchStr)
          cursors.add(location)
          view.show_at_center(location)

0 Likes

#2

Your Window.show_input_panel's on_done callback is None. So I am not sure what are you expecting to happen ? You need to define a callback to which the entered text will be passed and then perform whatever you want to do with the entered text in that callback. Take a look at the method docs here

https://www.sublimetext.com/docs/api_reference.html#sublime.Window:ver-dev

2 Likes

#3

Thanks, this is probably not the prettiest of pyton as I’m only starting to learn it.

import sublime, sublime_plugin

class AllOpenFilesScrollToFoundText(sublime_plugin.TextCommand):

  def run(self, edit):
    findStr = self.view.window().show_input_panel("Enter text to scroll to on all open windows:", '', self.on_done, None, None)

  def on_done(self, findStrVar):

    for view in self.view.window().views():

      contents = view.substr(sublime.Region(0, view.size()))  # https://stackoverflow.com/questions/20182008/sublime-text-3-api-get-all-text-from-a-file
      a = contents.find(findStrVar)

      cursors = view.sel()
      cursors.clear()
      location = sublime.Region(a, a)
      cursors.add(location)
      view.show_at_center(location)
0 Likes