-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathExternREPL.py
More file actions
391 lines (342 loc) · 15.4 KB
/
ExternREPL.py
File metadata and controls
391 lines (342 loc) · 15.4 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
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
import sublime, sublime_plugin, re, shutil, functools, os
from subprocess import Popen, call
class TestSubl(sublime_plugin.TextCommand):
def run(self, edit,directory=None):
base = r'C:\tools\conemu\160207\ConEmu.exe -LoadCfgFile C:\Dropbox\dotfiles\preferences\ConEmu.xml -cmdlist '
command = r'set foo=bar && cmd -cur_console:s3TH:d:"c:\"' # split [3Tab] [50] H|V
# command = r'%systemroot%\system32\WindowsPowerShell\v1.0\powershell.exe -new_console:d:"%scripts2%\libwba":t:"PS64":P:<powerShell>'
# command = r'cmd -cur_console:sTVn'
self.view.erase_status('foo')
sublime.status_message('Hello')
print(42)
# Popen(base+command)
class GitGui(sublime_plugin.TextCommand):
def run(self, edit,directory=None):
if directory == None:
directory = os.path.dirname( self.view.file_name())
if os.name == "posix":
self.view.window().run_command("exec",{
"cmd": [ "git", "gui" ],
"working_dir": directory
})
else:
os.chdir( directory )
Popen("git gui")
# git_install_root = "C:\\Program Files (x86)\\Git\\"
# Popen(["%sbin\\wish.exe" % (git_install_root),"%slibexec\\git-core\\git-gui" % (git_install_root)])
# replaces _ with \w+ and reduces whitespace to one single
def prep_data(a):
f = a[0].replace("_","\w+") # _ => \w+
f = re.sub(r'\s+', " ", f) # ' ' => ' '
return (f,a[1])
# assert prep_data(("a _",41)) == ("a \w+",41)
def extract_http(s):
m = re.search('\[.*\]\((.*)\)',s)
if m:
return m.group(1)
m = re.search("https?://\S*",s)
if m:
return(m.group(0))
# assert extract_http('a http://foo b') == 'http://foo'
# assert extract_http('[Die Foo Seite](htt://foo)') == 'htt://foo'
def extract_file(s):
"finds first word with / or \\"
m = re.search('\S*[\\\\/]\S*',s)
if m:
return m.group(0)
# assert extract_file("a f/d b") == "f/d"
class ExternReplUp(sublime_plugin.TextCommand):
"sends up arrow"
def run(self, edit):
self.view.run_command("save")
if sublime.platform() == 'windows':
Popen('ConEmuC -GuiMacro:0 Keys("Up");paste(2,"\\n")')
else:
command= 'tmux send-keys -t repl Up C-m'
print("Command = " + command)
return Popen(command,shell=True)
class ExternReplOps(sublime_plugin.TextCommand):
def run(self, edit, what):
if self.view.is_dirty():
self.view.run_command("save")
init_er(self)
command = self.er.ops_get(what)()
self.er.command(command)
class ExternReplFile(sublime_plugin.TextCommand):
"opens the file or webpage in current line"
def run(self, edit):
init_er(self)
lc = self.er.line_content
url = extract_http(lc)
if url:
c = self.er.ops_get("chrome")(url=url)
else:
file = extract_file(lc)
if file:
c = "subl " + file
if c:
print(c)
self.er.command(c)
else:
print("can't detect url or file in " + lc )
class ExternReplRefresh(sublime_plugin.TextCommand):
"invoked be F5, new version of run"
def run(self, edit):
if self.view.is_dirty():
self.view.run_command("save")
init_er(self)
self.test() or self.runn()
def test(self):
if (self.er.ops_get('istest')()):
self.er.command(self.er.ops_get('test')())
return True
def runn(self):
print("runn")
self.er.command(self.er.ops_get('run')())
class ExternReplTest(sublime_plugin.TextCommand):
"run associated test (CS-t)"
def run(self, edit):
if self.view.is_dirty():
self.view.run_command("save")
init_er(self)
if (self.er.ops_get('istest')()):
c = self.er.ops_get('test')()
else:
c = self.er.ops_get('testAlternate')()
self.er.command(c)
class ExternReplAlternate(sublime_plugin.TextCommand):
"switches from file to test and reverse"
def run(self, edit):
init_er(self)
other = self.er.alternate(self.view.file_name())
print("switch to: "+ other)
self.view.window().open_file(other)
class ExternReplDublicateFile(sublime_plugin.TextCommand):
"copies current file and opens it"
def run(self, edit):
if self.view.is_dirty():
self.view.run_command("save")
file = self.view.file_name()
v = self.view.window().show_input_panel("Copy File to:", file, functools.partial(self.on_done,file), None, None)
name, ext = os.path.splitext(file)
v.sel().clear()
v.sel().add(sublime.Region(0, len(name)))
def on_done(self,src, dst):
shutil.copyfile(src, dst)
self.view.window().open_file(dst)
class ExternReplMarkdownToc(sublime_plugin.TextCommand):
"copies current file and opens it"
def run(self, edit):
if self.view.is_dirty():
self.view.run_command("save")
file = self.view.file_name()
if re.compile( r'\.md$',re.I).search(file):
#c:\project\file.tests.ps1
toc = re.sub(r'\.md$',".md.toc",file)
command = "ruby \"" + sublime.packages_path() + "/ExternalREPL/ruby/toc.rb\" "+file+" > "+toc
print(command)
return_code = call(command, shell=True)
self.view.window().open_file(toc)
elif re.compile( r'\.md.toc$',re.I).search(file):
md = re.sub(r'\.md\.toc$',".md",file)
command = "ruby \""+sublime.packages_path()+"/ExternalREPL/ruby/retoc.rb\" "+file+" "+md #+" > "+md
print(command)
return_code = call(command, shell=True)
self.view.window().open_file(md)
class ExternReplShowOutput(sublime_plugin.WindowCommand):
"pipes textbuffer into command"
def run(self):
text="""
repl run test misc
a-EN selected cs-. load file cs-t run testfile cs-c change directory/ns
cs-s last command f5 run file cs-o run selected test cs-1 open explorer
cs-i inspect cs-' switch code<->test cs-2 dublicate file
cs-3 open file or http:// on line
f1 show shortkeys
cs-4 restructure markdown headings
"""
self.output_view = self.window.create_output_panel("exec")
self.output_view.run_command('append', {'characters': text, 'force': True, 'scroll_to_end': True})
self.window.run_command("show_panel", {"panel": "output.exec"})
class ExternReplMoveFile(sublime_plugin.TextCommand):
"renames current file and opens it"
def run(self, edit):
if self.view.is_dirty():
self.view.run_command("save")
file = self.view.file_name()
v = self.view.window().show_input_panel("Copy File to:", file, functools.partial(self.on_done,file), None, None)
name, ext = os.path.splitext(file)
v.sel().clear()
v.sel().add(sublime.Region(0, len(name)))
def on_done(self,src, dst):
try:
os.rename(src, dst)
self.view.retarget(dst)
except:
sublime.status_message("Unable to rename")
class Er:
def __init__(self,stc):
self.error = None # can be set
self.stc = stc
self.view = stc.view
self.file_name = self.view.file_name()
folders = [f for f in sublime.active_window().folders() if self.file_name.lower().startswith(f.lower())] # project directory
if not folders:
# self.error ="Project Folder needs to be incuded in Side Bar (can't find project folder)"
self.path = ""
self.file = self.file_name
else:
self.path = folders[0]
self.file = self.file_name[len(self.path)+1:]
if self.file == "Gemfile":
self.lang = "gemfile"
else:
scopes = self.view.scope_name(self.view.sel()[0].begin()) # source.python meta.structure.list.python punctuation.definition.list.begin.python
# print(scopes)
langs = ["fsharp","python","powershell","ruby","clojure","markdown","dot"]
match = [l for l in langs if l in scopes]
self.lang = "unknown"
if match:
self.lang = match[0]
else:
print("Cant find lang for scopes")
methods = [
("run python _", lambda: 'python ' + self.file),
("load python _", lambda: 'exec(open("'+self.file+'").read())'),
("istest powershell _", lambda: re.match(".*\.tests\.ps1$",self.file_name)),
("load powershell _", lambda: '. ' + self.file_name),
("run powershell _", lambda: self.file_name),
("test powershell _", lambda: 'psspec .\\' + self.file),
("testAlternate powershell _", lambda: 'psspec .\\' + self.alternate(self.file)),
("test1p powershell _", """^\s*(?:it|It|describe|Describe)\s+(?:'|")(.*)(?:'|").*\{\s*$"""),
("test1 powershell _", lambda: 'psspec .\\' + self.file + ' -example "' + '|'.join([i for i in self.selected_testnames]) + '"'),
("inspect powershell _", lambda: "pp (" + self.line()+")" ),
("load clojure _", lambda: '(load-file "' + self.file.replace("\\","/") + '")'),
("test ruby _", lambda: 'ruby -I test'+os.pathsep+'lib ' + self.file.replace("\\","/") ),
("load ruby _", lambda: 'load "' + self.file_name.replace("\\","/") + '"'),
("run gemfile _", lambda: 'bundle install'),
("run ruby _", lambda: 'ruby -I lib ' + self.file),
("test1 ruby _", lambda: 'ruby -I lib' + os.pathsep +'test ' + self.file + ' --name "/' + '|'.join([ '^test_\d{4}_'+i+'$' for i in self.selected_testnames]) +'/"'),
# ruby -I lib;test test\couch_test.rb --name /^test_\d{4}_describe1$|^test_\d{4}_describe2$/"
("test1p ruby _", """^\s*it\s+(?:'|")(.*)(?:'|")\s+do\s*$"""),
("load markdown _", lambda: "pandoc -r markdown_github+footnotes+grid_tables -o \"" + re.sub("\..+$",".docx",self.file) + "\" \"" + self.file +"\""),
("run markdown _", lambda: self.ops_lang.get("markdown").get("load")() + " && \"" + re.sub("\..+$",".docx",self.file) + "\""),
("load fsharp _", lambda: "#load \"" + self.file_name + "\";;"),
("run dot _", lambda: 'dot -Tpng -O ' + self.file),
("explorer _ windows", lambda: "explorer " + self.path),
("explorer _ osx" , lambda: "open " + self.path),
("cd clojure _", lambda: self.cd_clojure),
("cd _ _", lambda: 'cd "' + self.path + '"'),
("line clojure _", lambda: self.line_clojure),
("line fsharp _", lambda: self.line() + ";;"),
("line _ _", self.line),
("lineuncomment fsharp _", lambda s: re.sub(r"^\s*//\s*","",s)), # strip leading //
("lineuncomment _ _" , lambda s: re.sub(r'^# ', r'', s,0,re.MULTILINE)), # strip leading #
("istest _ _", lambda: False),
("chrome _ _", lambda **a: "chrome " + a['url'] ),
]
self.methods = list(map( prep_data,methods ))
def ops_get(self,method):
string = method + " " + self.lang + " " + sublime.platform()
print("opsget: "+string)
f = next(pl[1] for pl in self.methods if re.match( pl[0], string))
return f
@property
def line_content(self):
region = self.view.sel()[0]
line = self.view.line(region)
return self.view.substr(line)
def line(self):
for region in self.view.sel():
if region.empty():
# select current line
line = self.view.line(region)
line_contents = self.view.substr(line)
line_below = sublime.Region(line.b+1)
self.view.sel().clear()
self.view.sel().add(line_below)
return self.ops_get("lineuncomment")(line_contents)
else:
return self.ops_get("lineuncomment")(self.view.substr(region))
return self.view.substr(region)
@property
def line_clojure(self):
opening = []
regions = self.view.find_all("^\(",fmt="$1",extractions=opening)
for i,region in enumerate(regions[:-1]):
region.b = regions[i+1].a-1
regions[-1].b = self.view.size()
forms = []
for region in regions:
for s in self.view.sel():
if s.intersects(region):
forms.append( self.view.substr(region) )
return "".join(forms)
@property
def cd_clojure(self):
ns = self.view.find(r"\(\s*ns [\w\.]+", 0)
return self.view.substr(ns) + ")"
@property
def testnames(self):
"( (region, 'name'),... )"
testnames = []
regions = self.view.find_all(self.ops_get("test1p"),fmt="$1",extractions=testnames)
regions[0].a = 0
regions[-1].b = self.view.size()
for i,region in enumerate(regions[:-1]):
region.b = regions[i+1].a
return [ (region, testnames.pop(0)) for region in regions]
@property
def selected_testnames(self):
"list of testnames"
acc = []
for region, testname in self.testnames:
for s in self.view.sel():
if s.intersects(region):
acc.append( testname )
return acc
def command(self,command):
print("command:"+command)
# \ => \\ | " => \" | remove \n
quoted = command.replace('\\','\\\\')\
.replace('"','\\"')
if sublime.platform() == 'windows':
command = 'ConEmuC -GuiMacro:0 paste(2,"' + quoted + '\\n")'
Popen(command)
else:
# Multiline with tmux needs multiple commands
for line in quoted.split('\n'):
line = re.sub(r";$","\\;",line) # quote ; at end of line
line = re.sub(r"\$","\\\$", line) # quote $
command = 'tmux send-keys -l -t repl "' + line + '"'
print(command)
Popen(command,shell=True)
Popen('tmux send-keys -t repl C-m',shell=True)
# test switching
def alternate(self,file):
return getattr(self, "alternate_"+ self.lang)(file)
# converters for alternate file witching named altenate_syntax
def alternate_powershell(self,file):
if re.compile( r'\.tests\.',re.I).search(file):
# c:\project\file.tests.ps1
return re.sub(r'\.tests\.',".",file)
else:
# c:\project\file.ps1
return re.sub(r'\.ps1$',".tests.ps1",file)
def alternate_ruby(self,file):
if re.compile( r'\\test_',re.I).search(file):
# c:\project\test\bar\test_foo.ps1
a = re.sub(r'\\test\\',"\\\\lib\\\\",file)
return re.sub(r'\\test_',"\\\\",a)
else:
# c:\project\lib\bar\foo.ps1
a = re.sub(r'\\lib\\',"\\\\test\\\\",file)
return re.sub(r'\\([^\\]+)$',"\\\\test_\g<1>", a)
# returns false if there is an error happening
def init_er(self):
self.er = Er(self)
if self.er.error:
print(self.er.error)
return False
else:
return True