import sublime_plugin
import codecs
import functools
import sublime
import re
MAPPING = {"cp1250" : "Central European (Windows 1250)",
"cp1251" : "Cyrillic (Windows 1251)",
"cp1252" : "Western (Windows 1252)",
"cp1253" : "Greek (Windows 1253)",
"cp1254" : "Turkish (Windows 1254)",
"cp1255" : "Hebrew (Windows 1255)",
"cp1256" : "Arabic (Windows 1256)",
"cp1257" : "Baltic (Windows 1257)",
"cp1258" : "Vietnamese (Windows 1258)",
"cp437" : "DOS (CP 437)",
"cp866" : "Cyrillic (Windows 866)",
"iso8859-1" : "Western (ISO 8859-1)",
"iso8859-10" : "Nordic (ISO 8859-10)",
"iso8859-13" : "Estonian (ISO 8859-13)",
"iso8859-14" : "Celtic (ISO 8859-14)",
"iso8859-15" : "Western (ISO 8859-15)",
"iso8859-16" : "Romanian (ISO 8859-16)",
"iso8859-2" : "Central European (ISO 8859-2)",
"iso8859-3" : "Western (ISO 8859-3)",
"iso8859-4" : "Baltic (ISO 8859-4)",
"iso8859-5" : "Cyrillic (ISO 8859-5)",
"iso8859-6" : "Arabic (ISO 8859-6)",
"iso8859-7" : "Greek (ISO 8859-7)",
"iso8859-8" : "Hebrew (ISO 8859-8)",
"iso8859-9" : "Turkish (ISO 8859-9)",
"koi8-r" : "Cyrillic (KOI8-R)",
"koi8-u" : "Cyrillic (KOI8-U)",
"mac-roman" : "Western (Mac Roman)",
"utf-16-be" : "UTF-16 be",
"utf-16-le" : "UTF-16 le",
"utf-8" : "UTF-8"}
class ArweEventListener(sublime_plugin.EventListener):
def on_load(self, view):
required_codec = self.find_codec(view)
if not required_codec:
return
cd = codecs.lookup(required_codec)
if not cd.name in MAPPING:
return
req_enc = MAPPING[cd.name]
if view.encoding() == req_enc:
return
sublime.set_timeout(functools.partial(self.switch_encoding, view, req_enc), 0)
def switch_encoding(self, view, req_enc):
if view.is_dirty():
# some other plugins has modified this
# file on_load, ignore encoding switch
return
sel = list(view.sel())
sublime.status_message("SubARWE: Reopen with Encoding: {enc}".format(enc=req_enc))
view.run_command("reopen", {'encoding': req_enc})
sublime.set_timeout(functools.partial(self.restore_selection, view, sel), 0)
def restore_selection(self, view, sel):
view.sel().clear()
for s in sel:
view.sel().add(s)
def find_codec(self, view):
for line_no in xrange(1,2):
match = re.search("coding\s*[:=]\s*([-\w.]+)", view.substr(view.line(line_no)))
if match:
return match.group(1)
return None