Sublime Forum

Python Version-specific Snippet Scopes?

#1

Is the Sublime Text scope detector able to distinguish between Python 2.x and Python 3.x code? This could either be automatic or by looking at the set syntax - I am not sure how it works. If so, what value should be used instead of source.python when defining the scope tag in a snippet definition?

As an example, perhaps you have a ‘print’ snippet whose content is something like <![CDATA[print "$1:", $1]]>. That works fine when you’re in Python 2.x, but as soon as you switch to a Python 3.x source file or project it no longer works. Leaving aside that the content can be re-jiggered to work in both cases, and the question of whether printing variable values like this is good practice (it’s just a simple example of something that changed between Python 2 and 3) - it would be nice to be able to define two snippets with the same tabTrigger but different scopes and content specific to the relevant scope. Is such a thing currently possible?

0 Likes

#2

In theory yes, but that would require that there be two versions of the Python syntax definitions, one that only supports Python 2, and another that supports Python 3. The version of the syntax that ships with Sublime works for both and doesn’t make distinctions like that.

So, you’d need to find or create a version of the syntax that only supports Python 2, or at a minimum is just a duplicate of the built in Python but with a more unique scope, like source.python.legacy. This is probably fairly easy to do in ST4 because a syntax can inherit from another syntax.

In addition to that, syntaxes are chosen based on the extension of the file (or the first line, but the built in syntax does that and doesn’t make version distinctions either), so unless you’re only using one version of Python and not the other (which given your question is probably not the case) you would likely also need something like a plugin that can determine what Python version is in use in the file to swap the syntax as appropriate.

0 Likes

#3

Thanks for the feedback. I’ll look into what it would take to create those custom syntax definitions. At least at a minimum I could manage them manually and that might still be advantageous.

0 Likes