ChatterOne
ChatterOne

Reputation: 3541

Get file syntax selection in sublime text 3 plugin

I have a very small plugin to open a perl file module starting from the use statement. It's really basic and it just replaces '::' with '/' and then if the file exists in one of the paths specified in PERL5LIB, it opens it. I want it to run only when the open file syntax is selected as perl. Is there any API to get that information? This is the code that I have now:

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

(The OS is Ubuntu)

Upvotes: 3

Views: 605

Answers (2)

MattDMo
MattDMo

Reputation: 102872

Aside from self.view.settings().get("syntax") as described in Allen Bargi's answer, you could also get the scope for the current cursor position and check for source.perl in it:

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?")

Upvotes: 2

Allen Bargi
Allen Bargi

Reputation: 15172

Here is the code snippet you're looking for

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

You should check whether it's a syntax related to Perl or not. I suggest something like this:

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

The second or clause is to cover the new syntax that's introduced in >=3080

Upvotes: 3

Related Questions