forked from randy3k/R-Box
/
sendtext.py
155 lines (138 loc) · 5.47 KB
/
sendtext.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
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
import sublime
import sublime_plugin
import os
import subprocess
import re
import time
import sys
import tempfile
from .misc import RBoxSettings
def clean(cmd):
cmd = cmd.expandtabs(4)
cmd = cmd.rstrip('\n')
if len(re.findall("\n", cmd)) == 0:
cmd = cmd.lstrip()
return cmd
def escape_dq(cmd):
cmd = cmd.replace('\\', '\\\\')
cmd = cmd.replace('"', '\\"')
return cmd
def sendtext(cmd):
if cmd.strip() == "":
return
plat = sublime.platform()
if plat == "osx":
prog = RBoxSettings("App", "R")
if plat == "windows":
prog = RBoxSettings("App", "R64")
if plat == "linux":
prog = RBoxSettings("App", "tmux")
if re.match('Terminal', prog):
cmd = clean(cmd)
cmd = escape_dq(cmd)
args = ['osascript']
args.extend(['-e', 'tell app "Terminal" to do script "' + cmd + '" in front window\n'])
subprocess.Popen(args)
elif re.match('iTerm', prog):
cmd = clean(cmd)
cmd = escape_dq(cmd)
# when cmd ends in a space, iterm does not execute. Thus append a line break.
if (cmd[-1:] == ' '):
cmd += '\n'
try:
# iterm <2.9
args = ['osascript', '-e', 'tell app "iTerm" to tell the first terminal to tell current session to write text "' + cmd +'"']
subprocess.check_call(args)
except:
# iterm >=2.9
args = ['osascript', '-e', 'tell app "iTerm" to tell the first terminal window to tell current session to write text "' + cmd +'"']
subprocess.check_call(args)
elif plat == "osx" and re.match('R[0-9]*$', prog):
cmd = clean(cmd)
cmd = escape_dq(cmd)
args = ['osascript']
args.extend(['-e', 'tell app "' + prog + '" to cmd "' + cmd + '"'])
subprocess.Popen(args)
elif plat == "windows" and re.match('R[0-9]*$', prog):
cmd = clean(cmd)
progpath = RBoxSettings(prog, str(1) if prog == "R64" else str(0))
ahk_path = os.path.join(sublime.packages_path(), 'User', 'R-Box', 'bin','AutoHotkeyU32')
ahk_script_path = os.path.join(sublime.packages_path(), 'User', 'R-Box', 'bin','Rgui.ahk')
# manually add "\n" to keep the indentation of first line of block code,
# "\n" is later removed in AutoHotkey script
cmd = "\n"+cmd
args = [ahk_path, ahk_script_path, progpath, cmd ]
subprocess.Popen(args)
elif prog == "tmux":
cmd = clean(cmd) + "\n"
progpath = RBoxSettings("tmux", "tmux")
# `tmux set-buffer` fails if more than 16352 characters are
# passed to it. Send in chunks to avoid the problem.
n = 15000
chunks = [cmd[i:i+n] for i in range(0, len(cmd), n)]
for chunk in chunks:
subprocess.call([progpath, 'set-buffer', chunk])
subprocess.call([progpath, 'paste-buffer', '-d'])
elif prog == "screen":
cmd = clean(cmd) + "\n"
progpath = RBoxSettings("screen", "screen")
if len(cmd)<2000:
subprocess.call([progpath, '-X', 'stuff', cmd])
else:
with tempfile.NamedTemporaryFile() as tmp:
with open(tmp.name, 'w') as f:
f.write(cmd)
subprocess.call([progpath, '-X', 'stuff', ". %s\n" % (f.name)])
elif prog == "SublimeREPL":
cmd = clean(cmd)
view = sublime.active_window().active_view()
external_id = view.scope_name(0).split(" ")[0].split(".", 1)[1]
sublime.active_window().run_command("repl_send", {"external_id": external_id, "text": cmd})
return
class RBoxSendSelectionCommand(sublime_plugin.TextCommand):
# expand selection to {...} when being triggered
def expand_sel(self, sel):
esel = self.view.find(r"""^(?:.*(\{(?:(["\'])(?:[^\\]|\\.)*?\2|#.*$|[^\{\}]|(?1))*\})[^\{\}\n]*)+"""
, self.view.line(sel).begin())
if self.view.line(sel).begin() == esel.begin():
return esel
def run(self, edit):
view = self.view
cmd = ''
for sel in [s for s in view.sel()]:
if sel.empty():
thiscmd = view.substr(view.line(sel))
line = view.rowcol(sel.end())[0]
# if the line ends with {, expand to {...}
if re.match(r".*\{\s*$", thiscmd):
esel = self.expand_sel(sel)
if esel:
thiscmd = view.substr(esel)
line = view.rowcol(esel.end())[0]
if RBoxSettings("auto_advance", False):
view.sel().subtract(sel)
pt = view.text_point(line+1,0)
view.sel().add(sublime.Region(pt,pt))
else:
thiscmd = view.substr(sel)
cmd += thiscmd +'\n'
sendtext(cmd)
if RBoxSettings("auto_advance", False):
view.show(view.sel())
class RBoxChangeDirCommand(sublime_plugin.TextCommand):
def run(self, edit):
fname = self.view.file_name()
if not fname:
sublime.error_message("Save the file!")
return
dirname = os.path.dirname(fname)
cmd = "setwd(\"" + escape_dq(dirname) + "\")"
sendtext(cmd)
class RBoxSourceCodeCommand(sublime_plugin.TextCommand):
def run(self, edit):
fname = self.view.file_name()
if not fname:
sublime.error_message("Save the file!")
return
cmd = "source(\"" + escape_dq(fname) + "\")"
sendtext(cmd)