Last active
November 7, 2018 13:33
-
-
Save mattst/71488757f2a2ca573c2d5e73af636d4c to your computer and use it in GitHub Desktop.
GetFileExtensionSyntax
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Proof of concept; retrieve the path of the syntax that a user has | |
# associated with any file extension in Sublime Text. | |
# | |
# 1) Create a temp file with the file extension of the desired syntax. | |
# 2) Open the temp file in ST with the API `open_file()` method; use a | |
# sublime.TRANSIENT buffer so that no tab is shown on the tab bar. | |
# 3) Retrieve the syntax ST has assigned to the view's settings. | |
# 4) Close the temp file's ST buffer. | |
# 5) Delete the temp file. | |
# | |
# ST command of demo: get_file_extension_syntax | |
import sublime, sublime_plugin | |
import os, tempfile | |
class GetFileExtensionSyntaxCommand(sublime_plugin.WindowCommand): | |
def run(self): | |
file_ext = ".cpp" | |
syntax = self.get_file_extension_syntax(file_ext) | |
print(syntax) | |
def get_file_extension_syntax(self, file_ext): | |
try: | |
tmp_base = "GetFileExtensionSyntaxTempFile-" | |
tmp_file = tempfile.NamedTemporaryFile(prefix = tmp_base, | |
suffix = file_ext, | |
delete = False) | |
tmp_path = tmp_file.name | |
except Exception: | |
return None | |
finally: | |
tmp_file.close() | |
active_buffer = self.window.active_view() | |
# Using TRANSIENT prevents the creation of a tab bar tab. | |
tmp_buffer = self.window.open_file(tmp_path, sublime.TRANSIENT) | |
# Even if is_loading() is true the view's settings can be | |
# retrieved; settings assigned before open_file() returns. | |
syntax = tmp_buffer.settings().get("syntax", None) | |
self.window.run_command("close") | |
if active_buffer: | |
self.window.focus_view(active_buffer) | |
try: | |
os.remove(tmp_path) | |
# In the unlikely event of remove() failing: on Linux/OSX | |
# the OS will delete the contents of /tmp on boot or daily | |
# by default, on Windows the file will remain in the user | |
# temporary directory (amazingly never cleaned by default). | |
except Exception: | |
pass | |
return syntax |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment