forked from jugyo/SublimeRubyEval
-
Notifications
You must be signed in to change notification settings - Fork 1
/
RubyEval.py
56 lines (41 loc) · 1.68 KB
/
RubyEval.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
import os, sublime, sublime_plugin, subprocess, re
class RubyEvalCommand(sublime_plugin.TextCommand):
PACKAGE_PATH = os.path.dirname(os.path.abspath(__file__))
ENCODING = 'utf-8'
def run(self, edit):
self.settings = sublime.load_settings('RubyEval.sublime-settings')
view = self.view
selection = view.sel()
process = subprocess.Popen(
[
self.settings.get("ruby"),
os.path.join(self.PACKAGE_PATH,'bin','xmpfilter'),
"--no-warnings"
],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE)
if len(selection) == 1 and selection[0].size() == 0:
selection = [sublime.Region(0, view.size())]
for region in selection:
text = view.substr(region)
if not self.has_trailing_eval_mark(text):
text = self.add_trailing_eval_mark(text)
output = process.communicate(text.encode(self.ENCODING))
if process.returncode != None and process.returncode != 0:
sublime.message_dialog("There was an error: " + output[1])
return
view_lines = view.lines(region)
output_lines = output[0].decode(self.ENCODING).split('\n')
region_length = len(view_lines)
if len(output_lines) > region_length:
output_lines[region_length - 1] = "\n".join(output_lines[region_length - 1:-1])
output_lines = output_lines[0:region_length]
view_lines.reverse()
output_lines.reverse()
for i in range(len(output_lines)):
view.replace(edit, view_lines[i], output_lines[i])
def has_trailing_eval_mark(self, text):
return re.search(r'#\s?=>.*\Z', text.strip())
def add_trailing_eval_mark(self, text):
return text.strip() + "\n# => "