def color_depth(self) -> ColorDepth: """ Active :class:`.ColorDepth`. """ depth = self._color_depth if callable(depth): return depth() or ColorDepth.default() if depth is None: return ColorDepth.default() return depth
def print_formatted_text(output, formatted_text, style, color_depth=None): """ Print a list of (style_str, text) tuples in the given style to the output. """ assert isinstance(output, Output) assert isinstance(style, BaseStyle) assert color_depth is None or color_depth in ColorDepth._ALL fragments = to_formatted_text(formatted_text) color_depth = color_depth or ColorDepth.default() # Reset first. output.reset_attributes() output.enable_autowrap() # Print all (style_str, text) tuples. attrs_for_style_string = _StyleStringToAttrsCache( style.get_attrs_for_style_str) for style_str, text in fragments: attrs = attrs_for_style_string[style_str] if attrs: output.set_attributes(attrs, color_depth) else: output.reset_attributes() # Assume that the output is raw, and insert a carriage return before # every newline. (Also important when the front-end is a telnet client.) assert '\r' not in text output.write(text.replace('\n', '\r\n')) # Reset again. output.reset_attributes() output.flush()
def create_radian_prompt_session(options): history_file = ".radian_history" if options.no_history: history = ModalInMemoryHistory() elif not options.global_history and os.path.exists(history_file): history = ModalFileHistory(os.path.abspath(history_file)) else: history = ModalFileHistory( os.path.join(os.path.expanduser("~"), history_file)) if is_windows(): output = None else: output = CustomVt100Output.from_pty( sys.stdout, term=get_term_environment_variable()) def get_inputhook(): terminal_width = [None] def _(context): while True: if context.input_is_ready(): break try: process_events() except Exception: pass output_width = session.app.output.get_size().columns if output_width and terminal_width[0] != output_width: terminal_width[0] = output_width setoption("width", max(terminal_width[0], 20)) time.sleep(1.0 / 30) return _ session = ModalPromptSession( color_depth=ColorDepth.default(term=os.environ.get("TERM")), history=history, enable_history_search=True, enable_suspend=True, tempfile_suffix=".R", input=CustomVt100Input(sys.stdin) if not is_windows() else None, output=output, inputhook=get_inputhook(), mode_class=RadianMode) load_settings(session) register_modes(session) return session
def _get_attributes(output, color: str): attr = Attrs(color=color, bgcolor='', bold=False, underline=False, italic=False, blink=False, reverse=False, hidden=False) # if output.true_color() and not output.ansi_colors_only(): # return output._escape_code_cache_true_color[attr] # else: # FIXME: probably want this to be configurable escape_code_caches = output._escape_code_caches[ColorDepth.default()] return escape_code_caches[attr]
def print_formatted_text( output: Output, formatted_text: AnyFormattedText, style: BaseStyle, style_transformation: Optional[StyleTransformation] = None, color_depth: Optional[ColorDepth] = None, ) -> None: """ Print a list of (style_str, text) tuples in the given style to the output. """ fragments = to_formatted_text(formatted_text) style_transformation = style_transformation or DummyStyleTransformation() color_depth = color_depth or ColorDepth.default() # Reset first. output.reset_attributes() output.enable_autowrap() # Print all (style_str, text) tuples. attrs_for_style_string = _StyleStringToAttrsCache( style.get_attrs_for_style_str, style_transformation ) for style_str, text, *_ in fragments: attrs = attrs_for_style_string[style_str] if attrs: output.set_attributes(attrs, color_depth) else: output.reset_attributes() # Eliminate carriage returns text = text.replace("\r", "") # Assume that the output is raw, and insert a carriage return before # every newline. (Also important when the front-end is a telnet client.) output.write(text.replace("\n", "\r\n")) # Reset again. output.reset_attributes() output.flush()
def print_formatted_text( output, formatted_text, style, style_transformation=None, color_depth=None): """ Print a list of (style_str, text) tuples in the given style to the output. """ assert isinstance(output, Output) assert isinstance(style, BaseStyle) assert style_transformation is None or isinstance(style_transformation, StyleTransformation) assert color_depth is None or color_depth in ColorDepth._ALL fragments = to_formatted_text(formatted_text) style_transformation = style_transformation or DummyStyleTransformation() color_depth = color_depth or ColorDepth.default() # Reset first. output.reset_attributes() output.enable_autowrap() # Print all (style_str, text) tuples. attrs_for_style_string = _StyleStringToAttrsCache( style.get_attrs_for_style_str, style_transformation) for style_str, text in fragments: attrs = attrs_for_style_string[style_str] if attrs: output.set_attributes(attrs, color_depth) else: output.reset_attributes() # Assume that the output is raw, and insert a carriage return before # every newline. (Also important when the front-end is a telnet client.) assert '\r' not in text output.write(text.replace('\n', '\r\n')) # Reset again. output.reset_attributes() output.flush()
def create_radian_prompt_session(options, settings): history_file = ".radian_history" if options.no_history: history = ModalInMemoryHistory() elif not options.global_history and os.path.exists(history_file): history = ModalFileHistory(os.path.abspath(history_file)) else: history = ModalFileHistory( os.path.join(os.path.expanduser("~"), history_file)) if is_windows(): output = None else: output = CustomVt100Output.from_pty( sys.stdout, term=get_term_environment_variable()) def get_inputhook(): terminal_width = [None] def _(context): while True: if context.input_is_ready(): break try: process_events() except Exception: pass output_width = session.app.output.get_size().columns if output_width and terminal_width[0] != output_width: terminal_width[0] = output_width setoption("width", max(terminal_width[0], 20)) time.sleep(1.0 / 30) return _ def vi_mode_prompt(): if session.editing_mode.lower( ) == "vi" and settings.show_vi_mode_prompt: return settings.vi_mode_prompt.format( str(session.app.vi_state.input_mode)[3:6]) return "" def message(): if hasattr(session.current_mode, "get_message"): return ANSI(vi_mode_prompt() + session.current_mode.get_message()) elif hasattr(session.current_mode, "message"): message = session.current_mode.message if callable(message): return ANSI(vi_mode_prompt() + message()) else: return ANSI(vi_mode_prompt() + message) else: return "" session = ModalPromptSession( message=message, color_depth=ColorDepth.default(term=os.environ.get("TERM")), style=style_from_pygments_cls(get_style_by_name( settings.color_scheme)), editing_mode="VI" if settings.editing_mode in ["vim", "vi"] else "EMACS", history=history, enable_history_search=True, history_search_no_duplicates=settings.history_search_no_duplicates, search_ignore_case=settings.history_search_ignore_case, enable_suspend=True, tempfile_suffix=".R", input=CustomVt100Input(sys.stdin) if not is_windows() else None, output=output, inputhook=get_inputhook(), mode_class=RadianMode) apply_settings(session, settings) def browse_activator(session): message = session.prompt_text if BROWSE_PATTERN.match(message): session.browse_level = BROWSE_PATTERN.match(message).group(1) return True else: return False def browse_on_pre_accept(session): if session.default_buffer.text.strip() in [ "n", "s", "f", "c", "cont", "Q", "where", "help" ]: session.add_history = False def shell_process_text(session): text = session.default_buffer.text shell.run_command(text) input_processors = [] if settings.highlight_matching_bracket: input_processors.append(HighlightMatchingBracketProcessor()) session.register_mode( "r", activator=lambda session: session.prompt_text == settings.prompt, insert_new_line=True, history_share_with="browse", get_message=lambda: settings.prompt, multiline=settings.indent_lines, complete_while_typing=settings.complete_while_typing, lexer=PygmentsLexer(SLexer), completer=RCompleter(timeout=settings.completion_timeout), key_bindings=create_key_bindings(), input_processors=input_processors, prompt_key_bindings=create_r_key_bindings(prase_text_complete)) session.register_mode("shell", on_post_accept=shell_process_text, insert_new_line=True, get_message=lambda: settings.shell_prompt, multiline=settings.indent_lines, complete_while_typing=settings.complete_while_typing, lexer=None, completer=SmartPathCompleter(), prompt_key_bindings=create_shell_key_bindings()) session.register_mode( "browse", activator=browse_activator, # on_pre_accept=browse_on_pre_accept, # disable insert_new_line=True, history_share_with="r", get_message=lambda: settings.browse_prompt.format(session.browse_level ), multiline=settings.indent_lines, complete_while_typing=True, lexer=PygmentsLexer(SLexer), completer=RCompleter(timeout=settings.completion_timeout), input_processors=input_processors, prompt_key_bindings=create_r_key_bindings(prase_text_complete), switchable_from=False, switchable_to=False) session.register_mode("unknown", insert_new_line=False, get_message=lambda: session.prompt_text, complete_while_typing=False, lexer=None, completer=None, prompt_key_bindings=None, switchable_from=False, switchable_to=False, input_processors=[]) return session
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
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 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 __init__( self, get_globals: Optional[_GetNamespace] = None, get_locals: Optional[_GetNamespace] = None, history_filename: Optional[str] = None, vi_mode: bool = False, color_depth: Optional[ColorDepth] = None, # Input/output. input: Optional[Input] = None, output: Optional[Output] = None, # For internal use. extra_key_bindings: Optional[KeyBindings] = None, _completer: Optional[Completer] = None, _validator: Optional[Validator] = None, _lexer: Optional[Lexer] = None, _extra_buffer_processors=None, _extra_layout_body=None, _extra_toolbars=None, _input_buffer_height=None, ) -> None: self.get_globals: _GetNamespace = get_globals or (lambda: {}) self.get_locals: _GetNamespace = get_locals or self.get_globals self._completer = _completer or FuzzyCompleter( PythonCompleter( self.get_globals, self.get_locals, lambda: self.enable_dictionary_completion, ), enable_fuzzy=Condition(lambda: self.enable_fuzzy_completion), ) self._validator = _validator or PythonValidator( self.get_compiler_flags) self._lexer = _lexer or PygmentsLexer(PythonLexer) self.history: History 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.title: AnyFormattedText = "" self.show_signature: bool = False self.show_docstring: bool = False self.show_meta_enter_message: bool = True self.completion_visualisation: CompletionVisualisation = CompletionVisualisation.MULTI_COLUMN self.completion_menu_scroll_offset: int = 1 self.show_line_numbers: bool = False self.show_status_bar: bool = True self.wrap_lines: bool = True self.complete_while_typing: bool = True self.paste_mode: bool = False # When True, don't insert whitespace after newline. self.confirm_exit: bool = True # Ask for confirmation when Control-D is pressed. self.accept_input_on_enter: int = 2 # Accept when pressing Enter 'n' times. # 'None' means that meta-enter is always required. self.enable_open_in_editor: bool = True self.enable_system_bindings: bool = True self.enable_input_validation: bool = True self.enable_auto_suggest: bool = False self.enable_mouse_support: bool = False self.enable_history_search: bool = 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: bool = True self.enable_fuzzy_completion: bool = False self.enable_dictionary_completion: bool = False self.swap_light_and_dark: bool = False self.highlight_matching_parenthesis: bool = False self.show_sidebar: bool = False # Currently show the sidebar. # When the sidebar is visible, also show the help text. self.show_sidebar_help: bool = True # Currently show 'Do you really want to exit?' self.show_exit_confirmation: bool = False # The title to be displayed in the terminal. (None or string.) self.terminal_title: Optional[str] = None self.exit_message: str = "Do you really want to exit?" self.insert_blank_line_after_output: bool = True # (For the REPL.) # The buffers. self.default_buffer = self._create_buffer() self.search_buffer: Buffer = Buffer() self.docstring_buffer: Buffer = Buffer(read_only=True) # Tokens to be shown at the prompt. self.prompt_style: str = "classic" # The currently active style. # Styles selectable from the menu. self.all_prompt_styles: Dict[str, PromptStyle] = { "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: Dict[str, BaseStyle] = get_all_code_styles() self.ui_styles = get_all_ui_styles() self._current_code_style_name: str = "default" self._current_ui_style_name: str = "default" if is_windows(): self._current_code_style_name = "win32" self._current_style = self._generate_style() self.color_depth: ColorDepth = color_depth or ColorDepth.default() self.max_brightness: float = 1.0 self.min_brightness: float = 0.0 # Options to be configurable from the sidebar. self.options = self._create_options() self.selected_option_index: int = 0 #: Incremeting integer counting the current statement. self.current_statement_index: int = 1 # Code signatures. (This is set asynchronously after a timeout.) self.signatures: List[Any] = [] # Boolean indicating whether we have a signatures thread running. # (Never run more than one at the same time.) self._get_signatures_thread_running: bool = False # Get into Vi navigation mode at startup self.vi_start_in_navigation_mode: bool = False # Preserve last used Vi input mode between main loop iterations self.vi_keep_last_used_mode: bool = False 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(input, output) if vi_mode: self.app.editing_mode = EditingMode.VI
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 __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