forked from philippotto/Sublime-EvalPrinter
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathEvalPrinter.py
More file actions
252 lines (159 loc) · 6.35 KB
/
EvalPrinter.py
File metadata and controls
252 lines (159 loc) · 6.35 KB
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
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
import sublime, sublime_plugin
import subprocess
import os
try:
from EvalPrinter.KillableCmd import KillableCmd
except:
from KillableCmd import KillableCmd
class EvalPrintCommand(sublime_plugin.TextCommand):
def run(self, edit, codeStr=None):
view = self.view
codeStr = codeStr or Helper.getSelectedText(view)
syntax = view.settings().get('syntax')
if "Plain text" in syntax:
syntax = Helper.getSetting("default_language")
output = EvalEvaluator.evalPrint(codeStr, syntax)
Helper.showResult(output)
class EvalPrintEnterLiveSessionCommand(sublime_plugin.TextCommand):
def run(self, edit):
view = self.view
toggledValue = not view.settings().get("isEvalPrinterLiveSession", False)
view.settings().set("isEvalPrinterLiveSession", toggledValue)
sublime.status_message("EvalPrinter's Live Session is " + ("on" if toggledValue else "off"))
if toggledValue:
flags = 0
if len(Helper.getSelectedText(view)) == view.size():
# everything was selected, which is why we don't want to highlight the LiveSessionRegions
flags = sublime.HIDDEN
view.settings().set("EvalPrinterLiveSessionFullBuffer", True)
view.add_regions("EvalPrinterLiveSessionRegions", Helper.getExpandedRegions(view), "string", flags=flags)
view.run_command("eval_print")
else:
view.erase_regions("EvalPrinterLiveSessionRegions")
view.settings().set("EvalPrinterLiveSessionFullBuffer", False)
class ModifyListener(sublime_plugin.EventListener):
def on_modified_async(self, view):
if not view.settings().get("isEvalPrinterLiveSession", False):
view.erase_regions("EvalPrinterLiveSessionRegions")
return
fullBuffer = view.settings().get("EvalPrinterLiveSessionFullBuffer", False)
if fullBuffer:
liveSessionRegions = [sublime.Region(0, view.size())]
else:
liveSessionRegions = view.get_regions("EvalPrinterLiveSessionRegions")
areRegionsNotEmpty = any(map(lambda r: r.size() > 0, liveSessionRegions))
if areRegionsNotEmpty:
codeStr = Helper.getSelectedText(view, liveSessionRegions)
view.run_command("eval_print", dict(codeStr = codeStr))
elif not fullBuffer:
# liveSessionRegions is an empty region; deactive LiveSessionMode
view.run_command("eval_print_enter_live_session")
class TestEvalPrinterCommand(sublime_plugin.TextCommand):
def run(self, edit, codeStr, syntax):
output = EvalEvaluator.evalPrint(codeStr, syntax)
if int(sublime.version()) < 3000:
self.view.run_command("insert", {"characters": output})
else:
self.view.run_command("append", {"characters": output})
class EvalEvaluator:
@staticmethod
def evalPrint(codeStr, syntax):
output = None
if "Python" in syntax:
output = EvalEvaluator.runPython(codeStr)
elif "JavaScript" in syntax:
output = EvalEvaluator.runJavaScript(codeStr)
elif "CoffeeScript" in syntax:
output = EvalEvaluator.runCoffee(codeStr)
else:
output = "Couldn't determine a supported language. Maybe you want to set the default_language setting."
return output
@staticmethod
def runJavaScript(codeStr):
return Helper.executeCommand(["node", "-p", codeStr], False)
@staticmethod
def runCoffee(codeStr):
# does not work with multi-line-strings:
# transpileCmd = ['coffee', '-p', '-b', '-e', codeStr]
# does not work on unix:
# transpileCmd = ['coffee', '-p', '-b', Helper.writeToTmp(codeStr)]
transpileCmd = 'coffee -p -b "' + Helper.writeToTmp(codeStr) + '"'
transpiledJS = Helper.executeCommand(transpileCmd)
evaluatedJS = Helper.executeCommand(["node", "-p", transpiledJS], False)
return Helper.formatTwoOutputs(evaluatedJS, transpiledJS)
@staticmethod
def runPython(codeStr):
codeStr = Helper.unindentCode(codeStr)
try:
output = str(eval(codeStr))
except:
output = Helper.executeCommand(["python", "-c", codeStr], False)
return output
class Helper:
@staticmethod
def getSelectedText(view, regions=None):
fullRegions = Helper.getExpandedRegions(view, regions)
return "\n".join([view.substr(region) for region in fullRegions])
@staticmethod
def getExpandedRegions(view, regions=None):
regions = regions or view.sel()
fullRegions = []
for region in regions:
if region.a == region.b:
region = view.line(region)
fullRegions.append(region)
return fullRegions
@staticmethod
def showResult(resultStr):
if int(sublime.version()) < 3000:
sublime.active_window().run_command("show_panel", {"panel": "output.myOutput"})
myOutput = sublime.active_window().get_output_panel("myOutput")
edit = myOutput.begin_edit()
myOutput.insert(edit, 0, resultStr)
myOutput.end_edit(edit)
else:
myOutput = sublime.active_window().create_output_panel("myOutput")
sublime.active_window().run_command("show_panel", {"panel": "output.myOutput"})
myOutput.run_command("append", {"characters": resultStr})
myOutput.set_syntax_file("Packages/JavaScript/JavaScript.tmLanguage")
@staticmethod
def executeCommand(cmd, shell=True):
timeoutLimit = Helper.getSetting("execution_timeout")
return KillableCmd(cmd, timeoutLimit, shell).Run()
@staticmethod
def unindentCode(codeStr):
# finds the smallest common indentation and removes it,
# so that indented code can be evaluated properly
indentations = []
codeLines = codeStr.splitlines()
for l in codeLines:
if l.lstrip() == "":
# ignore empty lines
continue
indentation = len(l) - len(l.lstrip())
indentations.append(indentation)
unindentLength = min(indentations)
newCodeLines = [l[unindentLength:] for l in codeLines]
return "\n".join(newCodeLines)
@staticmethod
def getCodeFilePath():
# epPath = os.path.join(sublime.packages_path(), "EvalPrinter")
epPath = sublime.packages_path()
fileName = "ep_tmp"
filePath = os.path.join(epPath, fileName)
return filePath
@staticmethod
def writeToTmp(s):
filePath = Helper.getCodeFilePath()
with open(filePath, "wt") as out_file:
out_file.write(s)
return filePath
@staticmethod
def formatTwoOutputs(a, b):
if "error" in a.lower():
a, b = b, a
return a + "\n" + "-" * 80 + "\n\n" + b
@staticmethod
def getSetting(attr):
settings = sublime.load_settings("EvalPrinter.sublime-settings")
return settings.get(attr)