Skip to content

Instantly share code, notes, and snippets.

@jikuja
Created August 5, 2017 07:11
Show Gist options
  • Save jikuja/22f07f21e66983a79de4a5cfa05238d8 to your computer and use it in GitHub Desktop.
Save jikuja/22f07f21e66983a79de4a5cfa05238d8 to your computer and use it in GitHub Desktop.
from __future__ import unicode_literals
import logging
import traceback
from prompt_toolkit.application import Application
from prompt_toolkit.buffer import Buffer, AcceptAction
from prompt_toolkit.interface import CommandLineInterface
from prompt_toolkit.key_binding.defaults import load_key_bindings
from prompt_toolkit.keys import Keys
from prompt_toolkit.layout.containers import HSplit, Window
from prompt_toolkit.layout.controls import BufferControl, FillControl, TokenListControl
from prompt_toolkit.layout.dimension import LayoutDimension as D
from prompt_toolkit.shortcuts import create_eventloop
from prompt_toolkit.token import Token
logging.basicConfig(filename='example.log', level=logging.DEBUG)
logging.info("Starting")
PROMPT = "PROMPT"
OUTPUT = "OUTPUT"
def get_titlebar_tokens(cli):
return [
(Token.Title, ' Hello world '),
(Token.Title, ' (Press [Ctrl-Q] to quit.)'),
]
layout = HSplit([
# The titlebar.
Window(height=D.exact(1),
content=TokenListControl(get_titlebar_tokens, align_center=True)),
# fill line
Window(height=D.exact(1), content=FillControl('-', token=Token.Line)),
# content
Window(content=BufferControl(buffer_name=OUTPUT)),
# fill line
Window(height=D.exact(1), content=FillControl('-', token=Token.Line)),
# prompt
Window(height=D.exact(1), content=BufferControl(buffer_name=PROMPT))
])
registry = load_key_bindings()
@registry.add_binding(Keys.ControlC, eager=True)
@registry.add_binding(Keys.ControlQ, eager=True)
def _(event):
event.cli.set_return_value(None)
def _handler(cli, bfr):
# save line
text = bfr.text
logging.debug("Got: %s", text)
# reset line
cli.buffers[PROMPT].reset(append_to_history=True)
# append text to output window
cli.buffers[OUTPUT].insert_line_below()
cli.buffers[OUTPUT].insert_text(text)
# TODO: limit backlog
buffers = {
PROMPT: Buffer(
is_multiline=False,
accept_action=AcceptAction(handler=_handler)),
OUTPUT: Buffer(is_multiline=True),
}
application = Application(
layout=layout,
buffers=buffers,
key_bindings_registry=registry,
use_alternate_screen=True,
initial_focussed_buffer=PROMPT)
def run():
eventloop = create_eventloop()
try:
cli = CommandLineInterface(application=application, eventloop=eventloop)
cli.buffers[OUTPUT].text = "foo"
cli.run()
except Exception:
logging.exception("failed")
traceback.print_stack()
finally:
eventloop.close()
if __name__ == '__main__':
run()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment