-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathsublime_gbk.py
93 lines (74 loc) · 2.71 KB
/
sublime_gbk.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
#coding: utf8
import sublime, sublime_plugin
import os, re
def gbk2utf8(view):
try:
reg_all = sublime.Region(0, view.size())
gbk = view.substr(reg_all).encode('gbk')
except:
gbk = open(view.file_name(), 'r', encoding='GBK').read()
text = gbk
tmp_file = u"%s.dump"%view.file_name()
ver = int(sublime.version())
if ver >= 3000:
f = open(tmp_file, 'w', encoding='utf-8')
f.write(text)
f.close()
else:
f = open(tmp_file, 'w')
f.write(text.encode('utf8'))
f.close()
window = sublime.active_window()
tmp_view = window.open_file(tmp_file)
if not tmp_view:
tmp_view = window.open_file(tmp_file)
tmp_view.set_syntax_file(view.settings().get('syntax'))
window.focus_view(view)
window.run_command('close')
window.focus_view(tmp_view)
sublime.status_message('gbk encoding detected, open with utf8.')
def saveWithEncoding(view, file_name = None, encoding = 'gbk'):
if not file_name:
file_name = view.file_name()
reg_all = sublime.Region(0, view.size())
text = view.substr(reg_all).encode(encoding)
gbk = open(file_name, 'wb')
gbk.write(text)
gbk.close()
class EventListener(sublime_plugin.EventListener):
def on_load(self, view):
gbk2utf8(view)
def on_post_save(self, view):
if ".dump" in view.file_name():
file_name = view.file_name()[:-5]
saveWithEncoding(view, file_name)
def on_close(self,view):
if ".dump" in view.file_name():
os.remove(view.file_name())
class SaveWithGbkCommand(sublime_plugin.TextCommand):
def __init__(self, view):
self.view = view
def run(self, edit):
file_name = self.view.file_name()
if(not file_name):
return
if ".dump" not in self.view.file_name():
saveWithEncoding(self.view)
sublime.active_window().run_command('close')
sublime.active_window().open_file(self.view.file_name())
else:
sublime.active_window().run_command('save')
class SaveWithUtf8Command(sublime_plugin.TextCommand):
def __init__(self, view):
self.view = view
def run(self, edit):
file_name = self.view.file_name()
if(not file_name):
return
if ".dump" in self.view.file_name():
file_name = self.view.file_name()[:-5]
saveWithEncoding(self.view, file_name, 'utf-8')
sublime.active_window().run_command('close')
sublime.active_window().open_file(file_name)
else:
sublime.active_window().run_command('save')