-
Notifications
You must be signed in to change notification settings - Fork 325
/
cvim_server.py
executable file
·61 lines (50 loc) · 1.71 KB
/
cvim_server.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
#!/usr/bin/python3
'''
USAGE: ./cvim_server.py
If you want to use native Vim to edit text boxes
you must be running this script. To begin editing,
first map the editWithVim (e.g. "imap <C-o> editWithVim") mapping.
By default, this script will spawn a gvim ("gvim -f"), but this action
can be changed by setting the VIM_COMMAND variable below
'''
import os
import sys
import shlex
from json import loads
import subprocess
from tempfile import mkstemp
from http.server import HTTPServer, BaseHTTPRequestHandler
PORT = 8001
VIM_COMMAND = 'gvim -f'
def edit_file(content):
fd, fn = mkstemp(suffix='.txt', prefix='cvim-', text=True)
os.write(fd, content.encode('utf8'))
os.close(fd)
subprocess.Popen(shlex.split(VIM_COMMAND) + [fn]).wait()
text = None
with open(fn, 'r', encoding='utf8') as f:
text = f.read()
os.unlink(fn)
return text
class CvimServer(BaseHTTPRequestHandler):
def do_POST(self):
length = int(self.headers['Content-Length'])
content_str = self.rfile.read(length).decode('utf8')
content = loads(content_str)
self.send_response(200)
self.send_header('Content-Type', 'text/plain')
self.end_headers()
# Block XMLHttpRequests originating from non-Chrome extensions
if not self.headers.get('Origin', '').startswith('chrome-extension'):
edit = ''
else:
edit = edit_file(content['data'])
self.wfile.write(edit.encode('utf8'))
def init_server(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
server_address = ('127.0.0.1', PORT)
httpd = server_class(server_address, CvimServer)
httpd.serve_forever()
try:
init_server()
except KeyboardInterrupt:
pass