-
Notifications
You must be signed in to change notification settings - Fork 3
/
emacsclientw
executable file
·272 lines (214 loc) · 7.9 KB
/
emacsclientw
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
#!/usr/bin/python
USAGE = """
Usage: {prog} [OPTIONS] FILE...
{prog} --print-server-name
An emacsclient wrapper which invoke emacs-server automatically
and name the server after the current environments to avoid the `server-name` conflicts.
All unknown arguments/options will be passed to emacsclient.
"""
# TODO: No GUI Mac OS X support
RETRY_NUMBER = 30
RETRY_INTERVAL = 0.5 # sec
##
import os, sys, subprocess, time, re, optparse, shutil, tempfile
DEFAULT_EMACSCLIENT = "emacsclient"
MACOSX_EMACSCLIENT = "/Applications/Emacs.app/Contents/MacOS/bin/emacsclient"
PROG = os.path.basename(sys.argv[0])
USAGE = USAGE[1:][:-1].format(prog=PROG)
DEVNULL = open(os.devnull, "wb")
PROGRESS_CHARS = ["\\", "|", "/", "-"]
def main():
cmd, args = get_command()
cmd.run(args)
def get_command():
p = PassThroughOptionParser(add_help_option=False)
p.set_usage(USAGE)
p.set_defaults(command=Command.EMACSCLIENT_INVOKER)
p.add_option("-h", "--help",
help="Show this help message and exit.",
action="help")
p.add_option("-H", "--emacsclient-help",
help="Show `emacslient --help`.",
action="store_const",
dest="command",
const=Command.EMACSCLIENT_HELP_PRINTER)
p.add_option("--print-server-name",
help="Print the server name after the current environments. "+
"Does not invoke emacsclient.",
action="store_const",
dest="command",
const=Command.SERVER_NAME_PRINTER)
opts, args = p.parse_args()
return opts.command(), args
def get_server():
for svr in [MacOSXServer, XEmacsServer, ScreenEmacsServer, TmuxEmacsServer]:
s = svr()
if s.is_runnable():
return s
abort("cannot generate the socket-name. "
"require DISPLAY or STY or TMUX environment variable.")
def abort(msg):
sys.exit("Abort: " + msg)
def stderr(s):
sys.stderr.write(s)
sys.stderr.write(os.linesep)
def pp_string_as_cmd(cmd):
return " ".join(map(convert_as_arg, cmd))
def convert_as_arg(arg):
if re.search(r'[\s?!&]', arg, 1):
return '"%s"' % re.sub(r'"', '\\"', arg)
else:
return arg
def remove_all_from(l, *elements):
for e in elements:
while e in l:
l.remove(e)
def create_stdin_tempfile():
t = tempfile.NamedTemporaryFile(delete=False)
shutil.copyfileobj(sys.stdin, t)
return t.name
def get_progress_char(c):
return PROGRESS_CHARS[c % len(PROGRESS_CHARS)]
## commands
class ServerNamePrinter:
def run(self, args):
server = get_server()
print(server.name())
class EmacsclientInvoker:
def run(self, args):
server = get_server()
if not server.is_running():
server.start()
stdin_file = None
if "-" in args:
remove_all_from(args, "-", "--no-wait", "-n")
stdin_file = create_stdin_tempfile()
args.append("--eval")
args.append(("(let ((b (create-file-buffer \"*stdin*\")))"
" (switch-to-buffer b)"
" (insert-file-contents \"{stdin_file}\")"
" (delete-file \"{stdin_file}\"))").format(**vars()))
e = server.invoke_emacsclient(args)
server.focus()
e.wait()
class EmacsclientHelpPrinter:
def run(self, args):
server = get_server()
server.help()
class Command:
SERVER_NAME_PRINTER = ServerNamePrinter
EMACSCLIENT_INVOKER = EmacsclientInvoker
EMACSCLIENT_HELP_PRINTER = EmacsclientHelpPrinter
## emacs-servers
class EmacsServer:
"""super class for emacs server"""
def __init__(self):
self.emacsclient = DEFAULT_EMACSCLIENT
def is_running(self):
s = subprocess.call([self.emacsclient,
"--socket-name", self.name(),
"--eval", "(emacs-pid)"],
stderr=DEVNULL, stdout=DEVNULL)
return s == 0
def start(self):
opts = [
"--eval", "(setq server-name \"%s\")" % self.name(),
"--eval", "(server-start)"
]
self._start(opts)
self.__wait()
def invoke_emacsclient(self, args):
cmd = [self.emacsclient, "--socket-name", self.name()] + args
stderr("Invoke: %s" % pp_string_as_cmd(cmd))
return subprocess.Popen(cmd)
def help(self):
subprocess.call([self.emacsclient, "--help"])
def focus(self):
pass
def __wait(self):
c = 0
while c < RETRY_NUMBER and (not self.is_running()):
c += 1
time.sleep(RETRY_INTERVAL)
sys.stderr.write("{}\r".format(get_progress_char(c)))
sys.stderr.flush()
if c == RETRY_NUMBER:
raise RetryLimitExceededException()
class RetryLimitExceededException(BaseException):
pass
class XEmacsServer(EmacsServer):
"""emacs-server for X Window System"""
def name(self):
return "wm-" + os.getenv("DISPLAY")
def _start(self, emacs_opts):
cmd = "emacs "
cmd += " ".join(["'%s'" % e for e in emacs_opts])
cmd += " >/dev/null 2>&1 &"
subprocess.check_call(["sh", "-c", cmd])
# nohup?
def is_runnable(self):
return bool(os.getenv("DISPLAY"))
# http://emacsformacosx.com/
class MacOSXServer(EmacsServer):
"""emacs-server for Mac OS X"""
def __init__(self):
self.emacsclient = MACOSX_EMACSCLIENT
def name(self):
return "Darwin"
def _start(self, emacs_opts):
cmd = ["open", "-a", "Emacs", "--args"]
cmd += emacs_opts
subprocess.check_call(cmd)
def is_runnable(self):
return subprocess.check_output(["uname"]).strip() == "Darwin"
class ScreenEmacsServer(EmacsServer):
"""emacs-server for GNU screen"""
def name(self):
return "sty-" + os.getenv("STY")
def _start(self, emcas_opts):
subprocess.check_call(["screen", "emacs"] + emcas_opts)
def focus(self):
o = subprocess.check_output([self.emacsclient,
"--socket-name", self.name(),
"--eval", "(getenv \"WINDOW\")"])
wid = o.replace('"', "")
if len(wid) == 0:
return
subprocess.check_call(["screen", "-X", "select", str(wid)])
def is_runnable(self):
return bool(os.getenv("STY"))
class TmuxEmacsServer(EmacsServer):
"""emacs-server for GNU screen"""
def name(self):
cmd = ["tmux", "display", "-p", "#I"]
return "tmux-" + subprocess.check_output(cmd).strip()
def _start(self, emcas_opts):
subprocess.check_call(["tmux", "new-window", "emacs"] + emcas_opts)
def focus(self):
cmd = [self.emacsclient,
"--socket-name", self.name(),
"--eval", "(getenv \"TMUX_PANE\")"]
pane_id = subprocess.check_output(cmd).strip().replace("\"", "")
if len(pane_id) == 0:
return
subprocess.check_call(["tmux", "select-window", "-t", str(pane_id)])
def is_runnable(self):
return bool(os.getenv("TMUX"))
##
# http://stackoverflow.com/questions/1885161/how-can-i-get-optparses-optionparser-to-ignore-invalid-options
class PassThroughOptionParser(optparse.OptionParser):
"""
An unknown option pass-through implementation of OptionParser.
When unknown arguments are encountered, bundle with largs and try again,
until rargs is depleted.
sys.exit(status) will still be called if a known argument is passed
incorrectly (e.g. missing arguments or bad argument types, etc.)
"""
def _process_args(self, largs, rargs, values):
while rargs:
try:
optparse.OptionParser._process_args(self,largs,rargs,values)
except (optparse.BadOptionError, optparse.AmbiguousOptionError), e:
largs.append(e.opt_str)
if __name__ == "__main__":
main()