-
Notifications
You must be signed in to change notification settings - Fork 14
/
FixMyJS.py
executable file
·63 lines (54 loc) · 1.78 KB
/
FixMyJS.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
import sublime
import sublime_plugin
import json
from os.path import dirname, realpath, join, splitext, basename
try:
# Python 2
from node_bridge import node_bridge
except:
from .node_bridge import node_bridge
# monkeypatch `Region` to be iterable
sublime.Region.totuple = lambda self: (self.a, self.b)
sublime.Region.__iter__ = lambda self: self.totuple().__iter__()
BIN_PATH = join(sublime.packages_path(), dirname(realpath(__file__)), 'fixmyjs.js')
def get_setting(view, key):
settings = view.settings().get('FixMyJS')
if settings is None:
settings = sublime.load_settings('FixMyJS.sublime-settings')
return settings.get(key)
def is_javascript(view):
return splitext(basename(view.settings().get('syntax')))[0] in ('JavaScript', 'JavaScript (Babel)')
class FixCommand(sublime_plugin.TextCommand):
def run(self, edit):
if not self.has_selection():
region = sublime.Region(0, self.view.size())
originalBuffer = self.view.substr(region)
fixed = self.fix(originalBuffer)
if fixed:
self.view.replace(edit, region, fixed)
return
for region in self.view.sel():
if region.empty():
continue
originalBuffer = self.view.substr(region)
fixed = self.fix(originalBuffer)
if fixed:
self.view.replace(edit, region, fixed)
def fix(self, data):
try:
return node_bridge(data, BIN_PATH, [json.dumps({
'legacy': get_setting(self.view, 'legacy'),
'filepath': self.view.file_name()
})])
except Exception as e:
sublime.error_message('FixMyJS\n%s' % e)
def has_selection(self):
for sel in self.view.sel():
start, end = sel
if start != end:
return True
return False
class FixPreSaveCommand(sublime_plugin.EventListener):
def on_pre_save(self, view):
if get_setting(view, 'fixOnSave') is True and is_javascript(view):
view.run_command('fix')