def create_confirm_session(message, suffix=' (y/n) '): """ Create a `PromptSession` object for the 'confirm' function. """ assert isinstance(message, text_type) bindings = KeyBindings() @bindings.add('y') @bindings.add('Y') def yes(event): session.default_buffer.text = 'y' event.app.exit(result=True) @bindings.add('n') @bindings.add('N') @bindings.add('c-c') def no(event): session.default_buffer.text = 'n' event.app.exit(result=False) @bindings.add(Keys.Any) def _(event): " Disallow inserting other text. " pass complete_message = merge_formatted_text([message, suffix]) session = PromptSession(complete_message, key_bindings=bindings) return session
def __init__(self, path): self.theme = "default" sections_list = [] for section in ["text", "prompt"]: sections_list.append(sections[section]) book = Book(root=path) book.parse() chapters = book.chapters[1] chapters.parse() contents = chapters.contents[0] render = self.get_label(contents) label = Label(merge_formatted_text(render)) self.container = HSplit( [ VSplit( [ sections["menu"], sections["vseparator"], HSplit([label, sections["prompt"]]), ] ), sections["hseparator"], sections["status"], ] )
def _create_interruption_dialog() -> PromptSession[InterruptAction]: bindings = KeyBindings() @bindings.add(Keys.Enter) @bindings.add(Keys.Escape) def nothing(event: KeyPressEvent) -> None: event.app.exit(result=InterruptAction.NOTHING) @bindings.add("c-c") @bindings.add("C") @bindings.add("c") def kill(event: KeyPressEvent) -> None: event.app.exit(result=InterruptAction.KILL) @bindings.add("c-d") @bindings.add("D") @bindings.add("d") def detach(event: KeyPressEvent) -> None: event.app.exit(result=InterruptAction.DETACH) @bindings.add(Keys.Any) def _(event: KeyPressEvent) -> None: # Disallow inserting other text. pass message = HTML(" <b>Interrupted</b>. Please choose the action:\n") suffix = HTML("<b>Ctrl-C</b> or <b>C</b> -- Kill\n" "<b>Ctrl-D</b> or <b>D</b> -- Detach \n" "<b>Enter</b> or <b>ESC</b> -- Continue the attached mode") complete_message = merge_formatted_text([message, suffix]) session: PromptSession[InterruptAction] = PromptSession( complete_message, key_bindings=bindings) return session
def show_result(self, result: object) -> None: """ Show __repr__ for an `eval` result. """ out_prompt = to_formatted_text(self.get_output_prompt()) # If the repr is valid Python code, use the Pygments lexer. result_repr = repr(result) try: compile(result_repr, "", "eval") except SyntaxError: formatted_result_repr = to_formatted_text(result_repr) else: formatted_result_repr = to_formatted_text( PygmentsTokens(list(_lex_python_result(result_repr)))) # If __pt_repr__ is present, take this. This can return # prompt_toolkit formatted text. if hasattr(result, "__pt_repr__"): try: formatted_result_repr = to_formatted_text( getattr(result, "__pt_repr__")()) if isinstance(formatted_result_repr, list): formatted_result_repr = FormattedText( formatted_result_repr) except: pass # Align every line to the prompt. line_sep = "\n" + " " * fragment_list_width(out_prompt) indented_repr: StyleAndTextTuples = [] lines = list(split_lines(formatted_result_repr)) for i, fragment in enumerate(lines): indented_repr.extend(fragment) # Add indentation separator between lines, not after the last line. if i != len(lines) - 1: indented_repr.append(("", line_sep)) # Write output tokens. if self.enable_syntax_highlighting: formatted_output = merge_formatted_text( [out_prompt, indented_repr]) else: formatted_output = FormattedText(out_prompt + [( "", fragment_list_to_text(formatted_result_repr))]) print_formatted_text( formatted_output, style=self._current_style, style_transformation=self.style_transformation, include_default_pygments_style=False, output=self.app.output, ) self.app.output.flush()
def test_merge_formatted_text(): html1 = HTML('<u>hello</u>') html2 = HTML('<b>world</b>') result = merge_formatted_text([html1, html2]) assert to_formatted_text(result) == [ ('class:u', 'hello'), ('class:b', 'world'), ]
def render_section(self, section): renderer = Renderer(tui=self.tui, section=section) self.text_area = FormattedTextArea( merge_formatted_text(renderer.render()), scrollbar=True, focusable=True, after_copy=partial(notify_after_copy, self.tui), ) self.reset(self.text_area)
def test_merge_formatted_text(): html1 = HTML("<u>hello</u>") html2 = HTML("<b>world</b>") result = merge_formatted_text([html1, html2]) assert to_formatted_text(result) == [ ("class:u", "hello"), ("class:b", "world"), ]
def _get_formatted_text(self): result = [] for i, convs in enumerate(conversations.values()): name = convs.name if i == self.selected_line: result.append([("[SetCursorPosition]", "")]) result.append(name) result.append("\n") return merge_formatted_text(result)
def get_prompt(app: Flask): """ Build the prompt dynamically every time its rendered. """ info_app = [] if getattr(app, "_show_info_app", True): info_app = get_info_app(app) return merge_formatted_text([*info_app, "$ "])
def create_pager_prompt( style: BaseStyle, title: AnyFormattedText = "" ) -> PromptSession[PagerResult]: """ Create a "continue" prompt for paginated output. """ bindings = KeyBindings() @bindings.add("enter") @bindings.add("down") def next_line(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.NEXT_LINE) @bindings.add("space") def next_page(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.NEXT_PAGE) @bindings.add("a") def print_all(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.PRINT_ALL) @bindings.add("q") @bindings.add("c-c") @bindings.add("c-d") @bindings.add("escape", eager=True) def no(event: KeyPressEvent) -> None: event.app.exit(result=PagerResult.ABORT) @bindings.add("<any>") def _(event: KeyPressEvent) -> None: "Disallow inserting other text." pass style session: PromptSession[PagerResult] = PromptSession( merge_formatted_text( [ title, HTML( "<status-toolbar>" "<more> -- MORE -- </more> " "<key>[Enter]</key> Scroll " "<key>[Space]</key> Next page " "<key>[a]</key> Print all " "<key>[q]</key> Quit " "</status-toolbar>: " ), ] ), key_bindings=bindings, erase_when_done=True, style=style, ) return session
def mainPrompt(title) -> HTML: icon = " >" #version="" version = "version is version" #str(datetime.datetime.now()) if detectNerdFont: icon = " " #icon=getIcon(""," >") caseVersion = HTML('<aaa style="" fg="red" bg="#444444"> ' + str(version) + '</aaa>') promptUser = HTML('<aaa style="" fg="white" bg="#444444"> ' + str(title + icon) + ' </aaa>') return merge_formatted_text([caseVersion, promptUser, " "])
def error(self, source, header_text=''): if source is None: return if not self.app.batch_mode: self._tee_print( merge_formatted_text([ HTML('<ansired>--- </ansired>').formatted_text, FormattedText([(PeekStyle.styles[TipsMinor], header_text)]) ]), plain_source=f'--- {header_text}') if isinstance(source, FormattedText): self._tee_print(source) else: self._tee_print(source, plain_source=source)
def show_result(self, result: object) -> None: if hasattr(result, "__pt_repr__"): out_prompt = to_formatted_text(self.get_output_prompt()) try: formatted_result_repr = to_formatted_text( getattr(result, "__pt_repr__")()) if isinstance(formatted_result_repr, list): formatted_result_repr = FormattedText( formatted_result_repr) except: pass line_sep = "\n" + " " * fragment_list_width(out_prompt) indented_repr: StyleAndTextTuples = [] lines = list(split_lines(formatted_result_repr)) for i, fragment in enumerate(lines): indented_repr.extend(fragment) # Add indentation separator between lines, not after the last line. if i != len(lines) - 1: indented_repr.append(("", line_sep)) # Write output tokens. if self.enable_syntax_highlighting: formatted_output = merge_formatted_text( [out_prompt, indented_repr]) else: formatted_output = FormattedText(out_prompt + [( "", fragment_list_to_text(formatted_result_repr))]) if self.enable_pager: self.print_paginated_formatted_text( to_formatted_text(formatted_output)) else: self.print_formatted_text(to_formatted_text(formatted_output)) self.app.output.flush() if self.insert_blank_line_after_output: self.app.output.write("\n") else: if self._formatter: result = self._formatter(result) self.console.print(result)
def show_result(self, result: object) -> None: """ Show __repr__ for an `eval` result. Note: this can raise `KeyboardInterrupt` if either calling `__repr__`, `__pt_repr__` or formatting the output with "Black" takes to long and the user presses Control-C. """ out_prompt = to_formatted_text(self.get_output_prompt()) # If the repr is valid Python code, use the Pygments lexer. try: result_repr = repr(result) except KeyboardInterrupt: raise # Don't catch here. except BaseException as e: # Calling repr failed. self._handle_exception(e) return try: compile(result_repr, "", "eval") except SyntaxError: formatted_result_repr = to_formatted_text(result_repr) else: # Syntactically correct. Format with black and syntax highlight. if self.enable_output_formatting: # Inline import. Slightly speed up start-up time if black is # not used. import black result_repr = black.format_str( result_repr, mode=black.FileMode( line_length=self.app.output.get_size().columns), ) formatted_result_repr = to_formatted_text( PygmentsTokens(list(_lex_python_result(result_repr)))) # If __pt_repr__ is present, take this. This can return prompt_toolkit # formatted text. try: if hasattr(result, "__pt_repr__"): formatted_result_repr = to_formatted_text( getattr(result, "__pt_repr__")()) if isinstance(formatted_result_repr, list): formatted_result_repr = FormattedText( formatted_result_repr) except KeyboardInterrupt: raise # Don't catch here. except: # For bad code, `__getattr__` can raise something that's not an # `AttributeError`. This happens already when calling `hasattr()`. pass # Align every line to the prompt. line_sep = "\n" + " " * fragment_list_width(out_prompt) indented_repr: StyleAndTextTuples = [] lines = list(split_lines(formatted_result_repr)) for i, fragment in enumerate(lines): indented_repr.extend(fragment) # Add indentation separator between lines, not after the last line. if i != len(lines) - 1: indented_repr.append(("", line_sep)) # Write output tokens. if self.enable_syntax_highlighting: formatted_output = merge_formatted_text( [out_prompt, indented_repr]) else: formatted_output = FormattedText(out_prompt + [( "", fragment_list_to_text(formatted_result_repr))]) if self.enable_pager: self.print_paginated_formatted_text( to_formatted_text(formatted_output)) else: self.print_formatted_text(to_formatted_text(formatted_output)) self.app.output.flush() if self.insert_blank_line_after_output: self.app.output.write("\n")
def patched_execute(self, line): """ Evaluate the line and print the result. """ output = self.app.output # WORKAROUND: Due to a bug in Jedi, the current directory is removed # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148 if "" not in sys.path: sys.path.insert(0, "") def compile_with_flags(code, mode): " Compile code with the right compiler flags. " return compile(code, "<stdin>", mode, flags=self.get_compiler_flags(), dont_inherit=True) if line.lstrip().startswith("\x1a"): # When the input starts with Ctrl-Z, quit the REPL. self.app.exit() elif line.lstrip().startswith("!"): # Run as shell command os.system(line[1:]) else: # Try eval first try: code = compile_with_flags(line, "eval") result = eval(code, self.get_globals(), self.get_locals()) locals = self.get_locals() locals["_"] = locals["_%i" % self.current_statement_index] = result if result is not None: out_prompt = self.get_output_prompt() try: result_str = "%r\n" % (result,) except UnicodeDecodeError: # In Python 2: `__repr__` should return a bytestring, # so to put it in a unicode context could raise an # exception that the 'ascii' codec can't decode certain # characters. Decode as utf-8 in that case. result_str = "%s\n" % repr(result).decode("utf-8") # Align every line to the first one. line_sep = "\n" + " " * fragment_list_width(out_prompt) result_str = line_sep.join(result_str.splitlines()) + "\n" # Support ansi formatting (removed syntax higlighting) ansi_formatted = ANSI(result_str)._formatted_text formatted_output = merge_formatted_text([FormattedText(out_prompt) + ansi_formatted]) print_formatted_text( formatted_output, style=self._current_style, style_transformation=self.style_transformation, include_default_pygments_style=False, ) # If not a valid `eval` expression, run using `exec` instead. except SyntaxError: code = compile_with_flags(line, "exec") six.exec_(code, self.get_globals(), self.get_locals()) output.flush()
def _to_text(self, formatted_text_list): return fragment_list_to_text( to_formatted_text(merge_formatted_text(formatted_text_list)))
def _execute(self, line: str) -> None: """ Evaluate the line and print the result. """ output = self.app.output # WORKAROUND: Due to a bug in Jedi, the current directory is removed # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148 if "" not in sys.path: sys.path.insert(0, "") def compile_with_flags(code: str, mode: str): " Compile code with the right compiler flags. " return compile( code, "<stdin>", mode, flags=self.get_compiler_flags(), dont_inherit=True, ) # If the input is single line, remove leading whitespace. # (This doesn't have to be a syntax error.) if len(line.splitlines()) == 1: line = line.strip() if line.lstrip().startswith("\x1a"): # When the input starts with Ctrl-Z, quit the REPL. self.app.exit() elif line.lstrip().startswith("!"): # Run as shell command os.system(line[1:]) else: # Try eval first try: code = compile_with_flags(line, "eval") result = eval(code, self.get_globals(), self.get_locals()) locals: Dict[str, Any] = self.get_locals() locals["_"] = locals["_%i" % self.current_statement_index] = result if result is not None: out_prompt = to_formatted_text(self.get_output_prompt()) try: result_str = "%r\n" % (result, ) except UnicodeDecodeError: # In Python 2: `__repr__` should return a bytestring, # so to put it in a unicode context could raise an # exception that the 'ascii' codec can't decode certain # characters. Decode as utf-8 in that case. result_str = "%s\n" % repr( result).decode( # type: ignore "utf-8") # Align every line to the first one. line_sep = "\n" + " " * fragment_list_width(out_prompt) result_str = line_sep.join(result_str.splitlines()) + "\n" # Write output tokens. if self.enable_syntax_highlighting: formatted_output = merge_formatted_text([ out_prompt, PygmentsTokens(list( _lex_python_result(result_str))), ]) else: formatted_output = FormattedText(out_prompt + [("", result_str)]) print_formatted_text( formatted_output, style=self._current_style, style_transformation=self.style_transformation, include_default_pygments_style=False, output=output, ) # If not a valid `eval` expression, run using `exec` instead. except SyntaxError: code = compile_with_flags(line, "exec") exec(code, self.get_globals(), self.get_locals()) output.flush()
def _execute(self, line): """ Evaluate the line and print the result. """ output = self.app.output def compile_with_flags(code, mode): " Compile code with the right compiler flags. " return compile(code, '<stdin>', mode, flags=self.get_compiler_flags(), dont_inherit=True) if line.lstrip().startswith('\x1a'): # When the input starts with Ctrl-Z, quit the REPL. self.app.exit() elif line.lstrip().startswith('!'): # Run as shell command os.system(line[1:]) else: # Try eval first try: code = compile_with_flags(line, 'eval') result = eval(code, self.get_globals(), self.get_locals()) locals = self.get_locals() locals['_'] = locals['_%i' % self.current_statement_index] = result if result is not None: out_prompt = self.get_output_prompt() try: result_str = '%r\n' % (result, ) except UnicodeDecodeError: # In Python 2: `__repr__` should return a bytestring, # so to put it in a unicode context could raise an # exception that the 'ascii' codec can't decode certain # characters. Decode as utf-8 in that case. result_str = '%s\n' % repr(result).decode('utf-8') # Align every line to the first one. line_sep = '\n' + ' ' * fragment_list_width(out_prompt) result_str = line_sep.join(result_str.splitlines()) + '\n' # Write output tokens. if self.enable_syntax_highlighting: formatted_output = merge_formatted_text([ out_prompt, PygmentsTokens(list( _lex_python_result(result_str))), ]) else: formatted_output = FormattedText(out_prompt + [('', result_str)]) print_formatted_text(formatted_output, style=self._current_style, include_default_pygments_style=False) # If not a valid `eval` expression, run using `exec` instead. except SyntaxError: code = compile_with_flags(line, 'exec') six.exec_(code, self.get_globals(), self.get_locals()) output.flush()
def update_section(self, section): renderer = Renderer(tui=self.tui, section=section) self.text_area.text = merge_formatted_text(renderer.render()) self.reset(self.text_area)
def _execute(self, line): """ Evaluate the line and print the result. """ output = self.app.output # WORKAROUND: Due to a bug in Jedi, the current directory is removed # from sys.path. See: https://github.com/davidhalter/jedi/issues/1148 if '' not in sys.path: sys.path.insert(0, '') def compile_with_flags(code, mode): " Compile code with the right compiler flags. " return compile(code, '<stdin>', mode, flags=self.get_compiler_flags(), dont_inherit=True) if line.lstrip().startswith('\x1a'): # When the input starts with Ctrl-Z, quit the REPL. self.app.exit() elif line.lstrip().startswith('!'): # Run as shell command os.system(line[1:]) else: # Try eval first try: code = compile_with_flags(line, 'eval') result = eval(code, self.get_globals(), self.get_locals()) locals = self.get_locals() locals['_'] = locals['_%i' % self.current_statement_index] = result if result is not None: out_prompt = self.get_output_prompt() try: result_str = '%r\n' % (result, ) except UnicodeDecodeError: # In Python 2: `__repr__` should return a bytestring, # so to put it in a unicode context could raise an # exception that the 'ascii' codec can't decode certain # characters. Decode as utf-8 in that case. result_str = '%s\n' % repr(result).decode('utf-8') # Align every line to the first one. line_sep = '\n' + ' ' * fragment_list_width(out_prompt) result_str = line_sep.join(result_str.splitlines()) + '\n' # Write output tokens. if self.enable_syntax_highlighting: formatted_output = merge_formatted_text([ out_prompt, PygmentsTokens(list(_lex_python_result(result_str))), ]) else: formatted_output = FormattedText( out_prompt + [('', result_str)]) print_formatted_text( formatted_output, style=self._current_style, style_transformation=self.style_transformation, include_default_pygments_style=False) # If not a valid `eval` expression, run using `exec` instead. except SyntaxError: code = compile_with_flags(line, 'exec') six.exec_(code, self.get_globals(), self.get_locals()) output.flush()