Skip to content

Instantly share code, notes, and snippets.

@e-roux
Created February 28, 2018 21:49
Show Gist options
  • Save e-roux/2c7ab77c8f0d80849a2e086624fbe0ce to your computer and use it in GitHub Desktop.
Save e-roux/2c7ab77c8f0d80849a2e086624fbe0ce to your computer and use it in GitHub Desktop.
SublimeText
"""
~/Library/Application Support/Sublime Text 3/Packages/SublimeREPL/ipy_repl.py
"""
import os
import sys
import json
import socket
import threading
import IPython
activate_this = os.environ.get("SUBLIMEREPL_ACTIVATE_THIS", None)
# turn off pager
os.environ['TERM'] = 'emacs'
if activate_this:
with open(activate_this, "r") as f:
exec(f.read(), {"__file__": activate_this})
from traitlets.config.loader import Config
editor = "subl -w"
cfg = Config()
cfg.InteractiveShell.readline_use = False
cfg.InteractiveShell.autoindent = False
# cfg.InteractiveShell.colors = "NoColor"
cfg.InteractiveShell.editor = os.environ.get("SUBLIMEREPL_EDITOR", editor)
cfg.ZMQTerminalInteractiveShell.simple_prompt = True
from jupyter_console.app import ZMQTerminalIPythonApp
def kernel_client(zmq_shell):
return zmq_shell.kernel_client
embedded_shell = ZMQTerminalIPythonApp(config=cfg, user_ns={})
embedded_shell.initialize()
ac_port = int(os.environ.get("SUBLIMEREPL_AC_PORT", "0"))
ac_ip = os.environ.get("SUBLIMEREPL_AC_IP", "127.0.0.1")
if ac_port:
s = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
s.connect((ac_ip, ac_port))
def read_netstring(s):
size = 0
while True:
ch = s.recv(1)
if ch == b':':
break
size = size * 10 + int(ch)
msg = b""
while size != 0:
msg += s.recv(size)
size -= len(msg)
ch = s.recv(1)
assert ch == b','
return msg
def send_netstring(sock, msg):
payload = b"".join([str(len(msg)).encode("ascii"), b':', msg.encode("utf-8"), b','])
sock.sendall(payload)
def complete(zmq_shell, req):
kc = kernel_client(zmq_shell)
msg_id = kc.complete(req['line'], req['cursor_pos'])
msg = kc.shell_channel.get_msg(timeout=50)
if msg['parent_header']['msg_id'] == msg_id:
return msg["content"]["matches"]
return []
def handle():
while True:
msg = read_netstring(s).decode("utf-8")
try:
req = json.loads(msg)
completions = complete(embedded_shell, req)
result = (req["text"], completions)
res = json.dumps(result)
send_netstring(s, res)
except Exception:
send_netstring(s, "[]")
if ac_port:
t = threading.Thread(target=handle)
t.start()
embedded_shell.start()
if ac_port:
s.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment