Skip to content

Instantly share code, notes, and snippets.

@glyph

glyph/prompt.py Secret

Created April 13, 2020 08:07
Show Gist options
  • Select an option

  • Save glyph/e02303b61ca6fec0f0bc504b7f5fe52e to your computer and use it in GitHub Desktop.

Select an option

Save glyph/e02303b61ca6fec0f0bc504b7f5fe52e to your computer and use it in GitHub Desktop.
from __future__ import print_function
def __set_prompt__():
import os
import sys
sys.path.append(os.path.expanduser("~/Settings/Python/Lib"))
try:
from importlib.util import find_spec
except ImportError:
from imp import find_module
else:
def module_not_found(m):
if find_spec(m) is None:
raise ImportError(m)
find_module = module_not_found
def debug(*stuff):
if os.environ.get("PROMPTDEBUG"):
print(*stuff)
def macreactor():
try:
find_module("AppKit")
except ImportError:
debug('No AppKit, no CF loop.')
return 'select'
# Screw around with various Cocoa APIs without presenting an annoying
# bouncing-forever dock icon.
from twisted.application.reactors import Reactor
from twisted.plugins import twisted_reactors
from sys import modules
class CFGuiReactorModule(object):
__name__ = "__cfgui__"
def install(self):
debug("Fixing PyObjCTools...")
import PyObjCTools
PyObjCTools.__path__ = origPyObjCTools
debug("Loading AppHelper...")
from PyObjCTools import AppHelper
debug("Loading CFReactor...")
from twisted.internet.cfreactor import install
debug("Loading Foundation...")
from Foundation import NSPoint
debug("Loading AppKit...")
from AppKit import (
NSApplication, NSEvent, NSMouseMoved,
NSApplicationActivationPolicyAccessory
)
debug("Synthesizing shared application...")
app = NSApplication.sharedApplication()
def term():
"""
Upon receiving the TERM signal (well, any reactor shutdown,
really), create and dispatch a synthetic NSEvent so that
the loop un-blocks and can properly shut down / exit.
"""
app.stop_(app)
eventType = NSMouseMoved
location = NSPoint(0, 0)
modifierFlags = 0
timestamp = 0
windowNumber = 0
context = None
eventNumber = 0
clickCount = 0
pressure = 0.0
evt = (getattr(NSEvent,
"mouseEventWithType_location_"
"modifierFlags_timestamp_windowNumber_"
"context_eventNumber_clickCount_"
"pressure_")(eventType, location,
modifierFlags, timestamp, windowNumber,
context, eventNumber, clickCount,
pressure))
app.postEvent_atStart_(evt, True)
#NSRunLoop.currentRunLoop().stop()
# AppHelper.stopEventLoop()
debug('Setting Activation Policy...')
ok = app.setActivationPolicy_(
NSApplicationActivationPolicyAccessory
)
debug("Activation policy set: " + repr(ok))
r = install(runner=AppHelper.runEventLoop)
r.addSystemEventTrigger("before", "shutdown", term)
return r
modules["__cfgui__"] = CFGuiReactorModule()
import __cfgui__
twisted_reactors.cf = Reactor(
"cf", __cfgui__.__name__, "lol docs"
)
return 'cf'
if os.environ.get("TERM") not in [
"xterm", "xterm-color", "xterm-256color",
"eterm-color", "screen", "screen-256color"]:
debug("Wrong TERM, bailing out.")
return
import sys
if 'IPython' in sys.modules:
return
def htmlhelp(thing):
import pydoc
import tempfile
import webbrowser
resolved, name = pydoc.resolve(thing, 0)
text = pydoc.html.page(pydoc.describe(resolved),
pydoc.html.document(resolved, name))
name = os.path.join(tempfile.mkdtemp(), "pydoc.html")
with open(name, 'wb') as f:
f.write(text.encode("utf-8"))
webbrowser.open('file://' + name)
try:
import __builtin__
builtins = __builtin__
except ImportError:
import __main__
builtins = __main__
builtins.help = htmlhelp
if 'bpython' in sys.modules:
import itertools
if 'twisted.internet.reactor' in sys.modules:
from twisted.internet.defer import Deferred
global reactor
from twisted.internet import reactor
reactor = reactor
dcount = lambda: next(itertools.count())
orighook = sys.displayhook
dwait = {}
class message(object):
def __init__(self, m):
self.m = m
def __repr__(self):
return self.m
def deferredhook(x):
orighook(x)
if isinstance(x, Deferred):
dnum = dcount()
if x not in dwait:
dwait[x] = dnum
def whendone(result):
del dwait[x]
try:
orighook(message("Deferred #{0} Fired:"
.format(dnum)))
orighook(result)
except:
pass # XXX fixme!
else:
return result
orighook(message("Waiting on Deferred #{0}..."
.format(dnum)))
import __main__
__main__._ = x
def failureify(result):
return message(result.getTraceback())
x.addErrback(failureify)
x.addCallback(whendone)
else:
orighook(message("Already waiting; "
"this is Deferred #{0}."
.format(dwait[x])))
sys.displayhook = deferredhook
# We're already in bpython, so either the following stuff already ran
# to put us into bpython or the user ran bpython directly; in either
# case it's too late to do it again.
return
debug("Looking for pyObjC")
try:
import PyObjCTools
except ImportError:
debug("Nope")
else:
origPyObjCTools = list(PyObjCTools.__path__)
debug("OK")
# Initialize bpython, if we can.
twisted = urwid = entrypoint = None
mainpoint = sys.executable
try:
debug("Loading Twisted...")
import twisted.application.reactors
debug("Loading Urwid...")
import urwid
debug("Loading BPython...")
from bpython.urwid import main as entrypoint
mainpoint = 'bpython'
except ImportError as ie:
debug("No urwid because", ie)
if entrypoint is None:
try:
debug("Loading BPython...")
from bpython.curtsies import main as entrypoint
mainpoint = 'bpython-urwid'
except ImportError as ie:
debug("No bpython because", ie)
if twisted is not None and urwid is not None:
if sys.platform == 'darwin':
reactor = macreactor()
else:
try:
__import__("gtk")
except ImportError:
reactor = 'default'
else:
reactor = 'gtk2'
from twisted.application.reactors import getReactorTypes
if not list(getReactorTypes()):
print("No reactor plugins available.")
else:
sys.argv.insert(1, "--reactor="+reactor)
#sys.argv.insert(1, "--config=.bpython/config")
# Okay now let's get _super_ specific
for k, v in {
"ctrl b": "cursor left",
"ctrl f": "cursor right",
# "ctrl k": "cut to buffer",
}.items():
urwid.command_map[k] = v
if entrypoint is not None:
sys.argv[0] = mainpoint
try:
# Because BPython's initialization is somewhat like Python's
# interactive initialization, this actually dumps us back at
# the top of __set_prompt__ again, where we do Deferred-hook
# installation.
entrypoint()
except SystemExit:
raise
except:
# this is really bpython's job, I doubt this code will ever be
# run.
import traceback
traceback.print_exc()
sys.exit(1)
else:
sys.exit(0)
elif False:
import os
__import__("rlcompleter")
import readline
#readline.set_pre_input_hook(pre_input)
if 'libedit' in readline.__doc__:
debug('libedit detected!')
#readline.parse_and_bind('bind ^I rl_complete')
else:
readline.parse_and_bind("Tab: complete")
hostname = os.uname()[1].split('.')[0]
user = os.environ['USER']
color = os.environ.get('HOSTCOLOR')
bold = os.environ.get('BOLD')
#RL_PROMPT_START_IGNORE = '\x01'
#RL_PROMPT_END_IGNORE = '\x02'
if color:
hostname = '\x01\x1b[%sm\x02%s\x01\x1b[0m\x02' % (color, hostname)
if bold:
hostname = '\x01\x1b[1m\x02%s\x01\x1b[0m\x1b[0m\x02' % (hostname,)
class Completer(object):
def __str__(self):
# readline.parse_and_bind('bind ^I rl_complete')
return "%s@%s>>> " % (user, hostname)
class Indenter(object):
def __str__(self):
# Bah, this is evaluated before each *ps1* is printed; there
# doesn't seem to be a hook for printing ps2.
# readline.parse_and_bind("bind -s ^I ' '")
return "%s@%s... " % (user, hostname)
# sys.ps1 = Completer()
# sys.ps2 = Indenter()
__set_prompt__()
del __set_prompt__
globals().pop("__file__", None)
# Useful imports:
import os
import sys
import glob
from pprint import pprint as pprint, pformat
# Don't complain, pyflakes, I'm re-exporting these on purpose.
__all__ = [
'os', 'sys', 'glob', 'pprint', 'pformat'
]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment