Thanks, this is probably not the prettiest of python as Iām only starting to learn it.
Edit. Updated the code to be more verbose and a few other things mentioned in the header.
import sublime, sublime_plugin
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
#
# Written by StephenS. Forum thread: https://forum.sublimetext.com/t/how-to-enter-text-and-set-cursor-to-the-first-occurrence-for-all-open-files/56948
#
# INTIAL RELEASE: 2021.04.07
# REV 1: 2021.04.17
# Added the ability to select the found string and set_viewport_postion to it.
# Added putting the paths of the files where the string was found to your clipboard.
# REV 1.1: 2021.04.23
# Added the ability to select the text to find first which will be then populated to the 'Enter text to scroll' box
# Fixed the scrolling to the selected text with .show(highlightLocation).
#
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
class AllOpenFilesScrollToAndSelectFoundText(sublime_plugin.TextCommand):
def run(self, edit):
sel = self.view.sel()[0]
selected = self.view.substr(sel)
findStr = self.view.window().show_input_panel("Enter text to scroll to and select on all open tabs:", selected, self.on_done, None, None)
def on_done(self, findStrVar):
fileCnt = 0
fileList = ""
fileListPopupMsg = ""
fileMsg1 = ""
fileMsgCnt = ""
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
begin = contents.find(findStrVar)
if begin != -1:
# view.window().show_input_panel(str(begin), '', None, None, None) # Testing line.
fileCnt += 1
fileList += view.file_name() + "\r\n"
fileListPopupMsg += view.file_name() + "<br>"
end = begin + len(findStrVar)
cursors = view.sel()
cursors.clear()
highlightLocation = sublime.Region(begin, end)
cursors.add(highlightLocation)
view.show(highlightLocation) # show - Scroll the view to show the given location, which may be a point, Region or Selection.
view.show_at_center(highlightLocation)
if fileCnt == 0: fileMsgCnt = "files" ; fileMsg1 = "have been"
if fileCnt == 1: fileMsgCnt = "file" ; fileMsg1 = "has been" ; sublime.set_clipboard(fileList)
if fileCnt > 1: fileMsgCnt = "files" ; fileMsg1 = "have been" ; sublime.set_clipboard(fileList)
# Help on .show_popup: https://forum.sublimetext.com/t/dev-build-3070/14538/14
htmlStrResult = """
<style>
body { margin: 10px }
html { background-color: grey; border: 2px solid black; font-family: Arial, Helvetica, sans-serif }
</style>
<h2>Found """ + str(fileCnt) + """ """ + fileMsgCnt + """ that contain your text! Scrolling has been done to each.</h2>
<h3>(""" + str(fileCnt) + """ """ + fileMsgCnt + """ paths """ + fileMsg1 + """ also copied to your clipboard)</h3><br>
\r\n\r\n""" + fileListPopupMsg
self.view.show_popup(htmlStrResult, max_width=1000, max_height=400)