def create_application(self, full_layout=True): """ makes the application object and the buffers """ if full_layout: layout = create_layout(self.lexer, ExampleLexer, ToolbarLexer) else: layout = create_tutorial_layout(self.lexer) buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'description': Buffer(is_multiline=True, read_only=True), 'parameter': Buffer(is_multiline=True, read_only=True), 'examples': Buffer(is_multiline=True, read_only=True), 'bottom_toolbar': Buffer(is_multiline=True), 'example_line': Buffer(is_multiline=True), 'default_values': Buffer(), 'symbols': Buffer(), 'progress': Buffer(is_multiline=False) } writing_buffer = Buffer(history=self.history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always()) return Application( mouse_support=False, style=self.styles, buffer=writing_buffer, on_input_timeout=self.on_input_timeout, key_bindings_registry=registry, layout=layout, buffers=buffers, )
def __init__(self, process): assert isinstance(process, Process) self.process = process self.chosen_name = None # Displayed the clock instead of this pane content. self.clock_mode = False # Give unique ID. Pane._pane_counter += 1 self.pane_id = Pane._pane_counter # Prompt_toolkit buffer, for displaying scrollable text. # (In copy mode, or help mode.) # Note: Because the scroll_buffer can only contain text, we also use the # copy_token_list, that contains a token list with color information. self.scroll_buffer = Buffer(read_only=True) self.copy_token_list = [] self.display_scroll_buffer = False self.scroll_buffer_title = '' # Search buffer, for use in copy mode. (Each pane gets its own search buffer.) self.search_buffer = Buffer() self.is_searching = False self.search_state = SearchState(ignore_case=False)
def __init__(self, name, cmdProcessor): self.prompt = BeforeInput('MAV>') self.input = Buffer(multiline=False, accept_handler=self.handle_action) self.output = Buffer(multiline=True) self.active = False self.name = name self.cmdCallback = cmdProcessor
def _create_application(self): """ Create CommandLineInterface instance. """ # Create Vi command buffer. def handle_action(cli, buffer): ' When enter is pressed in the Vi command line. ' text = buffer.text # Remember: leave_command_mode resets the buffer. # First leave command mode. We want to make sure that the working # pane is focussed again before executing the command handlers. self.leave_command_mode(append_to_history=True) # Execute command. handle_command(self, text) # Create history and search buffers. commands_history = FileHistory( os.path.join(self.config_directory, 'commands_history')) command_buffer = Buffer( accept_action=AcceptAction(handler=handle_action), enable_history_search=Always(), completer=create_command_completer(self), history=commands_history) search_buffer_history = FileHistory( os.path.join(self.config_directory, 'search_history')) search_buffer = Buffer(history=search_buffer_history, enable_history_search=Always(), accept_action=AcceptAction.IGNORE) # Create app. # Create CLI. application = Application( layout=self.editor_layout.layout, key_bindings_registry=self.key_bindings_manager.registry, buffers={ COMMAND_BUFFER: command_buffer, SEARCH_BUFFER: search_buffer, }, get_style=lambda: self.current_style, paste_mode=Condition(lambda cli: self.paste_mode), ignore_case=Condition(lambda cli: self.ignore_case), use_alternate_screen=True, on_abort=AbortAction.IGNORE, on_exit=AbortAction.IGNORE, on_buffer_changed=Callback(self._current_buffer_changed)) # Handle command line previews. # (e.g. when typing ':colorscheme blue', it should already show the # preview before pressing enter.) def preview(): if self.cli.current_buffer == command_buffer: self.previewer.preview(command_buffer.text) command_buffer.on_text_changed += preview return application
def __init__(self, loader): self.glob_expr = None self.text_expr = None self.desc_expr = None self.file_expr = None self.code_expr = None self.loader = loader self.list_buffer = Buffer(on_cursor_position_changed=self. list_row_change) # Editable buffer. # self.list_buffer.text = '\n'.join(self.list_lines) self.sync_list_lines() self.list_buffer.read_only = to_filter(True) self.list_buffer.app_state = self self.content_buffer = Buffer() # Editable buffer. self.content_buffer.text = self.code(0) self.content_buffer.read_only = to_filter(True) self.content_buffer.app_state = self help_text = self.SEARCH_DEFAULT_TEXT self.search_buffer = Buffer( on_text_changed=self.search_text_change) # Editable buffer. self.search_buffer.app_state = self # self.search_buffer.text = help_text self.search_buffer.read_only = to_filter(True) self.search_buffer.app_state = self self._index = 0 self.print_on_exit = False self._list_lines = None
def __init__(self): history = InMemoryHistory() vault_commandhandler = VaultCommandHelper() resource = Resource() self.helper_buffer = Buffer(is_multiline=True, complete_while_typing=True, enable_history_search=False, initial_document=None, accept_action=AcceptAction.IGNORE) self.vault_completer = VaultCompleter(vault_commandhandler, resource, self.helper_buffer) self.main_buffer = Buffer(completer=self.vault_completer, auto_suggest=AutoSuggestFromHistory(), history=history, validator=None, tempfile_suffix='', complete_while_typing=True, initial_document=None, accept_action=AcceptAction.RETURN_DOCUMENT) self.helper_buffer.text = "Vault Help" self.vault_completer.help_buffer = self.helper_buffer self.buffers = { DEFAULT_BUFFER: self.main_buffer, 'HELP': self.helper_buffer }
def repl(parser, interpreter, style_name='default'): registry = load_key_bindings() @registry.add_binding(Keys.Escape, Keys.Enter) # meta-enter/alt-enter def _(event): '''Evaluate the buffer ''' code = buffers[DEFAULT_BUFFER].text try: ast = parser.parse(code) except (UnexpectedToken, UnexpectedInput) as e: toolbar_value = str(e) return try: start_eval_time = time.time() retval = interpreter.eval(ast) except Exception as e: toolbar_value = "Error: %s" % e.args return else: buffers['RESULT'].text = str(retval) toolbar_value = "Time: {:0.4f}, Value: {}".format( time.time() - start_eval_time, str(retval)) @registry.add_binding(Keys.ControlC, eager=True) @registry.add_binding(Keys.ControlQ, eager=True) def _(event): '''Exit the REPL ''' event.cli.set_return_value(None) buffers = { DEFAULT_BUFFER: Buffer(is_multiline=True), 'RESULT': Buffer(is_multiline=True), } style = style_from_pygments(get_style_by_name(style_name)) application = Application(layout=layout, buffers=buffers, mouse_support=True, style=style, use_alternate_screen=True, key_bindings_registry=registry) eventloop = create_eventloop() try: cli = CommandLineInterface(application=application, eventloop=eventloop) cli.run() finally: eventloop.close()
def __init__(self, pymux, input, output, color_depth, connection): self.pymux = pymux self.input = input self.output = output self.color_depth = color_depth self.connection = connection #: True when the prefix key (Ctrl-B) has been pressed. self.has_prefix = False #: Error/info message. self.message = None # When a "confirm-before" command is running, # Show this text in the command bar. When confirmed, execute # confirm_command. self.confirm_text = None self.confirm_command = None # When a "command-prompt" command is running. self.prompt_text = None self.prompt_command = None # Popup. self.display_popup = False # Input buffers. self.command_buffer = Buffer(name=COMMAND, accept_handler=self._handle_command, auto_suggest=AutoSuggestFromHistory(), multiline=False, complete_while_typing=False, completer=create_command_completer(pymux)) self.prompt_buffer = Buffer(name=PROMPT, accept_handler=self._handle_prompt_command, multiline=False, auto_suggest=AutoSuggestFromHistory()) # Layout. self.layout_manager = LayoutManager(self.pymux, self) self.app = self._create_app() # Clear write positions right before rendering. (They are populated # during rendering). def before_render(_): self.layout_manager.reset_write_positions() self.app.before_render += before_render
def __init__(self, python_input, original_document): """ Create an `Application` for the history screen. This has to be run as a sub application of `python_input`. When this application runs and returns, it retuns the selected lines. """ self.python_input = python_input history_mapping = HistoryMapping(self, python_input.history, original_document) self.history_mapping = history_mapping document = Document(history_mapping.concatenated_history) document = Document( document.text, cursor_position=document.cursor_position + document.get_start_of_line_position(), ) self.history_buffer = Buffer( document=document, on_cursor_position_changed=self._history_buffer_pos_changed, accept_handler=( lambda buff: get_app().exit(result=self.default_buffer.text)), read_only=True, ) self.default_buffer = Buffer( name=DEFAULT_BUFFER, document=history_mapping.get_new_document(), on_cursor_position_changed=self._default_buffer_pos_changed, read_only=True, ) self.help_buffer = Buffer(document=Document(HELP_TEXT, 0), read_only=True) self.history_layout = HistoryLayout(self) self.app = Application( layout=self.history_layout.layout, full_screen=True, style=python_input._current_style, mouse_support=Condition(lambda: python_input.enable_mouse_support), key_bindings=create_key_bindings(self, python_input, history_mapping), )
def __init__(self, question, candidates, other=False, default=None, **kwargs): self._candidates = candidates self._other = other self._selected, other_value = self._get_default_selected(default) self._candidate_control = ChoiceCandidatesControl( candidates, self._selected) if self.has_other: buf = Buffer(accept_handler=self._buffer_handler, multiline=False, **kwargs) buf.document = Document(other_value) self._other_value_control = BufferControl(buf) self._other_label_control = ChoiceOtherLabelControl( self.other_selected, self._other if isinstance(self._other, str) else None, ) super().__init__(question)
def _create_buffer(self) -> Buffer: """ Create the `Buffer` for the Python input. """ python_buffer = Buffer( name=DEFAULT_BUFFER, complete_while_typing=Condition( lambda: self.complete_while_typing), enable_history_search=Condition( lambda: self.enable_history_search), tempfile_suffix=".py", history=self.history, completer=ThreadedCompleter(self._completer), validator=ConditionalValidator( self._validator, Condition(lambda: self.enable_input_validation)), auto_suggest=ConditionalAutoSuggest( ThreadedAutoSuggest(AutoSuggestFromHistory()), Condition(lambda: self.enable_auto_suggest), ), accept_handler=self._accept_handler, on_text_changed=self._on_input_timeout, ) return python_buffer
def create_cli(message='', multiline=False, is_password=False, vi_mode=False, lexer=None, enable_system_prompt=False, enable_open_in_editor=False, validator=None, completer=None, style=None, history=None, get_bottom_toolbar_tokens=None): # Create history instance. if history is None: history = History() # Load all key bindings. manager = KeyBindingManager(enable_vi_mode=vi_mode, enable_system_prompt=enable_system_prompt, enable_open_in_editor=enable_open_in_editor) # Create interface. return CommandLineInterface( layout=create_default_layout(message=message, lexer=lexer, is_password=is_password, reserve_space_for_menu=(completer is not None), get_bottom_toolbar_tokens=get_bottom_toolbar_tokens), buffer=Buffer( is_multiline=multiline, history=history, validator=validator, completer=completer, ), key_bindings_registry=manager.registry, style=style)
def initialize(self): history = InMemoryHistory() toolbar_handler = create_toolbar_handler(self.get_long_options) layout = create_prompt_layout( get_prompt_tokens=self.get_prompt_tokens, lexer=create_lexer(), get_bottom_toolbar_tokens=toolbar_handler) buf = Buffer(history=history, completer=CrutchCompleter(self.renv), complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) manager = get_key_manager(self.set_long_options, self.get_long_options) application = Application(style=style_factory(), layout=layout, buffer=buf, key_bindings_registry=manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.cli = CommandLineInterface(application=application, eventloop=eventloop)
def _reset(self): self._answered: bool = False self._buffer: Buffer = Buffer( validator=Validator.from_callable(self._validate), name=DEFAULT_BUFFER, accept_handler=self._submit, )
class AppContext: app: Application = None process_fn = None box_veritcal_orientation = True display_help = False print_output_on_exit: bool = False non_interactive = False live = True current_error: str = None copied_to_clipboard = False dirty = False cmd_buffer: Buffer = Buffer(multiline=False) input_buffer: Buffer = Buffer() output_buffer: Buffer = Buffer(read_only=True)
def __init__(self, base_dir, config): for module in config.get('modules'): import_module(module) self.tasks = TaskManager(self) self.window = MainWindow(self) self.style = ToshStyle(config.get('ui', 'style')) self._parser = CommandLineParser(self, base_dir) self.config = config self.variables = {} application = Application( layout=self.window, buffer=Buffer( enable_history_search=True, complete_while_typing=False, is_multiline=False, history=FileHistory(base_dir + "/history"), # validator=validator, completer=CommandLineCompleter(self), auto_suggest=AutoSuggestFromHistory(), accept_action=AcceptAction(self.run_command), ), mouse_support=config.get('ui', 'mouse'), style=self.style, key_bindings_registry=get_key_bindings(self), use_alternate_screen=True) self._cli = CommandLineInterface(application=application, eventloop=create_asyncio_eventloop(), output=create_output(true_color=True))
def _create_cli(self): """Create the prompt_toolkit's CommandLineInterface.""" history = FileHistory(os.path.expanduser('~/.haxornewshistory')) toolbar = Toolbar(lambda: self.paginate_comments) layout = create_default_layout( message=u'haxor> ', reserve_space_for_menu=8, get_bottom_toolbar_tokens=toolbar.handler, ) cli_buffer = Buffer( history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=self.completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT) self.key_manager = self._create_key_manager() style_factory = StyleFactory(self.theme) application = Application( mouse_support=False, style=style_factory.style, layout=layout, buffer=cli_buffer, key_bindings_registry=self.key_manager.manager.registry, on_exit=AbortAction.RAISE_EXCEPTION, on_abort=AbortAction.RETRY, ignore_case=True) eventloop = create_eventloop() self.cli = CommandLineInterface( application=application, eventloop=eventloop)
def __init__(self, app=None, show=False, title='[ A Window ]', show_divider=lambda:True, get_lexer=lambda: None, height=Dimension(preferred=1), wrap_lines=False, scroll_offsets=ScrollOffsets()): self.app = app self.show = show self.buffer = Buffer(document=Document(), multiline=True) self.control = BufferControl(buffer=self.buffer, focusable=True, lexer=self.lexer, focus_on_click=True) self.window = PromptWindow(content=self.control, height=height, wrap_lines=wrap_lines, scroll_offsets=scroll_offsets) self.divider = Divider(self, show=show_divider) self.info = InfoLine(title, width=240) self.container = ConditionalContainer( content=VSplit([ self.divider.get_ui(), HSplit([self.info.get_ui(), self.window])]), filter=Condition(lambda: self.show))
def __init__(self, editor, location=None, text=None): assert location is None or isinstance(location, string_types) assert text is None or isinstance(text, string_types) assert not (location and text) self._editor_ref = weakref.ref(editor) self.location = location self.encoding = 'utf-8' #: is_new: True when this file does not yet exist in the storage. self.is_new = True # Read text. if location: text = self._read(location) else: text = text or '' self._file_content = text # Create Buffer. self.buffer = Buffer(multiline=True, completer=DocumentCompleter(editor, self), document=Document(text, 0), on_text_changed=lambda _: self.run_reporter()) # List of reporting errors. self.report_errors = [] self._reporter_is_running = False
def _feed_cli_with_input(text, editing_mode=EditingMode.EMACS, clipboard=None, history=None): """ Create a CommandLineInterface, feed it with the given user input and return the CLI object. This returns a (result, CLI) tuple. """ # If the given text doesn't end with a newline, the interface won't finish. assert text.endswith('\n') from prompt_toolkit.eventloop.posix import PosixEventLoop as EventLoop loop = EventLoop() try: inp = PipeInput() inp.send_text(text) cli = CommandLineInterface(application=Application( buffer=Buffer(accept_action=AcceptAction.RETURN_DOCUMENT, history=history), editing_mode=editing_mode, clipboard=clipboard or InMemoryClipboard(), key_bindings_registry=KeyBindingManager.for_prompt().registry, ), eventloop=loop, input=inp, output=DummyOutput()) result = cli.run() return result, cli finally: loop.close() inp.close()
def _create_buffer(self): """ Create the `Buffer` for the Python input. """ def is_buffer_multiline(): return (self.paste_mode or self.accept_input_on_enter is None or document_is_multiline_python(python_buffer.document)) python_buffer = Buffer( is_multiline=Condition(is_buffer_multiline), complete_while_typing=Condition( lambda: self.complete_while_typing), enable_history_search=Condition( lambda: self.enable_history_search), tempfile_suffix='.py', history=self.history, completer=self._completer, validator=ConditionalValidator( self._validator, Condition(lambda: self.enable_input_validation)), auto_suggest=ConditionalAutoSuggest( AutoSuggestFromHistory(), Condition(lambda cli: self.enable_auto_suggest)), accept_action=self._accept_action) return python_buffer
def create_application(self): """ Create an `Application` instance for use in a `CommandLineInterface`. """ buffers = { 'docstring': Buffer(read_only=True), } buffers.update(self._extra_buffers or {}) return Application( layout=create_layout( self, lexer=self._lexer, 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), buffer=self._create_buffer(), buffers=buffers, key_bindings_registry=self.key_bindings_registry, paste_mode=Condition(lambda cli: self.paste_mode), mouse_support=Condition(lambda cli: self.enable_mouse_support), on_abort=AbortAction.RETRY, on_exit=self._on_exit, style=DynamicStyle(lambda: self._current_style), get_title=lambda: self.terminal_title, on_initialize=self._on_cli_initialize, on_start=self._on_start, on_input_timeout=self._on_input_timeout)
def __init__(self, editor, buffer_name, location=None, text=None): assert isinstance(buffer_name, string_types) assert location is None or isinstance(location, string_types) assert text is None or isinstance(text, string_types) assert not (location and text) self._editor_ref = weakref.ref(editor) self.buffer_name = buffer_name self.location = location self.encoding = 'utf-8' #: is_new: True when this file does not yet exist in the storage. self.is_new = True # Read text. if location: text = self._read(location) else: text = text or '' self._file_content = text # Create Buffer. self.buffer = Buffer(is_multiline=Always(), completer=DocumentCompleter(editor, self), initial_document=Document(text, 0), accept_action=AcceptAction.IGNORE) # List of reporting errors. self.report_errors = []
def create_buffer(self, completer, history): return Buffer(history=history, auto_suggest=AutoSuggestFromHistory(), enable_history_search=True, completer=completer, complete_while_typing=Always(), accept_action=AcceptAction.RETURN_DOCUMENT)
def __init__(self, notebook, idx: int = 0, cell_json: Optional[Dict[str, Any]] = None): self.notebook = notebook if cell_json is None: cell_json = { "cell_type": "code", "execution_count": None, "metadata": {}, "source": [], "outputs": [], } self.input_prefix = Window(width=10) input_text = "".join(cell_json["source"]) if cell_json["cell_type"] == "code": execution_count = cell_json["execution_count"] or " " self.input_prefix.content = FormattedTextControl( text=f"\nIn [{execution_count}]:") if "outputs" in cell_json: outputs = cell_json["outputs"] else: outputs = [] self.json = cell_json output_text, output_height = get_output_text_and_height(outputs) self.idx = idx self.input_window = Window() self.input_buffer = Buffer(on_text_changed=self.input_text_changed) self.input_buffer.text = input_text self.set_input_readonly() self.input = Frame(self.input_window) self.output = Window(content=FormattedTextControl(text=output_text)) self.output.height = output_height
def __init__( self, prompt: AnyFormattedText = "Shell command: ", enable_global_bindings: FilterOrBool = True, ) -> None: self.prompt = prompt self.enable_global_bindings = to_filter(enable_global_bindings) self.system_buffer = Buffer(name=SYSTEM_BUFFER) self._bindings = self._build_key_bindings() self.buffer_control = BufferControl( buffer=self.system_buffer, lexer=SimpleLexer(style="class:system-toolbar.text"), input_processors=[ BeforeInput(lambda: self.prompt, style="class:system-toolbar") ], key_bindings=self._bindings, ) self.window = Window( self.buffer_control, height=1, style="class:system-toolbar" ) self.container = ConditionalContainer( content=self.window, filter=has_focus(self.system_buffer) )
def __init__(self, text='', width=None, extend_width=True, read_only=False, on_accepted=None, on_changed=None, style=''): self._activity_indicator = utils.ActivityIndicator( callback=self.set_text) self.read_only = read_only self.on_accepted = on_accepted self.buffer = Buffer( multiline=False, accept_handler=self._accept_handler, on_text_changed=on_changed, read_only=Condition(lambda: self.read_only), ) self.container = Window( content=BufferControl(self.buffer), always_hide_cursor=Condition(lambda: self.read_only), width=width, dont_extend_height=True, dont_extend_width=not extend_width, style=style, ) if text: self.set_text(text, ignore_callback=True)
def editor_window(self): """configure the editor window and returns a application class""" self.buffer_1 = Buffer() # need the text in another method self.text = self.open_file() f_ext = pathlib.PurePath(self.file_abs_path).suffix # set container(s) self.buffer_1.text = self.text style_n = style_from_pygments_cls(get_style_by_name("friendly")) container = Window( BufferControl(buffer=self.buffer_1, lexer=syntax_highlight(f_ext))) # create layout layout_editor = Layout(container) # make an instance from keybinds method key_bind = self.key_binds("") # define application that will be started app = Application(layout=layout_editor, key_bindings=key_bind, full_screen=True, style=style_n) return app
def _create_default_buffer(self): """ Create and return the default input buffer. """ dyncond = self._dyncond # Create buffers list. def accept(buff): """ Accept the content of the default buffer. This is called when the validation succeeds. """ self.app.exit(result=buff.document.text) return Buffer( name=DEFAULT_BUFFER, # Make sure that complete_while_typing is disabled when # enable_history_search is enabled. (First convert to Filter, # to avoid doing bitwise operations on bool objects.) complete_while_typing=Condition( lambda: _true(self.complete_while_typing) and not _true( self.enable_history_search) and not self.complete_style == CompleteStyle.READLINE_LIKE), validate_while_typing=dyncond('validate_while_typing'), enable_history_search=dyncond('enable_history_search'), validator=DynamicValidator(lambda: self.validator), completer=DynamicCompleter( lambda: ThreadedCompleter(self.completer) if self. complete_in_thread and self.completer else self.completer), history=self.history, auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest), accept_handler=accept, tempfile_suffix=lambda: self.tempfile_suffix)
def get_root_container(self) -> FloatContainer: validator = CoordinateValidator(self.maze_grid) maze_grid_container = Label(text=self.maze_grid.format_grid, ) coordinates_input_container = Window( BufferControl( buffer=Buffer( validator=validator, validate_while_typing=False, multiline=False, accept_handler=self._accept_handler, ), input_processors=[ BeforeInput("Enter coordinates (x, y): "), ], ), ) validation_toolbar = ConditionalContainer( ValidationToolbar(), filter=~is_done, ) return FloatContainer( HSplit([ maze_grid_container, HorizontalLine(), coordinates_input_container, validation_toolbar, ]), floats=[], )