-
Notifications
You must be signed in to change notification settings - Fork 0
/
vu.py
executable file
·442 lines (377 loc) · 13.5 KB
/
vu.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
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
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
#!/usr/bin/env python
import os
import sys
import argparse
import re
import json
import subprocess
import StringIO
import time
import tempfile
import fnmatch
DEFAULT_VIM = "gvim"
DEFAULT_SERVER = "default"
START_SERVER_TIMEOUT = 5
START_SERVER = "{vim} --servername {servername}"
LIST_SERVERS = "{vim} --serverlist"
RUN_COMMAND = """{vim} --servername {servername} --remote-expr \
'VimUtilsCommandOutput(\"{cmd}\")'"""
OPEN_TABS = """{vim} --servername {servername} --remote-tab-silent {files}"""
DUMP_BUFFER = """{vim} --servername {servername} --remote-expr \
'VimUtilsWriteBufferToTmpFile(\"{bufno}\")'"""
SEND_KEYS = """{vim} --servername {servername} --remote-send '{keys}'"""
VIMSCRIPT = """\
function! VimUtilsCommandOutput(cmd)
redir => message
silent execute a:cmd
redir END
return message
endfunction
"Write a buffer to a tmp file and return the tmp filename
function! VimUtilsWriteBufferToTmpFile(bufno)
python << EOF
import vim
import random
tmpfile = "/tmp/vimutils_" + str(random.randint(1,19928))
current_buffer = str(vim.current.buffer.number)
vim.command(":buffer " + vim.eval("a:bufno"))
vim.command("silent execute \\":write " + tmpfile + "\\"")
vim.command("silent execute \\":buffer " + current_buffer + "\\"")
EOF
redir => bb
:py print tmpfile
redir END
return bb
endfunction
"""
HELP_SERVERS = "List running vim servers."
HELP_START = "Start a vim server."
HELP_OPEN = "Open file(s)."
HELP_TABS = "Open file(s) in tab(s)."
HELP_DIFF = "Diff files"
HELP_BUFFERS = "List buffers."
HELP_DUMP_BUFFER = "Print the contents of a buffer (by buffer number)"
HELP_DUMP_FILE = """Print the contents of the buffer with the first filename
matching PATTERN"""
HELP_GREP = "Search the buffers using a Python regular expression."
HELP_KEYS = "Send a string of keys to the target vim server"
HELP_RUN = "Run a command and print the output."
HELP_SHELL_ALIASES = "Print a set of nice-to-have shell "\
"functions for your .(bash|zsh)rc"
HELP_NO_FULL_PATH = "Don't use the full path of this script"
def sh(cmd):
p = subprocess.Popen(cmd,
shell=True,
stdout=subprocess.PIPE)
r = p.wait()
out, err = p.communicate()
return r, out, err
class Server:
def __init__(self, servername="default", vim="gvim", autostart=True):
self.servername = servername.upper()
self.vim = vim
self.use_autostart = autostart
def list_servers(self):
try:
r, so, se = sh(LIST_SERVERS.format(vim=self.vim))
assert r == 0
servers = so.strip().split("\n")
return servers
except:
raise
return []
def is_running(self):
servers = self.list_servers()
return self.servername in servers
def run(self, s):
s = s.replace('"', '\\"')
return sh(RUN_COMMAND.format(vim=self.vim,
servername=self.servername,
cmd=s))
def send_keys(self, keys):
return sh(SEND_KEYS.format(vim=self.vim, servername=self.servername,
keys=keys))
def start(self):
if self.is_running(): return False
tf = tempfile.NamedTemporaryFile()
with open(tf.name, "w") as f:
f.write(VIMSCRIPT)
r = os.system(START_SERVER.format(vim=self.vim,
servername=self.servername))
# Wait for server to start
waited = 0
while not self.is_running():
if waited == START_SERVER_TIMEOUT:
sys.stderr.write("Timed out while trying to "
"start server '%s'\n" % self.servername)
return False
time.sleep(1)
waited = waited + 1
if r == 0:
r, out, err = self.send_keys(":source "+tf.name+" <CR>")
if r != 0:
return False
r, out, err = self.send_keys(":echo \"Started By VimUtils\" <CR>")
return True
return False
def open(self, files):
if type(files) != list:
files = [files]
files = [os.path.realpath(f) for f in files]
for f in files:
r, out, err = self.run(":e "+f)
def open_tabs(self, files):
if type(files) != list:
files = [files]
files = [os.path.realpath(f) for f in files]
return os.system(OPEN_TABS.format(vim=self.vim,
servername=self.servername,
files=" ".join(files)))
def open_diff(self, files):
if type(files) != list:
files = [files]
files = [os.path.realpath(f) for f in files]
self.open(files[0])
for f in files[1:]:
f = os.path.realpath(f)
self.run(":diffsplit %s" % (f))
def buffers_str(self):
r, out, err = self.run(":buffers")
return out
def buffers(self):
r, out, err = self.run(":buffers")
lines = out.strip().split("\n")
bufs = []
for line in lines:
bufar = re.split('\s+',line.strip().replace("line",""))
if len(bufar) == 3:
bufar.insert(1,"") #If theres no mode, insert None
bufar[2] = bufar[2].replace("\"", "")
buf = {
"id" : int(bufar[0]),
"mode" : bufar[1],
"file" : bufar[2],
"line" : bufar[3],
"unlisted" : False,
"current" : False,
"alternate" : False,
"active" : False,
"hidden" : False,
"modifiable" : True,
"readonly" : False,
"modified" : False,
"readerrors" : False
}
for m in bufar[1]:
if m == "u":
buf["unlisted"] = True
elif m == "%":
buf["current"] = True
elif m == "#":
buf["alternate"] = True
elif m == "a":
buf["active"] = True
elif m == "h":
buf["hidden"] = True
elif m == "-":
buf["modifiable"] = False
elif m == "=":
buf["readonly"] = True
elif m == "+":
buf["modified"] = True
elif m == "x":
buf["readerror"] = True
else:
continue
bufs.append(buf)
return bufs
def dump_buffer(self, bufno):
r, out, err = sh(DUMP_BUFFER.format(vim=self.vim,
servername=self.servername,
bufno=str(bufno)))
filename = out.strip()
with open(filename) as f:
return f.read()
def dump_buffers(self):
out = []
for buf in self.buffers():
out.append(self.dump_buffer(buf["id"]))
return out
def dump_files(self, pattern, wildcards=True):
out = []
for buf in self.buffers():
match = False
if wildcards:
match = fnmatch.fnmatch(buf["file"], pattern)
else:
match = (pattern == buf["file"])
if match:
out.append({"filename": buf["file"],
"content": self.dump_buffer(buf["id"])})
return out
def search_buffers(self, expr, **kwargs):
buffers = self.buffers()
expr = re.compile(expr)
matches = []
for buf in buffers:
lines = self.dump_buffer(buf["id"]).split("\n")
lineno = 1
for line in lines:
if re.search(expr, line):
matches.append({
"lineno" : lineno,
"buf" : buf,
"line" : line
})
lineno = lineno + 1
return matches
def config():
vim = os.environ.get("VIMUTILS_VIM", DEFAULT_VIM),
default_server = os.environ.get("VIMUTILS_DEFAULT_SERVER", DEFAULT_SERVER)
config_file = os.path.join(os.environ["HOME"], ".vimutils.json")
if os.path.isfile(config_file):
with open(config_file) as f:
c = json.loads(f.read())
vim = c["vim"]
default_server = c["default_server"]
return vim, default_server
def vimutils(servername=None, **kwargs):
c_vim, c_default_server = config()
vim = kwargs.get("vim", None)
if not vim:
vim = c_vim
if not servername:
servername = c_default_server
s = Server(servername, vim)
return s
def handle_servers(s, args):
print("\n".join(s.list_servers()))
def handle_start(s, args):
r = s.start()
if not r:
sys.stderr.write("Could not start vim server '%s': " % (s.servername))
if s.is_running():
sys.stderr.write("Already running")
else:
sys.stderr.write("Unknown Error")
sys.stderr.write("\n")
exit(1)
def handle_open(s, args):
s.open(args.files)
def handle_tabs(s, args):
s.open_tabs(args.files)
def handle_diff(s, args):
s.open_diff(args.files)
def handle_buffers(s, args):
if args.json:
print(json.dumps({"buffers":s.buffers()}, indent=2))
else:
print(s.buffers_str())
def handle_dump_buffer(s, args):
print(s.dump_buffer(args.bufno))
def handle_dump_file(s, args):
wc = not args.exact
files = s.dump_files(args.pattern, wc)
if not files:
exit(1)
print(files[0]["content"])
def handle_grep(s, args):
try:
results = s.search_buffers(args.expr)
except re.error as e:
sys.stderr.write("Invalid regular expression:\n")
sys.stderr.write(str(e)+"\n")
exit(1)
for result in results:
print("%d:%s:%d: %s" % (result["buf"]["id"],
result["buf"]["file"],
result["lineno"],
result["line"]))
def handle_keys(s, args):
s.send_keys(args.keys)
def handle_run(s, args):
r, out, err = s.run(args.cmdstr)
print(out)
SHELL_ALIASES = [
("vs", "start"),
("ve", "open"),
("vt", "tabs"),
("vd", "diff"),
("vls", "servers"),
("vbls", "buffers"),
("vdb", "dump-buffer"),
("vr", "run"),
("vk", "keys"),
("vgrep", "grep")
]
SHELL_ALIAS = """
{alias} () {{
{vu} {args} "$@";
}}
"""
def handle_shell_aliases(s, args):
out = ""
path = os.path.realpath(__file__)
if args.no_full_path:
path = os.path.basename(path)
for item in SHELL_ALIASES:
alias, args = item
out += SHELL_ALIAS.format(vu=path,
alias=alias,
args=args)
print(out)
def main():
argp = argparse.ArgumentParser()
subp = argp.add_subparsers()
argp.add_argument("-c","--vim-command", default="gvim")
argp.add_argument("-s", "--servername", default="default")
argp_servers = subp.add_parser("servers", help=HELP_SERVERS)
argp_servers.set_defaults(func=handle_servers)
argp_start = subp.add_parser("start", help=HELP_START)
argp_start.set_defaults(func=handle_start)
argp_open = subp.add_parser("open", help=HELP_OPEN)
argp_open.add_argument("files", nargs="*")
argp_open.set_defaults(func=handle_open)
argp_tabs = subp.add_parser("tabs", help=HELP_TABS)
argp_tabs.add_argument("files", nargs="*")
argp_tabs.set_defaults(func=handle_tabs)
argp_diff = subp.add_parser("diff", help=HELP_DIFF)
argp_diff.add_argument("files", nargs="*")
argp_diff.set_defaults(func=handle_diff)
argp_buffers = subp.add_parser("buffers", help=HELP_BUFFERS)
argp_buffers.add_argument("-j", "--json", action="store_true",
help="Output in json format")
argp_buffers.set_defaults(func=handle_buffers)
argp_dump_buffer = subp.add_parser("dump-buffer", help=HELP_DUMP_BUFFER)
argp_dump_buffer.add_argument("bufno", type=int, action="store")
argp_dump_buffer.set_defaults(func=handle_dump_buffer)
argp_dump_file = subp.add_parser("dump-file", help=HELP_DUMP_FILE)
argp_dump_file.add_argument("pattern", action="store")
argp_dump_file.add_argument("-e","--exact", action="store_true",
help="Only exact match (no wildcards)")
argp_dump_file.set_defaults(func=handle_dump_file)
argp_grep = subp.add_parser("grep")
argp_grep.add_argument("expr", action="store")
argp_grep.set_defaults(func=handle_grep)
argp_keys = subp.add_parser("keys", help=HELP_KEYS)
argp_keys.add_argument("keys", action="store")
argp_keys.set_defaults(func=handle_keys)
argp_run = subp.add_parser("run", help=HELP_RUN)
argp_run.add_argument("cmdstr", action="store")
argp_run.set_defaults(func=handle_run)
argp_shell_aliases = subp.add_parser("shell-aliases",
help=HELP_SHELL_ALIASES)
argp_shell_aliases.add_argument("-P",
"--no-full-path",
action="store_true",
help=HELP_NO_FULL_PATH)
argp_shell_aliases.set_defaults(func=handle_shell_aliases)
args = argp.parse_args()
s = vimutils(args.servername, vim=args.vim_command)
if args.func not in [handle_start, handle_servers,
handle_shell_aliases]:
if not s.is_running():
s.start()
args.func(s,args)
if __name__ == "__main__":
main()