Sublime Forum

Setting syntax for named, but unsaved buffer

#1

My sublime-github plugin can open your gists in the editor, but even though I’m setting the filename, the syntax doesn’t get properly set. Are there any hidden API calls that can map a file extension to a .tmLanguage file, so I can manually set the syntax?

I could iterate through all the .tmLanguage files and build up my own mapping, but it seems I should be able to get that from sublime.

0 Likes

#2

Well, went ahead and did it the long way. In case anyone else runs into this, here’s the code I used to generate a mapping of file extensions to syntax files (which can then be passed to view.set_syntax_file()):

import os
import os.path
import sublime
import plistlib
import logging as logger
try:
    import xml.parsers.expat as expat
except ImportError:  # not available on Linux
    expat = None


def generate_syntax_file_map():
    if not expat:
        return {}
    syntax_file_map = {}
    packages_path = sublime.packages_path()
    packages = [f for f in os.listdir(packages_path) if os.path.isdir(os.path.join(packages_path, f))]
    for package in packages:
        package_dir = os.path.join(packages_path, package)
        syntax_files = [os.path.join(package_dir, f) for f in os.listdir(package_dir) if f.endswith(".tmLanguage")]
        for syntax_file in syntax_files:
            try:
                plist = plistlib.readPlist(syntax_file)
                if plist:
                    for file_type in plist'fileTypes']:
                        syntax_file_map[file_type.lower()] = syntax_file
            except expat.ExpatError:  # can't parse
                logger.warn("could not parse '%s'" % syntax_file)
            except KeyError:  # no file types
                pass
    return syntax_file_map
0 Likes