【问题标题】:Get file syntax selection in sublime text 3 plugin在 sublime text 3 插件中获取文件语法选择
【发布时间】:2015-09-23 13:25:16
【问题描述】:

我有一个非常小的插件,可以从 use 语句开始打开一个 perl 文件模块。它非常基本,它只是将 '::' 替换为 '/',然后如果文件存在于 PERL5LIB 中指定的路径之一中,它将打开它。 我希望它仅在打开文件语法选择为 perl 时运行。 是否有任何 API 可以获取该信息? 这是我现在拥有的代码:

class OpenPerlModule(sublime_plugin.TextCommand):
    def run(self, edit=None, url=None):
        perl_file = url.replace("::", "/")
        perl_dirs = os.environ.get('PERL5LIB')
        for perl_dir in perl_dirs.split(':'):
            if (os.path.exists(perl_dir + '/' + perl_file + '.pm')):
                self.view.window().open_file(perl_dir + '/' + perl_file + '.pm')
                return

(操作系统是 Ubuntu)

【问题讨论】:

    标签: python sublimetext3 sublimetext sublime-text-plugin


    【解决方案1】:

    这是您要查找的代码 sn-p

    self.view.settings().get("syntax")
    

    您应该检查它是否是与 Perl 相关的语法。我建议是这样的:

    syntax = self.view.settings().get("syntax")
    syntax.endswith("Perl.tmLanguage") or syntax.endswith("Perl.sublime-syntax")
    

    第二个 or 子句涵盖 >=3080 中引入的新语法

    【讨论】:

    • if "Perl" in syntax: 将是一个更容易的测试,并且将涵盖用户安装了ModernPerl 等第 3 方 Perl 语法的情况。
    • 谢谢,我会将此标记为答案 :-) 我已经四处寻找一些参考指南,但其中大多数都缺乏一种或另一种方式,也许你也有关于在哪里可以找到此类信息?
    【解决方案2】:

    除了 Allen Bargi 的回答中描述的 self.view.settings().get("syntax") 之外,您还可以获取当前光标位置的范围并检查其中的 source.perl

    import sublime_plugin
    
    class FindScopeCommand(sublime_plugin.TextCommand):
        def run(self, edit):
            # `sel()` returns a list of Regions that are selected. 
            # Grab the beginning point of the first Region in the list.
            first_point = self.view.sel()[0].a
            # now, get the full scope name for that point
            scope = self.view.scope_name(first_point)
            if "source.perl" in scope:
                print("You're using Perl. Yay!")
            else:
                print("Why don't you love Perl?")
    

    【讨论】:

    • 这也是一个有效的解决方案,但要小心你可能有嵌套的语法。这一切都取决于您的用例。例如,您可能在 markdown 文档中嵌套了 perl 代码(MarkdownEditing 插件和我的旧 Knockdown 插件都添加了 source.perl 范围以突出显示嵌套代码)。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2016-09-22
    • 2014-02-13
    • 1970-01-01
    • 1970-01-01
    • 2013-12-09
    • 2014-10-11
    • 1970-01-01
    相关资源
    最近更新 更多