forked from DisposaBoy/GoSublime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gsfmt.py
70 lines (61 loc) · 2.3 KB
/
gsfmt.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
import sublime, sublime_plugin
import gscommon as gs
import thatcher
class SublimeEditor(thatcher.Editor):
def __init__(self, view, edit):
self.view = view
self.edit = edit
self.dirty = False
def update_regions(self):
self.regions = self.view.split_by_newlines(sublime.Region(0, self.view.size()))
def match_line(self, line_index, content):
self.update_regions()
if line_index < len(self.regions):
return self.view.substr(self.regions[line_index]) == content
return False
def insert_line(self, line_index, content):
self.update_regions()
if line_index <= len(self.regions):
if line_index < len(self.regions):
pos = self.regions[line_index].begin()
else:
pos = self.view.size()
self.view.insert(self.edit, pos, content+'\n')
self.dirty = True
return True
return False
def delete_line(self, line_index):
self.update_regions()
if line_index < len(self.regions):
self.view.erase(self.edit, self.view.full_line(self.regions[line_index]))
self.dirty = True
return True
return False
class GsFmtCommand(sublime_plugin.TextCommand):
def run(self, edit):
if not gs.is_go_source_view(self.view):
return
region = sublime.Region(0, self.view.size())
src = self.view.substr(region)
args = [gs.setting("gofmt_cmd", "gofmt"), "-d"]
diff, err = gs.runcmd(args, src)
if err:
fn = self.view.file_name()
err = err.replace('<standard input>', fn)
gs.notice('GsFmt', 'File %s contains errors' % fn)
elif diff:
err = ''
try:
edit = self.view.begin_edit()
ed = SublimeEditor(self.view, edit)
err = thatcher.patch(ed, diff)
except Exception as e:
err = "%s\n\n%s" % (err, e)
finally:
self.view.end_edit(edit)
if err:
def cb():
if ed.dirty:
self.view.run_command('undo')
gs.notice("GsFmt", "Could not patch the buffer: %s" % err)
sublime.set_timeout(cb, 0)