コード例 #1
0
    def __init__(self, title=None, formatters=None, bottom_toolbar=None,
                 style=None, key_bindings=None, file=None, color_depth=None,
                 output=None, input=None):
        assert formatters is None or (
            isinstance(formatters, list) and all(isinstance(fo, Formatter) for fo in formatters))
        assert style is None or isinstance(style, BaseStyle)
        assert key_bindings is None or isinstance(key_bindings, KeyBindings)

        self.title = title
        self.formatters = formatters or create_default_formatters()
        self.bottom_toolbar = bottom_toolbar
        self.counters = []
        self.style = style
        self.key_bindings = key_bindings

        # Note that we use __stderr__ as default error output, because that
        # works best with `patch_stdout`.
        self.color_depth = color_depth
        self.output = output or create_output(stdout=file or sys.__stderr__)
        self.input = input or get_default_input()

        self._thread = None

        self._loop = get_event_loop()
        self._previous_winch_handler = None
        self._has_sigwinch = False
コード例 #2
0
def print_container(
    container: "AnyContainer",
    file: Optional[TextIO] = None,
    style: Optional[BaseStyle] = None,
    include_default_pygments_style: bool = True,
) -> 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_app_session().output

    app: Application[None] = Application(
        layout=Layout(container=container),
        output=output,
        # `DummyInput` will cause the application to terminate immediately.
        input=DummyInput(),
        style=_create_merged_style(
            style,
            include_default_pygments_style=include_default_pygments_style),
    )
    try:
        app.run(in_thread=True)
    except EOFError:
        pass
コード例 #3
0
def print_container(container: 'Container', file: Optional[TextIO] = None) -> 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_app_session().output

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

    app: Application[None] = Application(
        layout=Layout(container=container),
        output=output,
        input=DummyInput())
    app.run(pre_run=exit_immediately)
コード例 #4
0
def print_container(
    container: "AnyContainer",
    file: Optional[TextIO] = None,
    style: Optional[BaseStyle] = None,
    include_default_pygments_style: bool = True,
) -> 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_app_session().output

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

    app: Application[None] = Application(
        layout=Layout(container=container),
        output=output,
        input=DummyInput(),
        style=_create_merged_style(
            style,
            include_default_pygments_style=include_default_pygments_style),
    )
    app.run(pre_run=exit_immediately, in_thread=True)
コード例 #5
0
ファイル: base.py プロジェクト: LonelySamurai/SDP-Math
    def __init__(self,
                 title=None,
                 formatters=None,
                 bottom_toolbar=None,
                 style=None,
                 key_bindings=None,
                 file=None,
                 color_depth=None,
                 output=None,
                 input=None):
        assert formatters is None or (isinstance(formatters, list) and all(
            isinstance(fo, Formatter) for fo in formatters))
        assert style is None or isinstance(style, BaseStyle)
        assert key_bindings is None or isinstance(key_bindings, KeyBindings)

        self.title = title
        self.formatters = formatters or create_default_formatters()
        self.bottom_toolbar = bottom_toolbar
        self.counters = []
        self.style = style
        self.key_bindings = key_bindings

        # Note that we use __stderr__ as default error output, because that
        # works best with `patch_stdout`.
        self.color_depth = color_depth
        self.output = output or create_output(stdout=file or sys.__stderr__)
        self.input = input or get_default_input()

        self._thread = None

        self._loop = get_event_loop()
        self._previous_winch_handler = None
        self._has_sigwinch = False
コード例 #6
0
ファイル: base.py プロジェクト: Arrendi/rice
    def __init__(self,
                 title=None,
                 formatters=None,
                 bottom_toolbar=None,
                 style=None,
                 key_bindings=None,
                 file=None,
                 output=None,
                 input=None):
        assert formatters is None or (isinstance(formatters, list) and all(
            isinstance(fo, f.Formatter) for fo in formatters))
        assert style is None or isinstance(style, BaseStyle)
        assert key_bindings is None or isinstance(key_bindings, KeyBindings)

        self.title = title
        self.formatters = formatters or create_default_formatters()
        self.bottom_toolbar = bottom_toolbar
        self.counters = []
        self.style = style
        self.key_bindings = key_bindings

        self.output = output or create_output(stdout=file or sys.stderr)
        self.input = input or get_default_input()

        self._thread = None

        self._loop = get_event_loop()
        self._previous_winch_handler = None
        self._has_sigwinch = False
コード例 #7
0
ファイル: bib_manager.py プロジェクト: pcubillos/bibmanager
def display_bibs(labels, bibs, meta=False):
    r"""
    Display a list of bib entries on screen with flying colors.

    Parameters
    ----------
    labels: List of Strings
        Header labels to show above each Bib() entry.
    bibs: List of Bib() objects
        BibTeX entries to display.
    meta: Bool
        If True, also display the meta-information.

    Examples
    --------
    >>> import bibmanager.bib_manager as bm
    >>> e1 = '''@Misc{JonesEtal2001scipy,
           author = {Eric Jones and Travis Oliphant and Pearu Peterson},
           title  = {{SciPy}: Open source scientific tools for {Python}},
           year   = {2001},
         }'''
    >>> e2 = '''@Misc{Jones2001,
           author = {Eric Jones and Travis Oliphant and Pearu Peterson},
           title  = {SciPy: Open source scientific tools for Python},
           year   = {2001},
         }'''
    >>> bibs = [bm.Bib(e1), bm.Bib(e2)]
    >>> bm.display_bibs(["DATABASE:\n", "NEW:\n"], bibs)
    ::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::::
    DATABASE:
    @Misc{JonesEtal2001scipy,
           author = {Eric Jones and Travis Oliphant and Pearu Peterson},
           title  = {{SciPy}: Open source scientific tools for {Python}},
           year   = {2001},
         }

    NEW:
    @Misc{Jones2001,
           author = {Eric Jones and Travis Oliphant and Pearu Peterson},
           title  = {SciPy: Open source scientific tools for Python},
           year   = {2001},
         }
    """
    style = prompt_toolkit.styles.style_from_pygments_cls(
        pygments.styles.get_style_by_name(cm.get('style')))
    if labels is None:
        labels = ["" for _ in bibs]
    tokens = [(Token.Comment, u.BANNER)]
    for label, bib in zip(labels, bibs):
        tokens += [(Token.Text, label)]
        if meta:
            tokens += [(Token.Comment, bib.meta())]
        tokens += list(pygments.lex(bib.content, lexer=BibTeXLexer()))
        tokens += [(Token.Text, "\n")]

    print_formatted_text(PygmentsTokens(tokens),
                         end="",
                         style=style,
                         output=create_output(sys.stdout))
コード例 #8
0
ファイル: utils.py プロジェクト: kalkin/git-log-viewer
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()
コード例 #9
0
ファイル: main.py プロジェクト: ashang/pymux
    def run_standalone(self, color_depth):
        """
        Run pymux standalone, rather than using a client/server architecture.
        This is mainly useful for debugging.
        """
        self._runs_standalone = True
        self._start_auto_refresh_thread()

        client_state = self.add_client(input=create_input(),
                                       output=create_output(stdout=sys.stdout),
                                       color_depth=color_depth,
                                       connection=None)

        client_state.app.run()
コード例 #10
0
ファイル: main.py プロジェクト: jonathanslenders/pymux
    def run_standalone(self, color_depth):
        """
        Run pymux standalone, rather than using a client/server architecture.
        This is mainly useful for debugging.
        """
        self._runs_standalone = True
        self._start_auto_refresh_thread()

        client_state = self.add_client(
            input=create_input(),
            output=create_output(stdout=sys.stdout),
            color_depth=color_depth,
            connection=None)

        client_state.app.run()
コード例 #11
0
ファイル: utils.py プロジェクト: chaitujaya720/JujuPractice
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)
コード例 #12
0
def create_app_session_from_tty() -> Generator[AppSession, None, None]:
    """
    Create `AppSession` that always prefers the TTY input/output.

    Even if `sys.stdin` and `sys.stdout` are connected to input/output pipes,
    this will still use the terminal for interaction (because `sys.stderr` is
    still connected to the terminal).

    Usage::

        from prompt_toolkit.shortcuts import prompt

        with create_app_session_from_tty():
            prompt('>')
    """
    from prompt_toolkit.input.defaults import create_input
    from prompt_toolkit.output.defaults import create_output

    input = create_input(always_prefer_tty=True)
    output = create_output(always_prefer_tty=True)

    with create_app_session(input=input, output=output) as app_session:
        yield app_session
コード例 #13
0
    def __init__(
            self,
            get_globals=None,
            get_locals=None,
            history_filename=None,
            vi_mode=False,
            input=None,
            output=None,
            color_depth=None,

            # For internal use.
            extra_key_bindings=None,
            _completer=None,
            _validator=None,
            _lexer=None,
            _extra_buffer_processors=None,
            _extra_layout_body=None,
            _extra_toolbars=None,
            _input_buffer_height=None):

        self.get_globals = get_globals or (lambda: {})
        self.get_locals = get_locals or self.get_globals

        self._completer = _completer or PythonCompleter(
            self.get_globals, self.get_locals)
        self._validator = _validator or PythonValidator(
            self.get_compiler_flags)
        self._lexer = _lexer or PygmentsLexer(PythonLexer)

        if history_filename:
            self.history = ThreadedHistory(FileHistory(history_filename))
        else:
            self.history = InMemoryHistory()

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        self.extra_key_bindings = extra_key_bindings or KeyBindings()

        # Settings.
        self.show_signature = False
        self.show_docstring = False
        self.show_meta_enter_message = True
        self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN
        self.completion_menu_scroll_offset = 1

        self.show_line_numbers = False
        self.show_status_bar = True
        self.wrap_lines = True
        self.complete_while_typing = True
        self.paste_mode = False  # When True, don't insert whitespace after newline.
        self.confirm_exit = True  # Ask for confirmation when Control-D is pressed.
        self.accept_input_on_enter = 2  # Accept when pressing Enter 'n' times.
        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor = True
        self.enable_system_bindings = True
        self.enable_input_validation = True
        self.enable_auto_suggest = False
        self.enable_mouse_support = False
        self.enable_history_search = False  # When True, like readline, going
        # back in history will filter the
        # history on the records starting
        # with the current input.

        self.enable_syntax_highlighting = True
        self.highlight_matching_parenthesis = False
        self.show_sidebar = False  # Currently show the sidebar.
        self.show_sidebar_help = True  # When the sidebar is visible, also show the help text.
        self.show_exit_confirmation = False  # Currently show 'Do you really want to exit?'
        self.terminal_title = None  # The title to be displayed in the terminal. (None or string.)
        self.exit_message = 'Do you really want to exit?'
        self.insert_blank_line_after_output = True  # (For the REPL.)

        # The buffers.
        self.default_buffer = self._create_buffer()
        self.search_buffer = Buffer()
        self.docstring_buffer = Buffer(read_only=True)

        # Tokens to be shown at the prompt.
        self.prompt_style = 'classic'  # The currently active style.

        self.all_prompt_styles = {  # Styles selectable from the menu.
            'ipython': IPythonPrompt(self),
            'classic': ClassicPrompt(),
        }

        self.get_input_prompt = lambda: \
            self.all_prompt_styles[self.prompt_style].in_prompt()

        self.get_output_prompt = lambda: \
            self.all_prompt_styles[self.prompt_style].out_prompt()

        #: Load styles.
        self.code_styles = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name = 'default'
        self._current_ui_style_name = 'default'

        if is_windows():
            self._current_code_style_name = 'win32'

        self._current_style = self._generate_style()

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures = []

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running = False

        self.output = output or create_output()
        self.input = input or create_input(sys.stdin)

        self.app = self._create_application(color_depth)

        if vi_mode:
            self.app.editing_mode = EditingMode.VI
コード例 #14
0
    def __init__(self,
                 get_globals=None, get_locals=None, history_filename=None,
                 vi_mode=False,

                 input=None,
                 output=None,
                 color_depth=None,

                 # For internal use.
                 extra_key_bindings=None,
                 _completer=None, _validator=None,
                 _lexer=None, _extra_buffer_processors=None,
                 _extra_layout_body=None, _extra_toolbars=None,
                 _input_buffer_height=None):

        self.get_globals = get_globals or (lambda: {})
        self.get_locals = get_locals or self.get_globals

        self._completer = _completer or PythonCompleter(self.get_globals, self.get_locals)
        self._validator = _validator or PythonValidator(self.get_compiler_flags)
        self._lexer = _lexer or PygmentsLexer(PythonLexer)

        if history_filename:
            self.history = ThreadedHistory(FileHistory(history_filename))
        else:
            self.history = InMemoryHistory()

        self._input_buffer_height = _input_buffer_height
        self._extra_layout_body = _extra_layout_body or []
        self._extra_toolbars = _extra_toolbars or []
        self._extra_buffer_processors = _extra_buffer_processors or []

        self.extra_key_bindings = extra_key_bindings or KeyBindings()

        # Settings.
        self.show_signature = False
        self.show_docstring = False
        self.show_meta_enter_message = True
        self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN
        self.completion_menu_scroll_offset = 1

        self.show_line_numbers = False
        self.show_status_bar = True
        self.wrap_lines = True
        self.complete_while_typing = True
        self.paste_mode = False  # When True, don't insert whitespace after newline.
        self.confirm_exit = True  # Ask for confirmation when Control-D is pressed.
        self.accept_input_on_enter = 2  # Accept when pressing Enter 'n' times.
                                        # 'None' means that meta-enter is always required.
        self.enable_open_in_editor = True
        self.enable_system_bindings = True
        self.enable_input_validation = True
        self.enable_auto_suggest = False
        self.enable_mouse_support = False
        self.enable_history_search = False  # When True, like readline, going
                                            # back in history will filter the
                                            # history on the records starting
                                            # with the current input.

        self.enable_syntax_highlighting = True
        self.swap_light_and_dark = False
        self.highlight_matching_parenthesis = False
        self.show_sidebar = False  # Currently show the sidebar.
        self.show_sidebar_help = True # When the sidebar is visible, also show the help text.
        self.show_exit_confirmation = False  # Currently show 'Do you really want to exit?'
        self.terminal_title = None  # The title to be displayed in the terminal. (None or string.)
        self.exit_message = 'Do you really want to exit?'
        self.insert_blank_line_after_output = True  # (For the REPL.)

        # The buffers.
        self.default_buffer = self._create_buffer()
        self.search_buffer = Buffer()
        self.docstring_buffer = Buffer(read_only=True)

        # Tokens to be shown at the prompt.
        self.prompt_style = 'classic'  # The currently active style.

        self.all_prompt_styles = {  # Styles selectable from the menu.
            'ipython': IPythonPrompt(self),
            'classic': ClassicPrompt(),
        }

        self.get_input_prompt = lambda: \
            self.all_prompt_styles[self.prompt_style].in_prompt()

        self.get_output_prompt = lambda: \
            self.all_prompt_styles[self.prompt_style].out_prompt()

        #: Load styles.
        self.code_styles = get_all_code_styles()
        self.ui_styles = get_all_ui_styles()
        self._current_code_style_name = 'default'
        self._current_ui_style_name = 'default'

        if is_windows():
            self._current_code_style_name = 'win32'

        self._current_style = self._generate_style()
        self.color_depth = color_depth or ColorDepth.default()

        self.max_brightness = 1.0
        self.min_brightness = 0.0

        # Options to be configurable from the sidebar.
        self.options = self._create_options()
        self.selected_option_index = 0

        #: Incremeting integer counting the current statement.
        self.current_statement_index = 1

        # Code signatures. (This is set asynchronously after a timeout.)
        self.signatures = []

        # Boolean indicating whether we have a signatures thread running.
        # (Never run more than one at the same time.)
        self._get_signatures_thread_running = False

        self.output = output or create_output()
        self.input = input or create_input(sys.stdin)

        self.style_transformation = merge_style_transformations([
            ConditionalStyleTransformation(
                SwapLightAndDarkStyleTransformation(),
                filter=Condition(lambda: self.swap_light_and_dark)),
            AdjustBrightnessStyleTransformation(
                lambda: self.min_brightness,
                lambda: self.max_brightness),
        ])
        self.ptpython_layout = PtPythonLayout(
            self,
            lexer=DynamicLexer(
                lambda: self._lexer if self.enable_syntax_highlighting else SimpleLexer()),
            input_buffer_height=self._input_buffer_height,
            extra_buffer_processors=self._extra_buffer_processors,
            extra_body=self._extra_layout_body,
            extra_toolbars=self._extra_toolbars)

        self.app = self._create_application()

        if vi_mode:
            self.app.editing_mode = EditingMode.VI
コード例 #15
0
def print_formatted_text(
    *values: Any,
    sep: str = " ",
    end: str = "\n",
    file: Optional[TextIO] = None,
    flush: bool = False,
    style: Optional[BaseStyle] = None,
    output: Optional[Output] = None,
    color_depth: Optional[ColorDepth] = None,
    style_transformation: Optional[StyleTransformation] = None,
    include_default_pygments_style: bool = True,
) -> None:
    """
    ::

        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.

    If a prompt_toolkit `Application` is currently running, this will always
    print above the application or prompt (similar to `patch_stdout`). So,
    `print_formatted_text` will erase the current application, print the text,
    and render the application again.

    :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).
    """
    assert not (output and file)

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

    assert isinstance(output, Output)

    # Get color depth.
    color_depth = color_depth or output.get_default_color_depth()

    # Merges values.
    def to_text(val: Any) -> StyleAndTextTuples:
        # 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.
    def render() -> None:
        assert isinstance(output, Output)

        renderer_print_formatted_text(
            output,
            fragments,
            _create_merged_style(
                style,
                include_default_pygments_style=include_default_pygments_style),
            color_depth=color_depth,
            style_transformation=style_transformation,
        )

        # Flush the output stream.
        if flush:
            output.flush()

    # If an application is running, print above the app. This does not require
    # `patch_stdout`.
    loop: Optional[AbstractEventLoop] = None

    app = get_app_or_none()
    if app is not None:
        loop = app.loop

    if loop is not None:
        loop.call_soon_threadsafe(lambda: run_in_terminal(render))
    else:
        render()
コード例 #16
0
ファイル: utils.py プロジェクト: pankajdeep/Project
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()
コード例 #17
0
 def default_output(self) -> 'Output':
     if self._default_output is None:
         from prompt_toolkit.output.defaults import create_output
         self._default_output = create_output()
     return self._default_output
コード例 #18
0
def print_formatted_text(
        *values: Any,
        sep: str = ' ',
        end: str = '\n',
        file: Optional[TextIO] = None,
        flush: bool = False,
        style: Optional[BaseStyle] = None,
        output: Optional[Output] = None,
        color_depth: Optional[ColorDepth] = None,
        style_transformation: Optional[StyleTransformation] = None,
        include_default_pygments_style: bool = True) -> None:
    """
    ::

        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).
    """
    assert not (output and file)

    # 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_app_session().output

    assert isinstance(output, Output)

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

    # Merges values.
    def to_text(val: Any) -> StyleAndTextTuples:
        # 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()
コード例 #19
0
def print_formatted_text(
        *values: Any,
        sep: str = ' ',
        end: str = '\n',
        file: Optional[TextIO] = None,
        flush: bool = False,
        style: Optional[BaseStyle] = None,
        output: Optional[Output] = None,
        color_depth: Optional[ColorDepth] = None,
        style_transformation: Optional[StyleTransformation] = None,
        include_default_pygments_style: bool = True) -> None:
    """
    ::

        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).
    """
    assert not (output and file)

    # 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_app_session().output

    assert isinstance(output, Output)

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

    # Merges values.
    def to_text(val: Any) -> StyleAndTextTuples:
        # 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()
コード例 #20
0
 def output(self) -> 'Output':
     if self._output is None:
         from prompt_toolkit.output.defaults import create_output
         self._output = create_output()
     return self._output
コード例 #21
0
ファイル: bib_manager.py プロジェクト: pcubillos/bibmanager
def display_list(bibs, verb=-1):
    """
    Display a list of BibTeX entries with different verbosity levels.

    Although this might seem a duplication of display_bibs(), this
    function is meant to provide multiple levels of verbosity and
    generally to display longer lists of entries.

    Parameters
    ----------
    bibs: List of Bib() objects
        BibTeX entries to display.
    verb: Integer
        The desired verbosity level:
        verb < 0: Display only the keys.
        verb = 0: Display the title, year, first author, and key.
        verb = 1: Display additionally the ADS and arXiv urls.
        verb = 2: Display additionally the full list of authors.
        verb > 2: Display the full BibTeX entry.
    """
    # Display outputs depending on the verb level:
    if verb >= 3:
        display_bibs(labels=None, bibs=bibs, meta=True)
        return

    style = prompt_toolkit.styles.style_from_pygments_cls(
        pygments.styles.get_style_by_name(cm.get('style')))
    if verb < 0:
        keys = "\n".join([bib.key for bib in bibs])
        print(f'\nKeys:\n{keys}')
        return

    for bib in bibs:
        year = '' if bib.year is None else f', {bib.year}'
        title = textwrap.fill(f"Title: {bib.title}{year}",
                              width=78,
                              subsequent_indent='    ')[7:]
        title_tokens = u.tokenizer('Title', title)

        author_format = 'short' if verb < 2 else 'long'
        authors = textwrap.fill(
            f"Authors: {bib.get_authors(format=author_format)}",
            width=78,
            subsequent_indent='    ')[9:]
        author_tokens = u.tokenizer('Authors', authors)

        # URLs:
        url_tokens = []
        if bib.eprint is not None:
            eprint = f'http://arxiv.org/abs/{bib.eprint}'
            url_tokens = u.tokenizer('ArXiv URL', eprint)
        url_tokens += u.tokenizer('ADS URL', bib.adsurl)
        url_tokens += u.tokenizer('bibcode', bib.bibcode)

        # Meta info:
        meta_tokens = u.tokenizer('PDF file', bib.pdf, Token.Comment)
        tags = textwrap.fill(' '.join(bib.tags),
                             width=78,
                             subsequent_indent='    ')[6:]
        meta_tokens += u.tokenizer('Tags', tags, Token.Comment)

        if verb <= 0:
            url_tokens = []
            meta_tokens = []

        key_tokens = u.tokenizer('key', bib.key, Token.Name.Label)

        print_formatted_text(
            PygmentsTokens([(Token.Text, '\n')] + title_tokens +
                           author_tokens + url_tokens + meta_tokens +
                           key_tokens),
            end="",
            style=style,
            output=create_output(sys.stdout))
コード例 #22
0
    def output(self) -> "Output":
        if self._output is None:
            from prompt_toolkit.output.defaults import create_output

            self._output = create_output()
        return self._output