forked from hbt/mouseless
-
Notifications
You must be signed in to change notification settings - Fork 0
/
cvim_server.py
executable file
·75 lines (57 loc) · 2.03 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
62
63
64
65
66
67
68
69
70
71
72
73
#!/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 via the "vimcommand" cVimrc option
'''
import os
import sys
import shlex
from json import loads
import subprocess
from tempfile import mkstemp
from http.server import HTTPServer, BaseHTTPRequestHandler
from SocketServer import ThreadingMixIn
from BaseHTTPServer import HTTPServer
from SimpleHTTPServer import SimpleHTTPRequestHandler
from time import sleep
reload(sys)
sys.setdefaultencoding('utf8')
print sys.getdefaultencoding()
PORT = 8001
VIM_COMMAND = 'gvim -f'
def edit_file(content, line, column):
fd, fn = mkstemp(suffix='.txt', prefix='cvim-', text=True)
os.write(fd, content.encode('utf8'))
os.close(fd)
command = VIM_COMMAND + " " + fn + ' -c "call cursor(' + str(line) + ',' + str(column) + ')"'
subprocess.Popen(shlex.split(command)).wait()
text = None
with open(fn, 'r') as f:
text = f.read()
#os.unlink(fn)
return text
class ThreadingServer(ThreadingMixIn, HTTPServer):
pass
class CvimServer(SimpleHTTPRequestHandler):
def do_POST(self):
length = int(self.headers['Content-Length'])
content = loads(self.rfile.read(length).decode('utf8'))
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'], content['line'], content['column'])
self.wfile.write(edit.encode('utf8'))
def init_server(server_class=HTTPServer, handler_class=BaseHTTPRequestHandler):
ThreadingServer(('127.0.0.1', PORT), CvimServer).serve_forever()
try:
init_server()
except KeyboardInterrupt:
exit