Sublime Forum

Expected file extension for unsaved file in plugin

#1

Hi.

I’m writing a plugin to Sublime and trying to somehow get expected file extension for unsaved buffer. I have a syntax for the buffer but cannot get the extension from it.

Right now my best shot is to parse syntax file in plugin code (tmLanguage or sublime-syntax file) and just extract first extension from the list. With tmLanguage it should be easy, as plistlib library is included in stdlib , but sublime-syntax files are yaml, and it’s not included in Python stdlib nor in Sublime libs, so I will need an external dependency. All this to do stuff that’s already done by Sublime when saving file.

Maybe I’m missing some API? Is there a simpler way to achieve this?

Thanks.

0 Likes

#2

Would you mind explaining why you need that information?

0 Likes

#3

Sure, sorry for not being more specific.

I’m writing a Rome formatter integration via subprocess & pipes and cli expects to pass file name for syntax detection. For saved files it’s easy, I just take current view file name, but for unsaved buffers I have no better idea to produce a fake file name with correct extension.

0 Likes

#4

If you don’t want to add YAML parser dependencies to your plugin, since the number of formats supported by Rome formatter are limited, you may maintain a mapping of scope => file extension manually. Such as

def get_view_pseudo_ext() -> str:
    view_main_scope = view.syntax().scope.partition(" ")[0]
    for scope, ext in (
        ("source.js", ".js"),
        ("source.ts", ".ts"),
        ("text.html.basic", ".html"),
        ("text.html.markdown", ".md"),
        # more... or load from plugin settings
    ):
        if sublime.score_selector(view_main_scope, scope):
            return ext
    return ""
0 Likes

#5

Was thinking about it, but wanted something a bit more future-proof, so it would automatically handle new formats supported and new syntaxes introduced to Sublime.

Thanks for your help. Will probably go the route of explicit mapping for now.

0 Likes

#6

If there isn’t one already I suggest submitting an enhancement request to the official issue tracker for adding this to the Syntax class.

0 Likes