I came up with a hack to solve the problem, which unfortunately has a major downside.
- Create a temp file with the file extension of the desired syntax
- Open the temp file in ST with the API
open_file()
method
- Retrieve the syntax ST has assigned to the viewâs settings
- Close the temp fileâs ST buffer;
close()
is undocumented API
- Delete the temp file
Hey presto, the syntax for any file extension can be retrieved.
MAJOR DOWNSIDE:
The sequence of ST creating and then immediately closing the new buffer results in a visual âslide effectâ on the tab bar depending on how many tabs are showing and where the current tab is positioned within them. Most noticeably in a full tab bar when the furthest right hand tab is visible. Annoyingly passing the sublime.TRANSIENT
flag to open_file()
results in the failure of close()
, i.e. the temp file buffer remains open and with the focus albeit tabless. Iâm pretty sure thereâs no way around this - making this syntax retrieval technique redundant for actual use in a plugin - unless anyone can think of a way of getting around this?
Proof of concept code - clearly barebones roughânâready:
import sublime, sublime_plugin
import os, tempfile
class TempTestCodeCommand(sublime_plugin.WindowCommand):
def run(self):
ext = ".cpp"
temp_file = tempfile.NamedTemporaryFile(suffix = ext, delete = False)
new_buffer = self.window.open_file(temp_file.name)
syntax = new_buffer.settings().get("syntax", None)
new_buffer.close()
os.remove(temp_file.name)
sublime.status_message("Syntax: " + syntax)