Beispiel #1
0
    def __init__(self,
                 editing_mode=EditingMode.EMACS,
                 history=None,
                 lexer=None,
                 style=None,
                 completer=None,
                 extra_key_bindings=None,
                 tempfile_suffix=None,
                 input=None,
                 output=None,
                 on_render=None):

        self.editing_mode = editing_mode
        self.history = history
        self.lexer = lexer
        self.style = None
        self.completer = completer
        self.extra_key_bindings = extra_key_bindings
        self.tempfile_suffix = tempfile_suffix
        if not is_windows():
            self.input = input or CustomVt100Input(sys.stdin)
        else:
            self.input = input or get_default_input()
        self.output = output or get_default_output()

        self.on_render = on_render

        self.create_layout()
        self.create_application()
def print_container(container, file=None):
    """
    Print any layout to the output in a non-interactive way.

    Example usage::

        from prompt_toolkit.widgets import Frame, TextArea
        print_container(
            Frame(TextArea(text='Hello world!')))
    """
    if file:
        output = create_output(stdout=file)
    else:
        output = get_default_output()

    def exit_immediately():
        # Use `call_from_executor` to exit "soon", so that we still render one
        # initial time, before exiting the application.
        get_event_loop().call_from_executor(
             lambda: app.exit())

    app = Application(
        layout=Layout(container=container),
        output=output,
        input=DummyInput())
    app.run(pre_run=exit_immediately)
Beispiel #3
0
def set_title(text):
    """
    Set the terminal title.
    """
    assert isinstance(text, six.text_type)

    output = get_default_output()
    output.set_title(text)
Beispiel #4
0
def clear():
    """
    Clear the screen.
    """
    out = get_default_output()
    out.erase_screen()
    out.cursor_goto(0, 0)
    out.flush()
def set_title(text):
    """
    Set the terminal title.
    """
    assert isinstance(text, six.text_type)

    output = get_default_output()
    output.set_title(text)
def clear():
    """
    Clear the screen.
    """
    out = get_default_output()
    out.erase_screen()
    out.cursor_goto(0, 0)
    out.flush()
Beispiel #7
0
def _screen_size() -> Size:
    ''' Return the screen size '''
    if PTK_VERSION == 2:
        output: Output = get_default_output()
    else:
        output: Output = create_output()

    return output.from_pty(sys.stdout).get_size()
Beispiel #8
0
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')])
    output = get_default_output()
    app = Application(layout=layout,
                      style=style_from_pygments_cls(CrateStyle),
                      key_bindings=merge_key_bindings(
                          [key_bindings,
                           load_open_in_editor_bindings()]),
                      editing_mode=_get_editing_mode(),
                      output=output)
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: '******'Bye!')
            return
Beispiel #9
0
def print_container(container, file=None):
    """
    Print any layout to the output in a non-interactive way.

    Example usage::

        from prompt_toolkit.widgets import Frame, TextArea
        print_container(
            Frame(TextArea(text='Hello world!')))
    """
    if file:
        output = create_output(stdout=file)
    else:
        output = get_default_output()

    def exit_immediately():
        # Use `call_from_executor` to exit "soon", so that we still render one
        # initial time, before exiting the application.
        get_event_loop().call_from_executor(lambda: app.exit())

    app = Application(layout=Layout(container=container), output=output)
    app.run(pre_run=exit_immediately)
Beispiel #10
0
def print_formatted_text(*values, **kwargs):
    """
    ::

        print_formatted_text(*values, sep=' ', end='\\n', file=None, flush=False, style=None, output=None)

    Print text to stdout. This is supposed to be compatible with Python's print
    function, but supports printing of formatted text. You can pass a
    :class:`~prompt_toolkit.formatted_text.FormattedText`,
    :class:`~prompt_toolkit.formatted_text.HTML` or
    :class:`~prompt_toolkit.formatted_text.ANSI` object to print formatted
    text.

    * Print HTML as follows::

        print_formatted_text(HTML('<i>Some italic text</i> <ansired>This is red!</ansired>'))

        style = Style.from_dict({
            'hello': '#ff0066',
            'world': '#884444 italic',
        })
        print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style)

    * Print a list of (style_str, text) tuples in the given style to the
      output.  E.g.::

        style = Style.from_dict({
            'hello': '#ff0066',
            'world': '#884444 italic',
        })
        fragments = FormattedText([
            ('class:hello', 'Hello'),
            ('class:world', 'World'),
        ])
        print_formatted_text(fragments, style=style)

    If you want to print a list of Pygments tokens, wrap it in
    :class:`~prompt_toolkit.formatted_text.PygmentsTokens` to do the
    conversion.

    :param values: Any kind of printable object, or formatted string.
    :param sep: String inserted between values, default a space.
    :param end: String appended after the last value, default a newline.
    :param style: :class:`.Style` instance for the color scheme.
    :param include_default_pygments_style: `bool`. Include the default Pygments
        style when set to `True` (the default).
    """
    # Pop kwargs (Python 2 compatibility).
    sep = kwargs.pop('sep', ' ')
    end = kwargs.pop('end', '\n')
    file = kwargs.pop('file', None)
    flush = kwargs.pop('flush', False)
    style = kwargs.pop('style', None)
    output = kwargs.pop('output', None)
    color_depth = kwargs.pop('color_depth', None)
    include_default_pygments_style = kwargs.pop(
        'include_default_pygments_style', True)
    assert not kwargs
    assert not (output and file)
    assert style is None or isinstance(style, BaseStyle)

    # Build/merge style.
    styles = [default_ui_style()]
    if include_default_pygments_style:
        styles.append(default_pygments_style())
    if style:
        styles.append(style)

    merged_style = merge_styles(styles)

    # Create Output object.
    if output is None:
        if file:
            output = create_output(stdout=file)
        else:
            output = get_default_output()

    assert isinstance(output, Output)

    # Get color depth.
    color_depth = color_depth or ColorDepth.default()

    # Merges values.
    def to_text(val):
        if isinstance(val, list):
            return to_formatted_text('{0}'.format(val))
        return to_formatted_text(val, auto_convert=True)

    fragments = []
    for i, value in enumerate(values):
        fragments.extend(to_text(value))

        if sep and i != len(values) - 1:
            fragments.extend(to_text(sep))

    fragments.extend(to_text(end))

    # Print output.
    renderer_print_formatted_text(output,
                                  fragments,
                                  merged_style,
                                  color_depth=color_depth)

    # Flush the output stream.
    if flush:
        output.flush()
    def __init__(self, layout=None,
                 style=None,
                 include_default_pygments_style=True,
                 style_transformation=None,
                 key_bindings=None, clipboard=None,
                 full_screen=False, color_depth=None,
                 mouse_support=False,

                 enable_page_navigation_bindings=None,  # Can be None, True or False.

                 paste_mode=False,
                 editing_mode=EditingMode.EMACS,
                 erase_when_done=False,
                 reverse_vi_search_direction=False,
                 min_redraw_interval=None,
                 max_render_postpone_time=0,

                 on_reset=None, on_invalidate=None,
                 before_render=None, after_render=None,

                 # I/O.
                 input=None, output=None):

        # If `enable_page_navigation_bindings` is not specified, enable it in
        # case of full screen applications only. This can be overridden by the user.
        if enable_page_navigation_bindings is None:
            enable_page_navigation_bindings = Condition(lambda: self.full_screen)

        paste_mode = to_filter(paste_mode)
        mouse_support = to_filter(mouse_support)
        reverse_vi_search_direction = to_filter(reverse_vi_search_direction)
        enable_page_navigation_bindings = to_filter(enable_page_navigation_bindings)
        include_default_pygments_style = to_filter(include_default_pygments_style)

        assert layout is None or isinstance(layout, Layout), 'Got layout: %r' % (layout, )
        assert key_bindings is None or isinstance(key_bindings, KeyBindingsBase)
        assert clipboard is None or isinstance(clipboard, Clipboard)
        assert isinstance(full_screen, bool)
        assert (color_depth is None or callable(color_depth) or
                color_depth in ColorDepth._ALL), 'Got color_depth: %r' % (color_depth, )
        assert isinstance(editing_mode, six.string_types)
        assert style is None or isinstance(style, BaseStyle)
        assert style_transformation is None or isinstance(style_transformation, StyleTransformation)
        assert isinstance(erase_when_done, bool)
        assert min_redraw_interval is None or isinstance(min_redraw_interval, (float, int))
        assert max_render_postpone_time is None or isinstance(max_render_postpone_time, (float, int))

        assert on_reset is None or callable(on_reset)
        assert on_invalidate is None or callable(on_invalidate)
        assert before_render is None or callable(before_render)
        assert after_render is None or callable(after_render)

        assert output is None or isinstance(output, Output)
        assert input is None or isinstance(input, Input)

        if layout is None:
            layout = create_dummy_layout()

        if style_transformation is None:
            style_transformation = DummyStyleTransformation()

        self.style = style
        self.style_transformation = style_transformation

        # Key bindings.
        self.key_bindings = key_bindings
        self._default_bindings = load_key_bindings()
        self._page_navigation_bindings = load_page_navigation_bindings()

        self.layout = layout
        self.clipboard = clipboard or InMemoryClipboard()
        self.full_screen = full_screen
        self._color_depth = color_depth
        self.mouse_support = mouse_support

        self.paste_mode = paste_mode
        self.editing_mode = editing_mode
        self.erase_when_done = erase_when_done
        self.reverse_vi_search_direction = reverse_vi_search_direction
        self.enable_page_navigation_bindings = enable_page_navigation_bindings
        self.min_redraw_interval = min_redraw_interval
        self.max_render_postpone_time = max_render_postpone_time

        # Events.
        self.on_invalidate = Event(self, on_invalidate)
        self.on_reset = Event(self, on_reset)
        self.before_render = Event(self, before_render)
        self.after_render = Event(self, after_render)

        # I/O.
        self.output = output or get_default_output()
        self.input = input or get_default_input()

        # List of 'extra' functions to execute before a Application.run.
        self.pre_run_callables = []

        self._is_running = False
        self.future = None

        #: Quoted insert. This flag is set if we go into quoted insert mode.
        self.quoted_insert = False

        #: Vi state. (For Vi key bindings.)
        self.vi_state = ViState()
        self.emacs_state = EmacsState()

        #: When to flush the input (For flushing escape keys.) This is important
        #: on terminals that use vt100 input. We can't distinguish the escape
        #: key from for instance the left-arrow key, if we don't know what follows
        #: after "\x1b". This little timer will consider "\x1b" to be escape if
        #: nothing did follow in this time span.
        #: This seems to work like the `ttimeoutlen` option in Vim.
        self.ttimeoutlen = .5  # Seconds.

        #: Like Vim's `timeoutlen` option. This can be `None` or a float.  For
        #: instance, suppose that we have a key binding AB and a second key
        #: binding A. If the uses presses A and then waits, we don't handle
        #: this binding yet (unless it was marked 'eager'), because we don't
        #: know what will follow. This timeout is the maximum amount of time
        #: that we wait until we call the handlers anyway. Pass `None` to
        #: disable this timeout.
        self.timeoutlen = 1.0

        #: The `Renderer` instance.
        # Make sure that the same stdout is used, when a custom renderer has been passed.
        self._merged_style = self._create_merged_style(include_default_pygments_style)

        self.renderer = Renderer(
            self._merged_style,
            self.output,
            self.input,
            full_screen=full_screen,
            mouse_support=mouse_support,
            cpr_not_supported_callback=self.cpr_not_supported_callback)

        #: Render counter. This one is increased every time the UI is rendered.
        #: It can be used as a key for caching certain information during one
        #: rendering.
        self.render_counter = 0

        # Invalidate flag. When 'True', a repaint has been scheduled.
        self._invalidated = False
        self._invalidate_events = []  # Collection of 'invalidate' Event objects.
        self._last_redraw_time = 0  # Unix timestamp of last redraw. Used when
                                    # `min_redraw_interval` is given.

        #: The `InputProcessor` instance.
        self.key_processor = KeyProcessor(_CombinedRegistry(self))

        # If `run_in_terminal` was called. This will point to a `Future` what will be
        # set at the point when the previous run finishes.
        self._running_in_terminal = False
        self._running_in_terminal_f = None

        # Trigger initialize callback.
        self.reset()
Beispiel #12
0
    def __init__(self,
                 message='',
                 default='',
                 multiline=False,
                 wrap_lines=True,
                 is_password=False,
                 vi_mode=False,
                 editing_mode=EditingMode.EMACS,
                 complete_while_typing=True,
                 validate_while_typing=True,
                 enable_history_search=False,
                 lexer=None,
                 enable_system_prompt=False,
                 enable_suspend=False,
                 enable_open_in_editor=False,
                 validator=None,
                 completer=None,
                 reserve_space_for_menu=8,
                 complete_style=None,
                 auto_suggest=None,
                 style=None,
                 history=None,
                 clipboard=None,
                 prompt_continuation=None,
                 rprompt=None,
                 bottom_toolbar=None,
                 mouse_support=False,
                 extra_input_processor=None,
                 extra_key_bindings=None,
                 erase_when_done=False,
                 tempfile_suffix='.txt',
                 refresh_interval=0,
                 input=None,
                 output=None):
        assert style is None or isinstance(style, BaseStyle)
        assert extra_input_processor is None or isinstance(
            extra_input_processor, Processor)
        assert extra_key_bindings is None or isinstance(
            extra_key_bindings, KeyBindingsBase)

        # Defaults.
        output = output or get_default_output()
        input = input or get_default_input()
        extra_input_processor = extra_input_processor

        history = history or InMemoryHistory()
        clipboard = clipboard or InMemoryClipboard()

        # Ensure backwards-compatibility, when `vi_mode` is passed.
        if vi_mode:
            editing_mode = EditingMode.VI

        # Store all settings in this class.
        self.input = input
        self.output = output

        # Store all settings in this class.
        for name in self._fields:
            if name not in ('editing_mode', ):
                value = locals()[name]
                setattr(self, name, value)

        self.app, self._default_buffer, self._default_buffer_control = \
            self._create_application(editing_mode, erase_when_done)
def print_formatted_text(*values, **kwargs):
    """
    ::

        print_formatted_text(*values, sep=' ', end='\\n', file=None, flush=False, style=None, output=None)

    Print text to stdout. This is supposed to be compatible with Python's print
    function, but supports printing of formatted text. You can pass a
    :class:`~prompt_toolkit.formatted_text.FormattedText`,
    :class:`~prompt_toolkit.formatted_text.HTML` or
    :class:`~prompt_toolkit.formatted_text.ANSI` object to print formatted
    text.

    * Print HTML as follows::

        print_formatted_text(HTML('<i>Some italic text</i> <ansired>This is red!</ansired>'))

        style = Style.from_dict({
            'hello': '#ff0066',
            'world': '#884444 italic',
        })
        print_formatted_text(HTML('<hello>Hello</hello> <world>world</world>!'), style=style)

    * Print a list of (style_str, text) tuples in the given style to the
      output.  E.g.::

        style = Style.from_dict({
            'hello': '#ff0066',
            'world': '#884444 italic',
        })
        fragments = FormattedText([
            ('class:hello', 'Hello'),
            ('class:world', 'World'),
        ])
        print_formatted_text(fragments, style=style)

    If you want to print a list of Pygments tokens, wrap it in
    :class:`~prompt_toolkit.formatted_text.PygmentsTokens` to do the
    conversion.

    :param values: Any kind of printable object, or formatted string.
    :param sep: String inserted between values, default a space.
    :param end: String appended after the last value, default a newline.
    :param style: :class:`.Style` instance for the color scheme.
    :param include_default_pygments_style: `bool`. Include the default Pygments
        style when set to `True` (the default).
    """
    # Pop kwargs (Python 2 compatibility).
    sep = kwargs.pop('sep', ' ')
    end = kwargs.pop('end', '\n')
    file = kwargs.pop('file', None)
    flush = kwargs.pop('flush', False)
    style = kwargs.pop('style', None)
    output = kwargs.pop('output', None)
    color_depth = kwargs.pop('color_depth', None)
    style_transformation = kwargs.pop('style_transformation', None)
    include_default_pygments_style = kwargs.pop('include_default_pygments_style', True)
    assert not kwargs
    assert not (output and file)
    assert style is None or isinstance(style, BaseStyle)

    # Build/merge style.
    styles = [default_ui_style()]
    if include_default_pygments_style:
        styles.append(default_pygments_style())
    if style:
        styles.append(style)

    merged_style = merge_styles(styles)

    # Create Output object.
    if output is None:
        if file:
            output = create_output(stdout=file)
        else:
            output = get_default_output()

    assert isinstance(output, Output)

    # Get color depth.
    color_depth = color_depth or ColorDepth.default()

    # Merges values.
    def to_text(val):
        # Normal lists which are not instances of `FormattedText` are
        # considered plain text.
        if isinstance(val, list) and not isinstance(val, FormattedText):
            return to_formatted_text('{0}'.format(val))
        return to_formatted_text(val, auto_convert=True)

    fragments = []
    for i, value in enumerate(values):
        fragments.extend(to_text(value))

        if sep and i != len(values) - 1:
            fragments.extend(to_text(sep))

    fragments.extend(to_text(end))

    # Print output.
    renderer_print_formatted_text(
        output, fragments, merged_style, color_depth=color_depth,
        style_transformation=style_transformation)

    # Flush the output stream.
    if flush:
        output.flush()
Beispiel #14
0
    def __init__(
            self,
            layout=None,
            style=None,
            key_bindings=None,
            clipboard=None,
            full_screen=False,
            mouse_support=False,
            enable_page_navigation_bindings=False,
            paste_mode=False,
            editing_mode=EditingMode.EMACS,
            erase_when_done=False,
            reverse_vi_search_direction=False,
            min_redraw_interval=None,
            max_render_postpone_time=0,
            on_reset=None,
            on_render=None,
            on_invalidate=None,

            # I/O.
            input=None,
            output=None):

        paste_mode = to_filter(paste_mode)
        mouse_support = to_filter(mouse_support)
        reverse_vi_search_direction = to_filter(reverse_vi_search_direction)
        enable_page_navigation_bindings = to_filter(
            enable_page_navigation_bindings)

        assert layout is None or isinstance(layout, Layout)
        assert key_bindings is None or isinstance(key_bindings,
                                                  KeyBindingsBase)
        assert clipboard is None or isinstance(clipboard, Clipboard)
        assert isinstance(full_screen, bool)
        assert isinstance(editing_mode, six.string_types)
        assert style is None or isinstance(style, BaseStyle)
        assert isinstance(erase_when_done, bool)
        assert min_redraw_interval is None or isinstance(
            min_redraw_interval, (float, int))
        assert max_render_postpone_time is None or isinstance(
            max_render_postpone_time, (float, int))

        assert on_reset is None or callable(on_reset)
        assert on_render is None or callable(on_render)
        assert on_invalidate is None or callable(on_invalidate)

        assert output is None or isinstance(output, Output)
        assert input is None or isinstance(input, Input)

        self.style = style

        if layout is None:
            layout = create_dummy_layout()

        # Key bindings.
        self.key_bindings = key_bindings
        self._default_bindings = load_key_bindings()
        self._page_navigation_bindings = load_page_navigation_bindings()

        self.layout = layout
        self.clipboard = clipboard or InMemoryClipboard()
        self.full_screen = full_screen
        self.mouse_support = mouse_support

        self.paste_mode = paste_mode
        self.editing_mode = editing_mode
        self.erase_when_done = erase_when_done
        self.reverse_vi_search_direction = reverse_vi_search_direction
        self.enable_page_navigation_bindings = enable_page_navigation_bindings
        self.min_redraw_interval = min_redraw_interval
        self.max_render_postpone_time = max_render_postpone_time

        # Events.
        self.on_invalidate = Event(self, on_invalidate)
        self.on_render = Event(self, on_render)
        self.on_reset = Event(self, on_reset)

        # I/O.
        self.output = output or get_default_output()
        self.input = input or get_default_input()

        # List of 'extra' functions to execute before a Application.run.
        self.pre_run_callables = []

        self._is_running = False
        self.future = None

        #: Quoted insert. This flag is set if we go into quoted insert mode.
        self.quoted_insert = False

        #: Vi state. (For Vi key bindings.)
        self.vi_state = ViState()

        #: When to flush the input (For flushing escape keys.) This is important
        #: on terminals that use vt100 input. We can't distinguish the escape
        #: key from for instance the left-arrow key, if we don't know what follows
        #: after "\x1b". This little timer will consider "\x1b" to be escape if
        #: nothing did follow in this time span.
        #: This seems to work like the `ttimeoutlen` option in Vim.
        self.input_timeout = .5

        #: The `Renderer` instance.
        # Make sure that the same stdout is used, when a custom renderer has been passed.
        self._merged_style = merge_styles([
            default_style(),
            DynamicStyle(lambda: self.style),
        ])

        self.renderer = Renderer(
            self._merged_style,
            self.output,
            full_screen=full_screen,
            mouse_support=mouse_support,
            cpr_not_supported_callback=self.cpr_not_supported_callback)

        #: Render counter. This one is increased every time the UI is rendered.
        #: It can be used as a key for caching certain information during one
        #: rendering.
        self.render_counter = 0

        # Invalidate flag. When 'True', a repaint has been scheduled.
        self._invalidated = False
        self._invalidate_events = [
        ]  # Collection of 'invalidate' Event objects.
        self._last_redraw_time = 0  # Unix timestamp of last redraw. Used when
        # `min_redraw_interval` is given.

        #: The `InputProcessor` instance.
        self.key_processor = KeyProcessor(_CombinedRegistry(self))

        # If `run_in_terminal` was called. This will point to a `Future` what will be
        # set at the point whene the previous run finishes.
        self._running_in_terminal = False
        self._running_in_terminal_f = None

        # Trigger initialize callback.
        self.reset()
    def __init__(self, layout=None,
                 style=None, include_default_pygments_style=True,
                 key_bindings=None, clipboard=None,
                 full_screen=False, color_depth=None,
                 mouse_support=False,

                 enable_page_navigation_bindings=None,  # Can be None, True or False.

                 paste_mode=False,
                 editing_mode=EditingMode.EMACS,
                 erase_when_done=False,
                 reverse_vi_search_direction=False,
                 min_redraw_interval=None,
                 max_render_postpone_time=0,

                 on_reset=None, on_invalidate=None,
                 before_render=None, after_render=None,

                 # I/O.
                 input=None, output=None):

        # If `enable_page_navigation_bindings` is not specified, enable it in
        # case of full screen applications only. This can be overridden by the user.
        if enable_page_navigation_bindings is None:
            enable_page_navigation_bindings = Condition(lambda: self.full_screen)

        paste_mode = to_filter(paste_mode)
        mouse_support = to_filter(mouse_support)
        reverse_vi_search_direction = to_filter(reverse_vi_search_direction)
        enable_page_navigation_bindings = to_filter(enable_page_navigation_bindings)
        include_default_pygments_style = to_filter(include_default_pygments_style)

        assert layout is None or isinstance(layout, Layout), 'Got layout: %r' % (layout, )
        assert key_bindings is None or isinstance(key_bindings, KeyBindingsBase)
        assert clipboard is None or isinstance(clipboard, Clipboard)
        assert isinstance(full_screen, bool)
        assert (color_depth is None or callable(color_depth) or
                color_depth in ColorDepth._ALL), 'Got color_depth: %r' % (color_depth, )
        assert isinstance(editing_mode, six.string_types)
        assert style is None or isinstance(style, BaseStyle)
        assert isinstance(erase_when_done, bool)
        assert min_redraw_interval is None or isinstance(min_redraw_interval, (float, int))
        assert max_render_postpone_time is None or isinstance(max_render_postpone_time, (float, int))

        assert on_reset is None or callable(on_reset)
        assert on_invalidate is None or callable(on_invalidate)
        assert before_render is None or callable(before_render)
        assert after_render is None or callable(after_render)

        assert output is None or isinstance(output, Output)
        assert input is None or isinstance(input, Input)

        self.style = style

        if layout is None:
            layout = create_dummy_layout()

        # Key bindings.
        self.key_bindings = key_bindings
        self._default_bindings = load_key_bindings()
        self._page_navigation_bindings = load_page_navigation_bindings()

        self.layout = layout
        self.clipboard = clipboard or InMemoryClipboard()
        self.full_screen = full_screen
        self._color_depth = color_depth
        self.mouse_support = mouse_support

        self.paste_mode = paste_mode
        self.editing_mode = editing_mode
        self.erase_when_done = erase_when_done
        self.reverse_vi_search_direction = reverse_vi_search_direction
        self.enable_page_navigation_bindings = enable_page_navigation_bindings
        self.min_redraw_interval = min_redraw_interval
        self.max_render_postpone_time = max_render_postpone_time

        # Events.
        self.on_invalidate = Event(self, on_invalidate)
        self.on_reset = Event(self, on_reset)
        self.before_render = Event(self, before_render)
        self.after_render = Event(self, after_render)

        # I/O.
        self.output = output or get_default_output()
        self.input = input or get_default_input()

        # List of 'extra' functions to execute before a Application.run.
        self.pre_run_callables = []

        self._is_running = False
        self.future = None

        #: Quoted insert. This flag is set if we go into quoted insert mode.
        self.quoted_insert = False

        #: Vi state. (For Vi key bindings.)
        self.vi_state = ViState()
        self.emacs_state = EmacsState()

        #: When to flush the input (For flushing escape keys.) This is important
        #: on terminals that use vt100 input. We can't distinguish the escape
        #: key from for instance the left-arrow key, if we don't know what follows
        #: after "\x1b". This little timer will consider "\x1b" to be escape if
        #: nothing did follow in this time span.
        #: This seems to work like the `ttimeoutlen` option in Vim.
        self.ttimeoutlen = .5  # Seconds.

        #: Like Vim's `timeoutlen` option. This can be `None` or a float.  For
        #: instance, suppose that we have a key binding AB and a second key
        #: binding A. If the uses presses A and then waits, we don't handle
        #: this binding yet (unless it was marked 'eager'), because we don't
        #: know what will follow. This timeout is the maximum amount of time
        #: that we wait until we call the handlers anyway. Pass `None` to
        #: disable this timeout.
        self.timeoutlen = 1.0

        #: The `Renderer` instance.
        # Make sure that the same stdout is used, when a custom renderer has been passed.
        self._merged_style = self._create_merged_style(include_default_pygments_style)

        self.renderer = Renderer(
            self._merged_style,
            self.output,
            full_screen=full_screen,
            mouse_support=mouse_support,
            cpr_not_supported_callback=self.cpr_not_supported_callback)

        #: Render counter. This one is increased every time the UI is rendered.
        #: It can be used as a key for caching certain information during one
        #: rendering.
        self.render_counter = 0

        # Invalidate flag. When 'True', a repaint has been scheduled.
        self._invalidated = False
        self._invalidate_events = []  # Collection of 'invalidate' Event objects.
        self._last_redraw_time = 0  # Unix timestamp of last redraw. Used when
                                    # `min_redraw_interval` is given.

        #: The `InputProcessor` instance.
        self.key_processor = KeyProcessor(_CombinedRegistry(self))

        # If `run_in_terminal` was called. This will point to a `Future` what will be
        # set at the point when the previous run finishes.
        self._running_in_terminal = False
        self._running_in_terminal_f = None

        # Trigger initialize callback.
        self.reset()
Beispiel #16
0
    def __init__(self,
                 message='',
                 default='',
                 multiline=False,
                 wrap_lines=True,
                 is_password=False,
                 vi_mode=False,
                 editing_mode=EditingMode.EMACS,
                 complete_while_typing=True,
                 validate_while_typing=True,
                 enable_history_search=False,
                 search_ignore_case=False,
                 lexer=None,
                 enable_system_prompt=False,
                 enable_suspend=False,
                 enable_open_in_editor=False,
                 validator=None,
                 completer=None,
                 complete_in_thread=False,
                 reserve_space_for_menu=8,
                 complete_style=None,
                 auto_suggest=None,
                 style=None,
                 style_transformation=None,
                 swap_light_and_dark_colors=False,
                 color_depth=None,
                 include_default_pygments_style=True,
                 history=None,
                 clipboard=None,
                 prompt_continuation=None,
                 rprompt=None,
                 bottom_toolbar=None,
                 mouse_support=False,
                 input_processors=None,
                 key_bindings=None,
                 erase_when_done=False,
                 tempfile_suffix='.txt',
                 inputhook=None,
                 refresh_interval=0,
                 input=None,
                 output=None):
        assert style is None or isinstance(style, BaseStyle)
        assert style_transformation is None or isinstance(
            style, StyleTransformation)
        assert input_processors is None or isinstance(input_processors, list)
        assert key_bindings is None or isinstance(key_bindings,
                                                  KeyBindingsBase)

        # Defaults.
        output = output or get_default_output()
        input = input or get_default_input()

        history = history or InMemoryHistory()
        clipboard = clipboard or InMemoryClipboard()

        # Ensure backwards-compatibility, when `vi_mode` is passed.
        if vi_mode:
            editing_mode = EditingMode.VI

        # Store all settings in this class.
        self.input = input
        self.output = output

        # Store all settings in this class.
        for name in self._fields:
            if name not in ('editing_mode', ):
                value = locals()[name]
                setattr(self, name, value)

        # Create buffers, layout and Application.
        self.history = history
        self.default_buffer = self._create_default_buffer()
        self.search_buffer = self._create_search_buffer()
        self.layout = self._create_layout()
        self.app = self._create_application(editing_mode, erase_when_done)
    def __init__(
            self,
            message='',
            multiline=False,
            wrap_lines=True,
            is_password=False,
            vi_mode=False,
            editing_mode=EditingMode.EMACS,
            complete_while_typing=True,
            validate_while_typing=True,
            enable_history_search=False,
            search_ignore_case=False,
            lexer=None,
            enable_system_prompt=False,
            enable_suspend=False,
            enable_open_in_editor=False,
            validator=None,
            completer=None,
            complete_in_thread=False,
            reserve_space_for_menu=8,
            complete_style=None,
            auto_suggest=None,
            style=None,
            style_transformation=None,
            swap_light_and_dark_colors=False,
            color_depth=None,
            include_default_pygments_style=True,
            history=None,
            clipboard=None,
            prompt_continuation=None,
            rprompt=None,
            bottom_toolbar=None,
            mouse_support=False,
            input_processors=None,
            key_bindings=None,
            erase_when_done=False,
            tempfile_suffix='.txt',
            inputhook=None,

            refresh_interval=0,
            input=None,
            output=None):
        assert style is None or isinstance(style, BaseStyle)
        assert style_transformation is None or isinstance(style_transformation, StyleTransformation)
        assert input_processors is None or isinstance(input_processors, list)
        assert key_bindings is None or isinstance(key_bindings, KeyBindingsBase)

        # Defaults.
        output = output or get_default_output()
        input = input or get_default_input()

        history = history or InMemoryHistory()
        clipboard = clipboard or InMemoryClipboard()

        # Ensure backwards-compatibility, when `vi_mode` is passed.
        if vi_mode:
            editing_mode = EditingMode.VI

        # Store all settings in this class.
        self.input = input
        self.output = output

        # Store all settings in this class.
        for name in self._fields:
            if name not in ('editing_mode', ):
                value = locals()[name]
                setattr(self, name, value)

        # Create buffers, layout and Application.
        self.history = history
        self.default_buffer = self._create_default_buffer()
        self.search_buffer = self._create_search_buffer()
        self.layout = self._create_layout()
        self.app = self._create_application(editing_mode, erase_when_done)