-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathdformat.py
71 lines (53 loc) · 1.95 KB
/
dformat.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
import sublime, sublime_plugin, os, shutil, tempfile, sys
plugin_settings = None
def read_settings(key, default):
global plugin_settings
if plugin_settings is None:
plugin_settings = sublime.load_settings("dformat.sublime-settings")
return sublime.active_window().active_view().settings().get(key, plugin_settings.get(key, default))
class dformat(sublime_plugin.TextCommand):
def run(self, edit):
if sys.platform == "win32":
prefix = "\\"
else:
prefix = "/"
# PY3 = sys.version_info[0] >= 3
# get temporary directory
tmpdir = tempfile.mkdtemp("", "_dfmt_temp_")
name = tmpdir + prefix + "sublime_dfmt_tmp.d"
# check config file
config_path = read_settings("config_path", "")
if os.path.isfile(config_path):
print("[DFormat] Config path: " + config_path)
try:
shutil.copy(config_path, tmpdir)
except IOError:
msg = "Can't copy config file to " + path
sublime.status_message(msg)
print(msg)
pass
print("[DFormat] Save text to file: " + name)
# get text from current view
all_text = sublime.Region(0, self.view.size())
text = self.view.substr(all_text)
# save text
f = open(name, "w")
f.write(text)
f.close()
# run dfmt
res = os.system(r"dfmt --inplace " + f.name)
if res == 0:
# clear view
self.view.erase(edit, all_text)
#read new text
f = open(name)
formated = f.read()
f.close()
self.view.insert(edit, 0, formated)
msg = "[DFormat] Formating finished"
else:
msg = "[DFormat] dfmt error (dfmt.exe not found?)"
# remove temporary file and dir
shutil.rmtree(tmpdir)
sublime.status_message(msg)
print(msg)