崇高插件:查找并选择文本 [英] sublime plugin: find and select text
问题描述
我有一个sublime text 3
插件,它允许我将光标移动到其编号所在的行:
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)
我想对其进行改进,以使光标移动到包含指定字符串的第一行.就像在文件上搜索一样:
例如,如果传递给它,则字符串"class go_to_lineCommand"
插件必须将光标移至第17行:
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 :
,并可能选择字符串class go_to_lineCommand
.
问题被简化为找到regionWithGivenString
,然后我可以选择它:
The problem is reduced to finding regionWithGivenString
, and then I can select it:
self.view.sel().add(regionWithGivenString)
但是不知道获取regionWithGivenString
的方法.
But don't know method to get regionWithGivenString
.
我试图
- 在Google上查找: api
- find on google: sublime plugin find and select text
- check api
但仍然没有结果.
推荐答案
我不确定这种典型方法.但是,您可以通过以下方式实现此目的:
I am not sure about the typical way. However, you can achieve this in following way:
- 获取当前文档的内容.
- 搜索目标字符串以找出其开始和结束位置.现在您有了起点和终点.
- 将
Region(start, end)
添加到选择中.
- Get the content of current doc.
- Search target string to find out its start and end position. Now you have the start and end point.
- Add the
Region(start, end)
to selections.
示例:
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)
这篇关于崇高插件:查找并选择文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!