def __init__( self, title: AnyFormattedText = None, formatters: Optional[Sequence[Formatter]] = None, bottom_toolbar: AnyFormattedText = None, style: Optional[BaseStyle] = None, key_bindings: Optional[KeyBindings] = None, file: Optional[TextIO] = None, color_depth: Optional[ColorDepth] = None, output: Optional[Output] = None, input: Optional[Input] = None, ) -> None: self.title = title self.formatters = formatters or create_default_formatters() self.bottom_toolbar = bottom_toolbar self.counters: List[ProgressBarCounter[object]] = [] 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 get_app_session().output self.input = input or get_app_session().input self._thread: Optional[threading.Thread] = None self._loop = get_event_loop() self._app_loop = new_event_loop() self._has_sigwinch = False self._app_started = threading.Event()
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)
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)
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
def clear() -> None: """ Clear the screen. """ output = get_app_session().output output.erase_screen() output.cursor_goto(0, 0) output.flush()
def __init__( self, title: AnyFormattedText = None, formatters: Optional[Sequence[Formatter]] = [Text(' ')], bottom_toolbar: AnyFormattedText = None, style: Optional[BaseStyle] = None, key_bindings: Optional[KeyBindings] = None, file: Optional[TextIO] = None, color_depth: Optional[ColorDepth] = None, output: Optional[Output] = None, input: Optional[Input] = None, ) -> None: self.title = title self.formatters = formatters self.bottom_toolbar = bottom_toolbar self.models: List[ProgressModel] = [] 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 get_app_session().output self.input = input or get_app_session().input self._thread: Optional[threading.Thread] = None self._loop = get_event_loop() self._app_loop = new_event_loop() self._previous_winch_handler = None self._has_sigwinch = False if TYPE_CHECKING: # Infer type from getsignal result, as defined in typeshed. Too # complex to repeat here. self._previous_winch_handler = signal.getsignal(_SIGWINCH) self.root = None
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()
def set_title(text: str) -> None: """ Set the terminal title. """ output = get_app_session().output output.set_title(text)
EDITORS = [ "atom", "emacs", "gedit", "mousepad", "nano", "notepad", "notepad++", "vi", "vim" ] VIEWERS = ["bat", "less"] try: DEFAULT_EDITOR = filter_bin(*EDITORS)[-1] except IndexError: DEFAULT_EDITOR = None try: DEFAULT_VIEWER = filter_bin(*VIEWERS)[0] except IndexError: DEFAULT_VIEWER = None _output = get_app_session().output dcount = lambda d, n=0: sum( [dcount(v, n) if isinstance(v, dict) else n + 1 for v in d.values()]) def print_formatted_text(*args, **kwargs): """ Proxy function that uses the global (capturable) _output. """ kwargs['output'] = kwargs.get('output', _output) return print_ft(*args, **kwargs) class _CaptureOutput(DummyOutput): def __init__(self): self.__file = io.StringIO() def __str__(self):
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()
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()