forked from randy3k/SendCode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
send_code.py
104 lines (80 loc) · 2.91 KB
/
send_code.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
import sublime
import sublime_plugin
import os
import re
from .code_getter import CodeGetter
from .code_sender import CodeSender
def escape_dquote(cmd):
cmd = cmd.replace('\\', '\\\\')
cmd = cmd.replace('"', '\\"')
return cmd
def escape_squote(cmd):
cmd = cmd.replace('\\', '\\\\')
cmd = cmd.replace("\'", "\'")
return cmd
PATTERN = re.compile(r"""
(?P<quote>["'])
(?P<quoted_var>
\$ (?: [_a-z][_a-z0-9]* | \{[^}]*\} )
)
(?P=quote)
|
(?P<var>
\$ (?: [_a-z][_a-z0-9]* | \{[^}]*\} )
)
""", re.VERBOSE)
class SendCodeCommand(sublime_plugin.TextCommand):
def resolve(self, cmd):
view = self.view
window = view.window()
extracted_variables = window.extract_variables()
if len(view.sel()) == 1:
row, _ = view.rowcol(view.sel()[0].begin())
extracted_variables["line"] = str(row + 1)
word = view.substr(view.sel()[0])
if not word:
word = view.substr(view.word(view.sel()[0].begin()))
extracted_variables["selection"] = word
fname = view.file_name()
if fname:
fname = os.path.realpath(fname)
for folder in window.folders():
if fname.startswith(os.path.realpath(folder) + os.sep):
extracted_variables["current_folder"] = folder
break
def convert(m):
quote = m.group("quote")
if quote:
var = sublime.expand_variables(m.group("quoted_var"), extracted_variables)
if quote == "'":
return "'" + escape_squote(var) + "'"
else:
return '"' + escape_dquote(var) + '"'
else:
return sublime.expand_variables(m.group("var"), extracted_variables)
cmd = PATTERN.sub(convert, cmd)
return cmd
def run(self, edit, cmd=None, prog=None, confirmation=None):
# set CodeGetter before get_text() because get_text may change cursor locations.
if confirmation:
ok = sublime.ok_cancel_dialog(confirmation)
if not ok:
return
sender = CodeSender.initialize(self.view, prog=prog, from_view=cmd is None)
if cmd:
cmd = self.resolve(cmd)
else:
getter = CodeGetter.initialize(self.view)
cmd = getter.get_text()
sublime.set_timeout_async(lambda: sender.send_text(cmd))
# historial reason
class SendReplCommand(SendCodeCommand):
def run(self, *args, **kargs):
print("The `send_repl` command has been deprecated, please use `send_code` command.")
super(SendReplCommand, self).run(*args, **kargs)
class SendCodeBuildCommand(sublime_plugin.WindowCommand):
def run(self, cmd=None, prog=None):
self.window.active_view().run_command(
"send_code",
{"cmd": cmd, "prog": prog}
)