def __init__(self, min_rows=3, suggested_max_column_width=30, show_meta=True, extra_filter=True): show_meta = to_cli_filter(show_meta) extra_filter = to_cli_filter(extra_filter) # Display filter: show when there are completions but not at the point # we are returning the input. full_filter = HasCompletions() & ~IsDone() & extra_filter any_completion_has_meta = Condition(lambda cli: any( c.display_meta for c in cli.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=LayoutDimension(min=8), height=LayoutDimension(min=1)), 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 signature_toolbar(python_input): """ Return the `Layout` for the signature. """ def get_tokens(cli): result = [] append = result.append Signature = Token.Toolbar.Signature if python_input.signatures: sig = python_input.signatures[0] # Always take the first one. append((Signature, ' ')) try: append((Signature, sig.full_name)) except IndexError: # Workaround for #37: https://github.com/jonathanslenders/python-prompt-toolkit/issues/37 # See also: https://github.com/davidhalter/jedi/issues/490 return [] append((Signature.Operator, '(')) for i, p in enumerate(sig.params): # Workaround for #47: 'p' is None when we hit the '*' in the signature. # and sig has no 'index' attribute. # See: https://github.com/jonathanslenders/ptpython/issues/47 # https://github.com/davidhalter/jedi/issues/598 description = (p.description if p else '*') #or '*' sig_index = getattr(sig, 'index', 0) if i == sig_index: # Note: we use `_Param.description` instead of # `_Param.name`, that way we also get the '*' before args. append((Signature.CurrentName, str(description))) else: append((Signature, str(description))) append((Signature.Operator, ', ')) if sig.params: # Pop last comma result.pop() append((Signature.Operator, ')')) append((Signature, ' ')) return result return ConditionalContainer( content=Window( TokenListControl(get_tokens), height=LayoutDimension.exact(1)), filter= # Show only when there is a signature HasSignature(python_input) & # And there are no completions to be shown. (would cover signature pop-up.) ~(HasCompletions() & (show_completions_menu(python_input) | show_multi_column_completions_menu(python_input))) # Signature needs to be shown. & ShowSignature(python_input) & # Not done yet. ~IsDone())
def register_ipython_shortcuts(registry, shell): """Set up the prompt_toolkit keyboard shortcuts for IPython""" insert_mode = ViInsertMode() | EmacsInsertMode() # Ctrl+J == Enter, seemingly registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode))( newline_or_execute_outer(shell)) registry.add_binding(Keys.ControlBackslash)(force_exit) registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER) ))(previous_history_or_previous_completion) registry.add_binding( Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER)))(next_history_or_next_completion) registry.add_binding(Keys.ControlG, filter=(HasFocus(DEFAULT_BUFFER) & HasCompletions()))(dismiss_completion) registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))(reset_buffer) registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER))(reset_search_buffer) supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) registry.add_binding(Keys.ControlZ, filter=supports_suspend)(suspend_to_bg) # Ctrl+I == Tab registry.add_binding(Keys.ControlI, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode & cursor_in_leading_ws))(indent_buffer) registry.add_binding( Keys.ControlO, filter=(HasFocus(DEFAULT_BUFFER) & EmacsInsertMode()))(newline_with_copy_margin) if shell.display_completions == 'readlinelike': registry.add_binding( Keys.ControlI, filter=( HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode & ~cursor_in_leading_ws))(display_completions_like_readline) if sys.platform == 'win32': registry.add_binding(Keys.ControlV, filter=(HasFocus(DEFAULT_BUFFER) & ~ViMode()))(win_paste)
def __init__(self, max_height=None, extra_filter=Always()): super(CompletionsMenu, self).__init__( content=CompletionsMenuControl(), width=LayoutDimension(min=8), height=LayoutDimension(min=1, max=max_height), # Show when there are completions but not at the point we are # returning the input. filter=HasCompletions() & ~IsDone() & extra_filter)
def __init__(self, settings): super(SignatureToolbar, self).__init__( SignatureControl(settings), height=LayoutDimension.exact(1), filter= # Show only when there is a signature HasSignature(settings) & # And there are no completions to be shown. (would cover signature pop-up.) (~HasCompletions() | ~ShowCompletionsMenu(settings)) # Signature needs to be shown. & ShowSignature(settings) & # Not done yet. ~IsDone())
def __init__(self, max_height=None, scroll_offset=0, extra_filter=True, display_arrows=False): extra_filter = to_cli_filter(extra_filter) display_arrows = to_cli_filter(display_arrows) super(CompletionsMenu, self).__init__( content=Window( content=CompletionsMenuControl(), width=LayoutDimension(min=8), height=LayoutDimension(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, ), # Show when there are completions but not at the point we are # returning the input. filter=HasCompletions() & ~IsDone() & extra_filter)
def __init__(self, extra_filter=Always()): super(CompletionsToolbar, self).__init__( content=Window(CompletionsToolbarControl(), height=LayoutDimension.exact(1)), filter=HasCompletions() & ~IsDone() & extra_filter)
def init_prompt_toolkit_cli(self): self._app = None if self.simple_prompt: # Fall back to plain non-interactive output for tests. # This is very limited, and only accepts a single line. def prompt(): return cast_unicode_py2(input('In [%d]: ' % self.execution_count)) self.prompt_for_code = prompt return kbmanager = KeyBindingManager.for_prompt() insert_mode = ViInsertMode() | EmacsInsertMode() # Ctrl+J == Enter, seemingly @kbmanager.registry.add_binding(Keys.ControlJ, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode )) def _(event): b = event.current_buffer d = b.document if b.complete_state: cc = b.complete_state.current_completion if cc: b.apply_completion(cc) else: b.cancel_completion() return if not (d.on_last_line or d.cursor_position_row >= d.line_count - d.empty_line_count_at_the_end()): b.newline() return status, indent = self.input_splitter.check_complete(d.text) if (status != 'incomplete') and b.accept_action.is_returnable: b.accept_action.validate_and_handle(event.cli, b) else: b.insert_text('\n' + (' ' * (indent or 0))) @kbmanager.registry.add_binding(Keys.ControlP, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER))) def _previous_history_or_previous_completion(event): """ Control-P in vi edit mode on readline is history next, unlike default prompt toolkit. If completer is open this still select previous completion. """ event.current_buffer.auto_up() @kbmanager.registry.add_binding(Keys.ControlN, filter=(ViInsertMode() & HasFocus(DEFAULT_BUFFER))) def _next_history_or_next_completion(event): """ Control-N in vi edit mode on readline is history previous, unlike default prompt toolkit. If completer is open this still select next completion. """ event.current_buffer.auto_down() @kbmanager.registry.add_binding(Keys.ControlG, filter=( HasFocus(DEFAULT_BUFFER) & HasCompletions() )) def _dismiss_completion(event): b = event.current_buffer if b.complete_state: b.cancel_completion() @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER)) def _reset_buffer(event): b = event.current_buffer if b.complete_state: b.cancel_completion() else: b.reset() @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(SEARCH_BUFFER)) def _reset_search_buffer(event): if event.current_buffer.document.text: event.current_buffer.reset() else: event.cli.push_focus(DEFAULT_BUFFER) supports_suspend = Condition(lambda cli: hasattr(signal, 'SIGTSTP')) @kbmanager.registry.add_binding(Keys.ControlZ, filter=supports_suspend) def _suspend_to_bg(event): event.cli.suspend_to_background() @Condition def cursor_in_leading_ws(cli): before = cli.application.buffer.document.current_line_before_cursor return (not before) or before.isspace() # Ctrl+I == Tab @kbmanager.registry.add_binding(Keys.ControlI, filter=(HasFocus(DEFAULT_BUFFER) & ~HasSelection() & insert_mode & cursor_in_leading_ws )) def _indent_buffer(event): event.current_buffer.insert_text(' ' * 4) # Pre-populate history from IPython's history database history = InMemoryHistory() last_cell = u"" for __, ___, cell in self.history_manager.get_tail(self.history_load_length, include_latest=True): # Ignore blank lines and consecutive duplicates cell = cell.rstrip() if cell and (cell != last_cell): history.append(cell) self._style = self._make_style_from_name(self.highlighting_style) style = DynamicStyle(lambda: self._style) editing_mode = getattr(EditingMode, self.editing_mode.upper()) self._app = create_prompt_application( editing_mode=editing_mode, key_bindings_registry=kbmanager.registry, history=history, completer=IPythonPTCompleter(self.Completer), enable_history_search=True, style=style, mouse_support=self.mouse_support, **self._layout_options() ) self._eventloop = create_eventloop(self.inputhook) self.pt_cli = CommandLineInterface(self._app, eventloop=self._eventloop)
def ctrl_d(_): """Ctrl D quits appliaction returning 0 to sys.""" sys.exit(0) @registry.add(Keys.ControlC) def ctrl_c(_): """Ctrl C raises an exception to be caught by functions. Main prompt must exit uhu with code status 1, while subprompts must returns to main prompt. """ raise CancelPromptException('Cancelled operation.') @registry.add(Keys.Enter, filter=HasCompletions()) def enter(event): """Enter selects a completion when has completions. When there is no completion available, submit value. """ buffer = event.current_buffer state = buffer.complete_state if len(state.current_completions) == 1: state = state.go_to_index(0) buffer.apply_completion(state.current_completion) elif state.current_completion is None: buffer.complete_next() else: buffer.apply_completion(buffer.complete_state.current_completion)
def ctrl_d(_): """Ctrl D quits appliaction returning 0 to sys.""" sys.exit(0) @manager.registry.add_binding(Keys.ControlC) def ctrl_c(_): """Ctrl C raises an exception to be caught by functions. Main prompt must exit uhu with code status 1, while subprompts must returns to main prompt. """ raise CancelPromptException('Cancelled operation.') @manager.registry.add_binding(Keys.Enter, filter=HasCompletions()) def enter(event): """Enter selects a completion when has completions. When there is no completion available, submit value. """ buffer = event.current_buffer state = buffer.complete_state if len(state.current_completions) == 1: state = state.go_to_index(0) buffer.apply_completion(state.current_completion) elif state.current_completion is None: buffer.complete_next() else: buffer.apply_completion(buffer.complete_state.current_completion)