Sublime Text插件 - 如何在选择中查找所有区域

时间:2016-07-28 09:50:56

标签: python sublimetext2 sublimetext3 sublimetext sublime-text-plugin

如何在选择中找到所有区域(也是regeon类型)? 如果我们调用这个方法:

def chk_links(self,vspace):
    url_regions = vspace.find_all("https?://[^\"'\s]+")

    i=0
    for region in url_regions:
        cl = vspace.substr(region)
        code = self.get_response(cl)
        vspace.add_regions('url'+str(i), [region], "mark", "Packages/User/icons/"+str(code)+".png")
        i = i+1
    return i

在视图上下文中,例如:

chk_links(self.view)

一切正常,但这样:

chk_links(self.view.sel()[0])

我收到错误:AttributeError:'Region'对象没有属性'find_all'

您可以找到here

的完整插件代码

Sublime "View" method documentation

1 个答案:

答案 0 :(得分:3)

Selection类(由View.sel()返回)基本上只是表示当前选择的Region个对象的列表。 Region可以为空,因此列表始终包含至少一个长度为0的区域。

唯一的methods available on the Selection class是修改和查询它的范围。类似methods are available on the Region class

可以做的是找到您代码当前正在进行的所有有趣区域,然后在迭代它们以执行检查时,查看它们是否包含在选择中或不。

这是上面示例的精简版本,以说明这一点(为清楚起见,您的一些逻辑已被删除)。首先收集整个URL列表,然后在迭代列表时,只有在 NO 选择或 THERE IS时才会考虑每个区域 选择 AND 网址区域包含在选择范围内。

import sublime, sublime_plugin

class ExampleCommand(sublime_plugin.TextCommand):
    # Check all links in view
    def check_links(self, view):
        # The view selection list always has at least one item; if its length is
        # 0, then there is no selection; otherwise one or more regions are
        # selected.
        has_selection = len(view.sel()[0]) > 0

        # Find all URL's in the view
        url_regions = view.find_all ("https?://[^\"'\s]+")

        i = 0
        for region in url_regions:
            # Skip any URL regions that aren't contained in the selection.
            if has_selection and not view.sel ().contains (region):
                continue

            # Region is either in the selection or there is no selection; process
            # Check and
            view.add_regions ('url'+str(i), [region], "mark", "Packages/Default/Icon.png")
            i = i + 1

    def run(self, edit):
        if self.view.is_read_only() or self.view.size () == 0:
            return
        self.check_links (self.view)