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 sync_list_lines(self): # if self._list_lines is None: # self._list_lines = self.all_list_lines self.list_buffer.read_only = to_filter(False) self.list_buffer.text = '\n'.join(self.list_lines) self.list_buffer.read_only = to_filter(True)
def decorator(func: T) -> T: if isinstance(func, Binding): # We're adding an existing Binding object. self.bindings.append( Binding( keys, func.handler, filter=func.filter & to_filter(filter), eager=to_filter(eager) | func.eager, is_global=to_filter(is_global) | func.is_global, save_before=func.save_before, record_in_macro=func.record_in_macro, )) else: self.bindings.append( Binding( keys, cast(KeyHandlerCallable, func), filter=filter, eager=eager, is_global=is_global, save_before=save_before, record_in_macro=record_in_macro, )) self._clear_cache() return func
def __init__( self, content: Container, scroll_offsets: Optional[ScrollOffsets] = None, keep_cursor_visible: FilterOrBool = True, keep_focused_window_visible: FilterOrBool = True, max_available_height: int = MAX_AVAILABLE_HEIGHT, width: AnyDimension = None, height: AnyDimension = None, show_scrollbar: FilterOrBool = True, display_arrows: FilterOrBool = True, up_arrow_symbol: str = "^", down_arrow_symbol: str = "v", ) -> None: self.content = content self.scroll_offsets = scroll_offsets or ScrollOffsets(top=1, bottom=1) self.keep_cursor_visible = to_filter(keep_cursor_visible) self.keep_focused_window_visible = to_filter( keep_focused_window_visible) self.max_available_height = max_available_height self.width = width self.height = height self.show_scrollbar = to_filter(show_scrollbar) self.display_arrows = to_filter(display_arrows) self.up_arrow_symbol = up_arrow_symbol self.down_arrow_symbol = down_arrow_symbol self.vertical_scroll = 0
def __init__( self, max_height: Optional[int] = None, scroll_offset: int = 0, extra_filter: FilterOrBool = True, display_arrows: FilterOrBool = False, z_index: int = 10**8, ) -> None: extra_filter = to_filter(extra_filter) display_arrows = to_filter(display_arrows) super().__init__( content=Window( content=CompletionsMenuControl(), width=Dimension(min=8), height=Dimension(min=1, max=max_height), scroll_offsets=ScrollOffsets(top=scroll_offset, bottom=scroll_offset), right_margins=[ScrollbarMargin(display_arrows=display_arrows)], dont_extend_width=True, style="class:completion-menu", z_index=z_index, ), # Show when there are completions but not at the point we are # returning the input. filter=has_completions & ~is_done & extra_filter, )
def key_binding( filter: FilterOrBool = True, eager: FilterOrBool = False, is_global: FilterOrBool = False, save_before: Callable[['KeyPressEvent'], bool] = (lambda event: True), record_in_macro: FilterOrBool = True) -> Callable[[KeyHandlerCallable], Binding]: """ Decorator that turn a function into a `Binding` object. This can be added to a `KeyBindings` object when a key binding is assigned. """ assert save_before is None or callable(save_before) filter = to_filter(filter) eager = to_filter(eager) is_global = to_filter(is_global) save_before = save_before record_in_macro = to_filter(record_in_macro) keys = () def decorator(function: KeyHandlerCallable) -> Binding: return Binding(keys, function, filter=filter, eager=eager, is_global=is_global, save_before=save_before, record_in_macro=record_in_macro) return decorator
def key_binding(filter=True, eager=False, is_global=False, save_before=None, record_in_macro=True): """ Decorator that turn a function into a `_Binding` object. This can be added to a `KeyBindings` object when a key binding is assigned. """ assert save_before is None or callable(save_before) filter = to_filter(filter) eager = to_filter(eager) is_global = to_filter(is_global) save_before = save_before or (lambda event: True) record_in_macro = to_filter(record_in_macro) keys = () def decorator(function): return _Binding(keys, function, filter=filter, eager=eager, is_global=is_global, save_before=save_before, record_in_macro=record_in_macro) return decorator
def __init__(self, min_rows=3, suggested_max_column_width=30, show_meta=True, extra_filter=True): show_meta = to_filter(show_meta) extra_filter = to_filter(extra_filter) # Display filter: show when there are completions but not at the point # we are returning the input. full_filter = has_completions & ~is_done & extra_filter any_completion_has_meta = Condition( lambda: any(c.display_meta for c in get_app().current_buffer. complete_state.current_completions)) # Create child windows. completions_window = ConditionalContainer(content=Window( content=MultiColumnCompletionMenuControl( min_rows=min_rows, suggested_max_column_width=suggested_max_column_width), width=Dimension(min=8), height=Dimension(min=1), style='class:completion-menu'), filter=full_filter) meta_window = ConditionalContainer( content=Window(content=_SelectedCompletionMetaControl()), filter=show_meta & full_filter & any_completion_has_meta) # Initialise split. super(MultiColumnCompletionsMenu, self).__init__([completions_window, meta_window])
def add(self, *keys, **kwargs): """ Decorator for adding a key bindings. :param filter: :class:`~prompt_toolkit.filters.Filter` to determine when this key binding is active. :param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`. When True, ignore potential longer matches when this key binding is hit. E.g. when there is an active eager key binding for Ctrl-X, execute the handler immediately and ignore the key binding for Ctrl-X Ctrl-E of which it is a prefix. :param is_global: When this key bindings is added to a `Container` or `Control`, make it a global (always active) binding. :param save_before: Callable that takes an `Event` and returns True if we should save the current buffer, before handling the event. (That's the default.) :param record_in_macro: Record these key bindings when a macro is being recorded. (True by default.) """ filter = to_filter(kwargs.pop('filter', True)) eager = to_filter(kwargs.pop('eager', False)) is_global = to_filter(kwargs.pop('is_global', False)) save_before = kwargs.pop('save_before', lambda e: True) record_in_macro = to_filter(kwargs.pop('record_in_macro', True)) assert not kwargs assert keys assert callable(save_before) keys = tuple(_check_and_expand_key(k) for k in keys) if isinstance(filter, Never): # When a filter is Never, it will always stay disabled, so in that # case don't bother putting it in the key bindings. It will slow # down every key press otherwise. def decorator(func): return func else: def decorator(func): if isinstance(func, _Binding): # We're adding an existing _Binding object. self.bindings.append( _Binding( keys, func.handler, filter=func.filter & filter, eager=eager | func.eager, is_global = is_global | func.is_global, save_before=func.save_before, record_in_macro=func.record_in_macro)) else: self.bindings.append( _Binding(keys, func, filter=filter, eager=eager, is_global=is_global, save_before=save_before, record_in_macro=record_in_macro)) self._clear_cache() return func return decorator
def add(self, *keys, **kwargs): """ Decorator for adding a key bindings. :param filter: :class:`~prompt_toolkit.filters.Filter` to determine when this key binding is active. :param eager: :class:`~prompt_toolkit.filters.Filter` or `bool`. When True, ignore potential longer matches when this key binding is hit. E.g. when there is an active eager key binding for Ctrl-X, execute the handler immediately and ignore the key binding for Ctrl-X Ctrl-E of which it is a prefix. :param is_global: When this key bindings is added to a `Container` or `Control`, make it a global (always active) binding. :param save_before: Callable that takes an `Event` and returns True if we should save the current buffer, before handling the event. (That's the default.) :param record_in_macro: Record these key bindings when a macro is being recorded. (True by default.) """ filter = to_filter(kwargs.pop('filter', True)) eager = to_filter(kwargs.pop('eager', False)) is_global = to_filter(kwargs.pop('is_global', False)) save_before = kwargs.pop('save_before', lambda e: True) record_in_macro = to_filter(kwargs.pop('record_in_macro', True)) assert not kwargs assert keys assert callable(save_before) keys = tuple(_check_and_expand_key(k) for k in keys) if isinstance(filter, Never): # When a filter is Never, it will always stay disabled, so in that # case don't bother putting it in the key bindings. It will slow # down every key press otherwise. def decorator(func): return func else: def decorator(func): if isinstance(func, _Binding): # We're adding an existing _Binding object. self.bindings.append( _Binding( keys, func.handler, filter=func.filter & filter, eager=eager | func.eager, is_global=is_global | func.is_global, save_before=func.save_before, record_in_macro=func.record_in_macro)) else: self.bindings.append( _Binding(keys, func, filter=filter, eager=eager, is_global=is_global, save_before=save_before, record_in_macro=record_in_macro)) self._clear_cache() return func return decorator
def list_row_change(self, buffer): app_state = buffer.app_state doc = buffer.document pos = doc.cursor_position_row content_buffer = app_state.content_buffer content_buffer.read_only = to_filter(False) content_buffer.text = app_state.code(pos) content_buffer.read_only = to_filter(True)
def search_text_change(self, buffer): rex_glob = re.compile(r'\\g([^\\]+)') rex_code = re.compile(r'\\c([^\\]+)') rex_file = re.compile(r'\\f([^\\]+)') rex_text = re.compile(r'\\t([^\\]+)') rex_slash = re.compile(r'\\$') app_state = buffer.app_state query = buffer.text m_glob = rex_glob.search(query) m_code = rex_code.search(query) m_file = rex_file.search(query) m_text = rex_text.search(query) m_slash = rex_slash.search(query) self.clear_searches() if m_slash: return if m_glob: self.glob_expr = m_glob.group(1) if m_code: self.code_expr = m_code.group(1) if m_file: self.file_expr = m_file.group(1) if m_text: self.text_expr = m_text.group(1) if not any([bool(m) for m in [m_glob, m_code, m_file, m_text]]): self.text_expr = query # if m_glob: # self.glob_expr = query.replace('\g', '') # elif m_code: # self.code_expr = query.replace('\c', '') # elif m_file: # self.file_expr = query.replace('\f', '') # else: # self.text_expr = query # app_state.text_expr = buffer.text app_state.sync_list_lines() self.set_code(0) return app_state = buffer.app_state doc = buffer.document pos = doc.cursor_position_row content_buffer = app_state.content_buffer content_buffer.read_only = to_filter(False) content_buffer.text = app_state.code(pos) content_buffer.read_only = to_filter(True)
def toggle_fuzzy(self): """ Toggle the fuzzy completions on/off for all of the relevant subcompleters. The QueryCompleter and NestedCompleter do not support fuzzy completions. """ log.debug('Toggling fuzzy completion.') self._fuzzy = not self._fuzzy self._profile_completer.enable_fuzzy = to_filter(self._fuzzy) self._region_completer.enable_fuzzy = to_filter(self._fuzzy) self._cache_completer.enable_fuzzy = to_filter(self._fuzzy) self._aws_completer.toggle_fuzzy()
def __init__(self, buffer=None, input_processors=None, include_default_input_processors=True, lexer=None, preview_search=False, focusable=True, search_buffer_control=None, menu_position=None, focus_on_click=False, key_bindings=None): from prompt_toolkit.key_binding.key_bindings import KeyBindingsBase assert buffer is None or isinstance(buffer, Buffer) assert input_processors is None or isinstance(input_processors, list) assert isinstance(include_default_input_processors, bool) assert menu_position is None or callable(menu_position) assert lexer is None or isinstance(lexer, Lexer) assert (search_buffer_control is None or callable(search_buffer_control) or isinstance(search_buffer_control, SearchBufferControl)) assert key_bindings is None or isinstance(key_bindings, KeyBindingsBase) self.input_processors = input_processors self.include_default_input_processors = include_default_input_processors self.default_input_processors = [ HighlightSearchProcessor(), HighlightIncrementalSearchProcessor(), HighlightSelectionProcessor(), DisplayMultipleCursors(), ] self.preview_search = to_filter(preview_search) self.focusable = to_filter(focusable) self.focus_on_click = to_filter(focus_on_click) self.buffer = buffer or Buffer() self.menu_position = menu_position self.lexer = lexer or SimpleLexer() self.key_bindings = key_bindings self._search_buffer_control = search_buffer_control #: Cache for the lexer. #: Often, due to cursor movement, undo/redo and window resizing #: operations, it happens that a short time, the same document has to be #: lexed. This is a fairly easy way to cache such an expensive operation. self._fragment_cache = SimpleCache(maxsize=8) self._xy_to_cursor_position = None self._last_click_timestamp = None self._last_get_processed_line = None
def __init__(self, keys, handler, filter=True, eager=False, is_global=False, save_before=None, record_in_macro=True): assert isinstance(keys, tuple) assert callable(handler) assert callable(save_before) self.keys = keys self.handler = handler self.filter = to_filter(filter) self.eager = to_filter(eager) self.is_global = to_filter(is_global) self.save_before = save_before self.record_in_macro = to_filter(record_in_macro)
def __init__(self, keys, handler, filter=True, eager=False, is_global=False, save_before=None, record_in_macro=True): assert isinstance(keys, tuple) assert callable(handler) assert callable(save_before) self.keys = keys self.handler = handler self.filter = to_filter(filter) self.eager = to_filter(eager) self.is_global = to_filter(is_global) self.save_before = save_before self.record_in_macro = to_filter(record_in_macro)
def delete_server(event, name): db.delete_one(name) buttons = servers.hsplit.children # The server has been removed from the db. Now, we have to remove the # button from the layout by iterating over buttons and removing it by index for idx, button in enumerate(buttons): if name == button.content.text()[1][1].strip(): del buttons[idx] if len(buttons) > 0: try: # If the deleted button was not the last button event.app.layout.focus(buttons[idx]) ButtonManager.prev_button = buttons[idx] select_item(event) except IndexError: # If the deleted button was the last button event.app.layout.focus(buttons[idx - 1]) ButtonManager.prev_button = buttons[idx - 1] select_item(event) else: # Last button was deleted, display message "No servers" control = FormattedTextControl('No Servers', focusable=True, show_cursor=False) window = Window(control, height=1, dont_extend_width=True, dont_extend_height=True) buttons.append(window) summary_buffer.read_only = to_filter(False) summary_buffer.text = '' summary_buffer.read_only = to_filter(True) ButtonManager.prev_button = None ButtonManager.current_button = None event.app.layout.focus(servers.content)
def custom_keybindings(bindings, **kw): if ptk_shell_type() == "prompt_toolkit2": from xonsh.ptk2.key_bindings import carriage_return from prompt_toolkit.filters import EmacsInsertMode, ViInsertMode handler = bindings.add insert_mode = ViInsertMode() | EmacsInsertMode() else: from xonsh.ptk.key_bindings import carriage_return from prompt_toolkit.filters import to_filter handler = bindings.registry.add_binding insert_mode = to_filter(True) @handler(" ", filter=IsMultiline() & insert_mode) def handle_space(event): buffer = event.app.current_buffer expand_abbrev(buffer) buffer.insert_text(" ") @handler( Keys.ControlJ, filter=IsMultiline() & insert_mode & ~completion_is_selected ) @handler( Keys.ControlM, filter=IsMultiline() & insert_mode & ~completion_is_selected ) def multiline_carriage_return(event): buffer = event.app.current_buffer current_char = buffer.document.current_char if not current_char or current_char.isspace(): expand_abbrev(buffer) carriage_return(buffer, event.cli)
def __init__( self, text: AnyFormattedText = '', style: str = '', focusable: FilterOrBool = False, key_bindings: Optional['KeyBindingsBase'] = None, show_cursor: bool = True, modal: bool = False, get_cursor_position: Optional[Callable[[], Optional[Point]]] = None ) -> None: self.text = text # No type check on 'text'. This is done dynamically. self.style = style self.focusable = to_filter(focusable) # Key bindings. self.key_bindings = key_bindings self.show_cursor = show_cursor self.modal = modal self.get_cursor_position = get_cursor_position #: Cache for the content. self._content_cache: SimpleCache[Any, UIContent] = SimpleCache(maxsize=18) self._fragment_cache: SimpleCache[int, StyleAndTextTuples] = SimpleCache(maxsize=1) # Only cache one fragment list. We don't need the previous item. # Render info for the mouse support. self._fragments: Optional[StyleAndTextTuples] = None
def __init__(self, style, output, input, full_screen=False, mouse_support=False, cpr_not_supported_callback=None): assert isinstance(style, BaseStyle) assert isinstance(output, Output) assert isinstance(input, Input) assert callable(cpr_not_supported_callback) or cpr_not_supported_callback is None self.style = style self.output = output self.input = input self.full_screen = full_screen self.mouse_support = to_filter(mouse_support) self.cpr_not_supported_callback = cpr_not_supported_callback self._in_alternate_screen = False self._mouse_support_enabled = False self._bracketed_paste_enabled = False # Future set when we are waiting for a CPR flag. self._waiting_for_cpr_futures = deque() self.cpr_support = CPR_Support.UNKNOWN if not input.responds_to_cpr: self.cpr_support = CPR_Support.NOT_SUPPORTED # Cache for the style. self._attrs_for_style = None self._last_style_hash = None self._last_transformation_hash = None self._last_color_depth = None self.reset(_scroll=True)
def __init__(self, display_arrows: FilterOrBool = False, up_arrow_symbol: str = '^', down_arrow_symbol: str = 'v') -> None: self.display_arrows = to_filter(display_arrows) self.up_arrow_symbol = up_arrow_symbol self.down_arrow_symbol = down_arrow_symbol
def __init__(self, style, output, full_screen=False, mouse_support=False, cpr_not_supported_callback=None): assert isinstance(style, BaseStyle) assert isinstance(output, Output) assert callable( cpr_not_supported_callback) or cpr_not_supported_callback is None self.style = style self.output = output self.full_screen = full_screen self.mouse_support = to_filter(mouse_support) self.cpr_not_supported_callback = cpr_not_supported_callback self._in_alternate_screen = False self._mouse_support_enabled = False self._bracketed_paste_enabled = False # Future set when we are waiting for a CPR flag. self._waiting_for_cpr_futures = deque() self.cpr_support = CPR_Support.UNKNOWN # Cache for the style. self._attrs_for_style = None self._last_style_hash = None self._last_transformation_hash = None self._last_color_depth = None self.reset(_scroll=True)
def __init__(self, display_arrows=False, up_arrow_symbol='^', down_arrow_symbol='v'): self.display_arrows = to_filter(display_arrows) self.up_arrow_symbol = up_arrow_symbol self.down_arrow_symbol = down_arrow_symbol
def __init__(self, key_bindings: KeyBindingsBase, filter: FilterOrBool = True) -> None: _Proxy.__init__(self) self.key_bindings = key_bindings self.filter = to_filter(filter)
def create_output(stdout=None, true_color=False, ansi_colors_only=None): """ Return an :class:`~prompt_toolkit.output.Output` instance for the command line. :param true_color: When True, use 24bit colors instead of 256 colors. (`bool` or :class:`~prompt_toolkit.filters.Filter`.) :param ansi_colors_only: When True, restrict to 16 ANSI colors only. (`bool` or :class:`~prompt_toolkit.filters.Filter`.) """ stdout = stdout or sys.__stdout__ true_color = to_filter(true_color) if is_windows(): from .conemu import ConEmuOutput from .win32 import Win32Output from .windows10 import is_win_vt100_enabled, Windows10_Output if is_win_vt100_enabled(): return Windows10_Output(stdout) if is_conemu_ansi(): return ConEmuOutput(stdout) else: return Win32Output(stdout) else: from .vt100 import Vt100_Output term = os.environ.get('TERM', '') if PY2: term = term.decode('utf-8') return Vt100_Output.from_pty(stdout, true_color=true_color, ansi_colors_only=ansi_colors_only, term=term)
def __init__( self, keys: Tuple[Union[Keys, str], ...], handler: KeyHandlerCallable, filter: FilterOrBool = True, eager: FilterOrBool = False, is_global: FilterOrBool = False, save_before: Callable[['KeyPressEvent'], bool] = (lambda e: True), record_in_macro: FilterOrBool = True ) -> None: self.keys = keys self.handler = handler self.filter = to_filter(filter) self.eager = to_filter(eager) self.is_global = to_filter(is_global) self.save_before = save_before self.record_in_macro = to_filter(record_in_macro)
def __init__( self, style: BaseStyle, output: Output, input: Input, full_screen: bool = False, mouse_support: FilterOrBool = False, cpr_not_supported_callback: Optional[Callable[[], None]] = None) -> None: self.style = style self.output = output self.input = input self.full_screen = full_screen self.mouse_support = to_filter(mouse_support) self.cpr_not_supported_callback = cpr_not_supported_callback self._in_alternate_screen = False self._mouse_support_enabled = False self._bracketed_paste_enabled = False # Future set when we are waiting for a CPR flag. self._waiting_for_cpr_futures: Deque[Future] = deque() self.cpr_support = CPR_Support.UNKNOWN if not input.responds_to_cpr: self.cpr_support = CPR_Support.NOT_SUPPORTED # Cache for the style. self._attrs_for_style: Optional[_StyleStringToAttrsCache] = None self._last_style_hash: Optional[Hashable] = None self._last_transformation_hash: Optional[Hashable] = None self._last_color_depth: Optional[ColorDepth] = None self.reset(_scroll=True)
def __init__(self, text='', style='', focusable=False, key_bindings=None, show_cursor=True, modal=False, get_cursor_position=None): from prompt_toolkit.key_binding.key_bindings import KeyBindingsBase assert isinstance(style, six.text_type) assert key_bindings is None or isinstance(key_bindings, KeyBindingsBase) assert isinstance(show_cursor, bool) assert isinstance(modal, bool) assert get_cursor_position is None or callable(get_cursor_position) self.text = text # No type check on 'text'. This is done dynamically. self.style = style self.focusable = to_filter(focusable) # Key bindings. self.key_bindings = key_bindings self.show_cursor = show_cursor self.modal = modal self.get_cursor_position = get_cursor_position #: Cache for the content. self._content_cache = SimpleCache(maxsize=18) self._fragment_cache = SimpleCache(maxsize=1) # Only cache one fragment list. We don't need the previous item. # Render info for the mouse support. self._fragments = None
def __init__( self, text: AnyFormattedText = "", style: str = "", focusable: FilterOrBool = False, key_bindings: Optional["KeyBindingsBase"] = None, show_cursor: bool = True, modal: bool = False, get_cursor_position: Optional[Callable[[], Optional[Point]]] = None, ) -> None: self.text = text # No type check on 'text'. This is done dynamically. self.style = style self.focusable = to_filter(focusable) # Key bindings. self.key_bindings = key_bindings self.show_cursor = show_cursor self.modal = modal self.get_cursor_position = get_cursor_position #: Cache for the content. self._content_cache: SimpleCache[Hashable, UIContent] = SimpleCache(maxsize=18) self._fragment_cache: SimpleCache[int, StyleAndTextTuples] = SimpleCache( maxsize=1) # Only cache one fragment list. We don't need the previous item. # Render info for the mouse support. self._fragments: Optional[StyleAndTextTuples] = None
def create_application(self): # Default key bindings. open_in_editor_bindings = load_open_in_editor_bindings() prompt_bindings = create_prompt_bindings() self.app = Application( layout=self.create_layout(), style=merge_styles([ default_style(), DynamicStyle(lambda: self.style), ]), key_bindings=merge_key_bindings([ merge_key_bindings([ ConditionalKeyBindings( open_in_editor_bindings, to_filter(self.enable_open_in_editor) & has_focus(DEFAULT_BUFFER)), prompt_bindings ]), DynamicKeyBindings(lambda: self.extra_key_bindings), ]), editing_mode=self.editing_mode, reverse_vi_search_direction=True, on_render=self.on_render, input=self.input, output=self.output) self.app.mp = self
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, min_rows: int = 3, suggested_max_column_width: int = 30, show_meta: FilterOrBool = True, extra_filter: FilterOrBool = True, z_index: int = 10**8, ) -> None: show_meta = to_filter(show_meta) extra_filter = to_filter(extra_filter) # Display filter: show when there are completions but not at the point # we are returning the input. full_filter = has_completions & ~is_done & extra_filter @Condition def any_completion_has_meta() -> bool: complete_state = get_app().current_buffer.complete_state return complete_state is not None and any( c.display_meta for c in complete_state.completions) # Create child windows. # NOTE: We don't set style='class:completion-menu' to the # `MultiColumnCompletionMenuControl`, because this is used in a # Float that is made transparent, and the size of the control # doesn't always correspond exactly with the size of the # generated content. completions_window = ConditionalContainer( content=Window( content=MultiColumnCompletionMenuControl( min_rows=min_rows, suggested_max_column_width=suggested_max_column_width, ), width=Dimension(min=8), height=Dimension(min=1), ), filter=full_filter, ) meta_window = ConditionalContainer( content=Window(content=_SelectedCompletionMetaControl()), filter=show_meta & full_filter & any_completion_has_meta, ) # Initialise split. super().__init__([completions_window, meta_window], z_index=z_index)
def _(event): " Quit application. " window_to_focus = event.app.state.focus_window(0) event.app.layout.focus(window_to_focus) event.app.state.search_buffer.text = AppState.SEARCH_DEFAULT_TEXT event.app.state.search_buffer.read_only = to_filter(True) event.app.state.clear_searches() event.app.state.sync_list_lines()
def __init__( self, buffer: Optional[Buffer] = None, input_processors: Optional[List[Processor]] = None, include_default_input_processors: bool = True, lexer: Optional[Lexer] = None, preview_search: FilterOrBool = False, focusable: FilterOrBool = True, search_buffer_control: Union[None, "SearchBufferControl", Callable[[], "SearchBufferControl"]] = None, menu_position: Optional[Callable] = None, focus_on_click: FilterOrBool = False, key_bindings: Optional["KeyBindingsBase"] = None, ): self.input_processors = input_processors self.include_default_input_processors = include_default_input_processors self.default_input_processors = [ HighlightSearchProcessor(), HighlightIncrementalSearchProcessor(), HighlightSelectionProcessor(), DisplayMultipleCursors(), ] self.preview_search = to_filter(preview_search) self.focusable = to_filter(focusable) self.focus_on_click = to_filter(focus_on_click) self.buffer = buffer or Buffer() self.menu_position = menu_position self.lexer = lexer or SimpleLexer() self.key_bindings = key_bindings self._search_buffer_control = search_buffer_control #: Cache for the lexer. #: Often, due to cursor movement, undo/redo and window resizing #: operations, it happens that a short time, the same document has to be #: lexed. This is a fairly easy way to cache such an expensive operation. self._fragment_cache: SimpleCache[Hashable, Callable[ [int], StyleAndTextTuples]] = SimpleCache(maxsize=8) self._last_click_timestamp: Optional[float] = None self._last_get_processed_line: Optional[Callable[ [int], _ProcessedLine]] = None
def __init__(self, min_rows: int = 3, suggested_max_column_width: int = 30, show_meta: FilterOrBool = True, extra_filter: FilterOrBool = True, z_index: int = 10 ** 8) -> None: show_meta = to_filter(show_meta) extra_filter = to_filter(extra_filter) # Display filter: show when there are completions but not at the point # we are returning the input. full_filter = has_completions & ~is_done & extra_filter @Condition def any_completion_has_meta() -> bool: complete_state = get_app().current_buffer.complete_state return complete_state is not None and any( c.display_meta for c in complete_state.completions) # Create child windows. # NOTE: We don't set style='class:completion-menu' to the # `MultiColumnCompletionMenuControl`, because this is used in a # Float that is made transparent, and the size of the control # doesn't always correspond exactly with the size of the # generated content. completions_window = ConditionalContainer( content=Window( content=MultiColumnCompletionMenuControl( min_rows=min_rows, suggested_max_column_width=suggested_max_column_width), width=Dimension(min=8), height=Dimension(min=1)), filter=full_filter) meta_window = ConditionalContainer( content=Window(content=_SelectedCompletionMetaControl()), filter=show_meta & full_filter & any_completion_has_meta) # Initialise split. super().__init__([ completions_window, meta_window ], z_index=z_index)
def __init__(self, max_height=None, scroll_offset=0, extra_filter=True, display_arrows=False, z_index=10 ** 8): extra_filter = to_filter(extra_filter) display_arrows = to_filter(display_arrows) super(CompletionsMenu, self).__init__( content=Window( content=CompletionsMenuControl(), width=Dimension(min=8), height=Dimension(min=1, max=max_height), scroll_offsets=ScrollOffsets(top=scroll_offset, bottom=scroll_offset), right_margins=[ScrollbarMargin(display_arrows=display_arrows)], dont_extend_width=True, style='class:completion-menu', z_index=z_index, ), # Show when there are completions but not at the point we are # returning the input. filter=has_completions & ~is_done & extra_filter)
def __init__( self, buffer: Optional[Buffer] = None, input_processors: Optional[List[Processor]] = None, include_default_input_processors: bool = True, lexer: Optional[Lexer] = None, preview_search: FilterOrBool = False, focusable: FilterOrBool = True, search_buffer_control: Union[None, 'SearchBufferControl', Callable[[], 'SearchBufferControl']] = None, menu_position: Optional[Callable] = None, focus_on_click: FilterOrBool = False, key_bindings: Optional['KeyBindingsBase'] = None): self.input_processors = input_processors self.include_default_input_processors = include_default_input_processors self.default_input_processors = [ HighlightSearchProcessor(), HighlightIncrementalSearchProcessor(), HighlightSelectionProcessor(), DisplayMultipleCursors(), ] self.preview_search = to_filter(preview_search) self.focusable = to_filter(focusable) self.focus_on_click = to_filter(focus_on_click) self.buffer = buffer or Buffer() self.menu_position = menu_position self.lexer = lexer or SimpleLexer() self.key_bindings = key_bindings self._search_buffer_control = search_buffer_control #: Cache for the lexer. #: Often, due to cursor movement, undo/redo and window resizing #: operations, it happens that a short time, the same document has to be #: lexed. This is a fairly easy way to cache such an expensive operation. self._fragment_cache: SimpleCache[Any, Callable[[int], StyleAndTextTuples]] = \ SimpleCache(maxsize=8) self._last_click_timestamp: Optional[float] = None self._last_get_processed_line: Optional[Callable[[int], _ProcessedLine]] = None
def __init__(self, completer: Completer, WORD: bool = False, pattern: Optional[str] = None, enable_fuzzy: FilterOrBool = True): assert pattern is None or pattern.startswith('^') self.completer = completer self.pattern = pattern self.WORD = WORD self.pattern = pattern self.enable_fuzzy = to_filter(enable_fuzzy)
def key_binding(filter=True, eager=False, is_global=False, save_before=None, record_in_macro=True): """ Decorator that turn a function into a `_Binding` object. This can be added to a `KeyBindings` object when a key binding is assigned. """ assert save_before is None or callable(save_before) filter = to_filter(filter) eager = to_filter(eager) is_global = to_filter(is_global) save_before = save_before or (lambda event: True) record_in_macro = to_filter(record_in_macro) keys = () def decorator(function): return _Binding(keys, function, filter=filter, eager=eager, is_global=is_global, save_before=save_before, record_in_macro=record_in_macro) return decorator
def __init__(self, pygments_lexer_cls, sync_from_start=True, syntax_sync=None): assert syntax_sync is None or isinstance(syntax_sync, SyntaxSync) self.pygments_lexer_cls = pygments_lexer_cls self.sync_from_start = to_filter(sync_from_start) # Instantiate the Pygments lexer. self.pygments_lexer = pygments_lexer_cls( stripnl=False, stripall=False, ensurenl=False) # Create syntax sync instance. self.syntax_sync = syntax_sync or RegexSync.from_pygments_lexer_cls(pygments_lexer_cls)
def __init__(self, pygments_lexer_cls: Type['PygmentsLexerCls'], sync_from_start: FilterOrBool = True, syntax_sync: Optional[SyntaxSync] = None) -> None: self.pygments_lexer_cls = pygments_lexer_cls self.sync_from_start = to_filter(sync_from_start) # Instantiate the Pygments lexer. self.pygments_lexer = pygments_lexer_cls( stripnl=False, stripall=False, ensurenl=False) # Create syntax sync instance. self.syntax_sync = syntax_sync or RegexSync.from_pygments_lexer_cls(pygments_lexer_cls)
def __init__(self, prompt='Shell command: ', enable_global_bindings=True): 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 test_to_filter(): f1 = to_filter(True) f2 = to_filter(False) f3 = to_filter(Condition(lambda: True)) f4 = to_filter(Condition(lambda: False)) assert isinstance(f1, Filter) assert isinstance(f2, Filter) assert isinstance(f3, Filter) assert isinstance(f4, Filter) assert f1() assert not f2() assert f3() assert not f4() with pytest.raises(TypeError): to_filter(4)
def __init__(self, style_transformation: StyleTransformation, filter: FilterOrBool) -> None: self.style_transformation = style_transformation self.filter = to_filter(filter)
def __init__(self, relative=False, display_tildes=False): self.relative = to_filter(relative) self.display_tildes = to_filter(display_tildes)
def __init__(self, style_transformation, filter): assert isinstance(style_transformation, StyleTransformation) self.style_transformation = style_transformation self.filter = to_filter(filter)
def __init__(self, display_arrows=False, up_arrow_symbol='^', down_arrow_symbol='v'): self.display_arrows = to_filter(display_arrows) self.up_arrow_symbol = up_arrow_symbol self.down_arrow_symbol = down_arrow_symbol
def dynamic(): value = getattr(self, attr_name) return to_filter(value)()
def __init__(self, processor: Processor, filter: FilterOrBool) -> None: self.processor = processor self.filter = to_filter(filter)
def __init__(self, margin, filter): assert isinstance(margin, Margin) self.margin = margin self.filter = to_filter(filter)
def __init__(self, text='', multiline=True, password=False, lexer=None, auto_suggest=None, completer=None, complete_while_typing=True, accept_handler=None, history=None, focusable=True, focus_on_click=False, wrap_lines=True, read_only=False, width=None, height=None, dont_extend_height=False, dont_extend_width=False, line_numbers=False, get_line_prefix=None, scrollbar=False, style='', search_field=None, preview_search=True, prompt='', input_processors=None): # assert isinstance(text, six.text_type) if search_field is None: search_control = None if input_processors is None: input_processors = [] # Writeable attributes. self.completer = completer self.complete_while_typing = complete_while_typing self.lexer = lexer self.auto_suggest = auto_suggest self.read_only = read_only self.wrap_lines = wrap_lines self.buffer = Buffer( document=Document(text, 0), multiline=multiline, read_only=Condition(lambda: is_true(self.read_only)), completer=DynamicCompleter(lambda: self.completer), complete_while_typing=Condition( lambda: is_true(self.complete_while_typing)), auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest), accept_handler=accept_handler, history=history) self.control = BufferControl( buffer=self.buffer, lexer=DynamicLexer(lambda: self.lexer), input_processors=[ ConditionalProcessor( AppendAutoSuggestion(), has_focus(self.buffer) & is_done), # ConditionalProcessor( processor=PasswordProcessor(), filter=to_filter(password) ), BeforeInput(prompt, style='class:text-area.prompt'), ] + input_processors, search_buffer_control=search_control, preview_search=preview_search, focusable=focusable, focus_on_click=focus_on_click) if multiline: if scrollbar: right_margins = [ScrollbarMargin(display_arrows=True)] else: right_margins = [] if line_numbers: left_margins = [NumberedMargin()] else: left_margins = [] else: height = D.exact(1) left_margins = [] right_margins = [] style = 'class:text-area ' + style self.window = Window( height=height, width=width, dont_extend_height=dont_extend_height, dont_extend_width=dont_extend_width, content=self.control, style=style, wrap_lines=Condition(lambda: is_true(self.wrap_lines)), left_margins=left_margins, right_margins=right_margins, get_line_prefix=get_line_prefix)
def enable_suspend(): return to_filter(self.enable_suspend)()
def __init__(self, layout: Optional[Layout] = None, style: Optional[BaseStyle] = None, include_default_pygments_style: FilterOrBool = True, style_transformation: Optional[StyleTransformation] = None, key_bindings: Optional[KeyBindingsBase] = None, clipboard: Optional[Clipboard] = None, full_screen: bool = False, color_depth: Union[ColorDepth, Callable[[], Union[ColorDepth, None]], None] = None, mouse_support: FilterOrBool = False, enable_page_navigation_bindings: Optional[FilterOrBool] = None, # Can be None, True or False. paste_mode: FilterOrBool = False, editing_mode: EditingMode = EditingMode.EMACS, erase_when_done: bool = False, reverse_vi_search_direction: FilterOrBool = False, min_redraw_interval: Union[float, int, None] = None, max_render_postpone_time: Union[float, int, None] = .01, on_reset: Optional[ApplicationEventHandler] = None, on_invalidate: Optional[ApplicationEventHandler] = None, before_render: Optional[ApplicationEventHandler] = None, after_render: Optional[ApplicationEventHandler] = None, # I/O. input: Optional[Input] = None, output: Optional[Output] = None): # If `enable_page_navigation_bindings` is not specified, enable it in # case of full screen applications only. This can be overridden by the user. if enable_page_navigation_bindings is None: enable_page_navigation_bindings = Condition(lambda: self.full_screen) paste_mode = to_filter(paste_mode) mouse_support = to_filter(mouse_support) reverse_vi_search_direction = to_filter(reverse_vi_search_direction) enable_page_navigation_bindings = to_filter(enable_page_navigation_bindings) include_default_pygments_style = to_filter(include_default_pygments_style) if layout is None: layout = create_dummy_layout() if style_transformation is None: style_transformation = DummyStyleTransformation() self.style = style self.style_transformation = style_transformation # Key bindings. self.key_bindings = key_bindings self._default_bindings = load_key_bindings() self._page_navigation_bindings = load_page_navigation_bindings() self.layout = layout self.clipboard = clipboard or InMemoryClipboard() self.full_screen: bool = full_screen self._color_depth = color_depth self.mouse_support = mouse_support self.paste_mode = paste_mode self.editing_mode = editing_mode self.erase_when_done = erase_when_done self.reverse_vi_search_direction = reverse_vi_search_direction self.enable_page_navigation_bindings = enable_page_navigation_bindings self.min_redraw_interval = min_redraw_interval self.max_render_postpone_time = max_render_postpone_time # Events. self.on_invalidate = Event(self, on_invalidate) self.on_reset = Event(self, on_reset) self.before_render = Event(self, before_render) self.after_render = Event(self, after_render) # I/O. session = get_app_session() self.output = output or session.output self.input = input or session.input # List of 'extra' functions to execute before a Application.run. self.pre_run_callables: List[Callable[[], None]] = [] self._is_running = False self.future: Optional[Future[_AppResult]] = None self.loop: Optional[AbstractEventLoop] = None self.context: Optional[contextvars.Context] = None #: Quoted insert. This flag is set if we go into quoted insert mode. self.quoted_insert = False #: Vi state. (For Vi key bindings.) self.vi_state = ViState() self.emacs_state = EmacsState() #: When to flush the input (For flushing escape keys.) This is important #: on terminals that use vt100 input. We can't distinguish the escape #: key from for instance the left-arrow key, if we don't know what follows #: after "\x1b". This little timer will consider "\x1b" to be escape if #: nothing did follow in this time span. #: This seems to work like the `ttimeoutlen` option in Vim. self.ttimeoutlen = .5 # Seconds. #: Like Vim's `timeoutlen` option. This can be `None` or a float. For #: instance, suppose that we have a key binding AB and a second key #: binding A. If the uses presses A and then waits, we don't handle #: this binding yet (unless it was marked 'eager'), because we don't #: know what will follow. This timeout is the maximum amount of time #: that we wait until we call the handlers anyway. Pass `None` to #: disable this timeout. self.timeoutlen = 1.0 #: The `Renderer` instance. # Make sure that the same stdout is used, when a custom renderer has been passed. self._merged_style = self._create_merged_style(include_default_pygments_style) self.renderer = Renderer( self._merged_style, self.output, self.input, full_screen=full_screen, mouse_support=mouse_support, cpr_not_supported_callback=self.cpr_not_supported_callback) #: Render counter. This one is increased every time the UI is rendered. #: It can be used as a key for caching certain information during one #: rendering. self.render_counter = 0 # Invalidate flag. When 'True', a repaint has been scheduled. self._invalidated = False self._invalidate_events: List[Event[object]] = [] # Collection of 'invalidate' Event objects. self._last_redraw_time = 0.0 # Unix timestamp of last redraw. Used when # `min_redraw_interval` is given. #: The `InputProcessor` instance. self.key_processor = KeyProcessor(_CombinedRegistry(self)) # If `run_in_terminal` was called. This will point to a `Future` what will be # set at the point when the previous run finishes. self._running_in_terminal = False self._running_in_terminal_f: Optional[Future[None]] = None # Trigger initialize callback. self.reset()
def __init__(self, text: str = '', multiline: FilterOrBool = True, password: FilterOrBool = False, lexer: Optional[Lexer] = None, auto_suggest: Optional[AutoSuggest] = None, completer: Optional[Completer] = None, complete_while_typing: FilterOrBool = True, accept_handler: Optional[BufferAcceptHandler] = None, history: Optional[History] = None, focusable: FilterOrBool = True, focus_on_click: FilterOrBool = False, wrap_lines: FilterOrBool = True, read_only: FilterOrBool = False, width: AnyDimension = None, height: AnyDimension = None, dont_extend_height: FilterOrBool = False, dont_extend_width: FilterOrBool = False, line_numbers: bool = False, get_line_prefix: Optional[GetLinePrefixCallable] = None, scrollbar: bool = False, style: str = '', search_field: Optional[SearchToolbar] = None, preview_search: FilterOrBool = True, prompt: AnyFormattedText = '', input_processors: Optional[List[Processor]] = None) -> None: if search_field is None: search_control = None elif isinstance(search_field, SearchToolbar): search_control = search_field.control if input_processors is None: input_processors = [] # Writeable attributes. self.completer = completer self.complete_while_typing = complete_while_typing self.lexer = lexer self.auto_suggest = auto_suggest self.read_only = read_only self.wrap_lines = wrap_lines self.buffer = Buffer( document=Document(text, 0), multiline=multiline, read_only=Condition(lambda: is_true(self.read_only)), completer=DynamicCompleter(lambda: self.completer), complete_while_typing=Condition( lambda: is_true(self.complete_while_typing)), auto_suggest=DynamicAutoSuggest(lambda: self.auto_suggest), accept_handler=accept_handler, history=history) self.control = BufferControl( buffer=self.buffer, lexer=DynamicLexer(lambda: self.lexer), input_processors=[ ConditionalProcessor( AppendAutoSuggestion(), has_focus(self.buffer) & ~is_done), ConditionalProcessor( processor=PasswordProcessor(), filter=to_filter(password) ), BeforeInput(prompt, style='class:text-area.prompt'), ] + input_processors, search_buffer_control=search_control, preview_search=preview_search, focusable=focusable, focus_on_click=focus_on_click) if multiline: if scrollbar: right_margins = [ScrollbarMargin(display_arrows=True)] else: right_margins = [] if line_numbers: left_margins = [NumberedMargin()] else: left_margins = [] else: height = D.exact(1) left_margins = [] right_margins = [] style = 'class:text-area ' + style self.window = Window( height=height, width=width, dont_extend_height=dont_extend_height, dont_extend_width=dont_extend_width, content=self.control, style=style, wrap_lines=Condition(lambda: is_true(self.wrap_lines)), left_margins=left_margins, right_margins=right_margins, get_line_prefix=get_line_prefix)
def __init__(self, key_bindings, filter=True): assert isinstance(key_bindings, KeyBindingsBase) _Proxy.__init__(self) self.key_bindings = key_bindings self.filter = to_filter(filter)