def get_completions(self, document, complete_event): editor = self._editor_ref() location = self._editor_buffer_ref().location or '.txt' # Select completer. if location.endswith('.py') and editor.enable_jedi: completer = PythonCompleter(lambda: globals(), lambda: {}) else: completer = DocumentWordsCompleter() # Call completer. return completer.get_completions(document, complete_event)
def _get_input(self): """ Read PDB input. Return input text. """ # Reset multiline/paste mode every time. self.python_input.paste_mode = False self.python_input.currently_multiline = False # Set source code document. self._show_source_code(self.curframe.f_code.co_filename) self.cli.buffers[DEFAULT_BUFFER].document = Document('') # Select the current frame of the stack. for i, (frame, lineno) in enumerate(self.stack): if frame is self.curframe: self.callstack_selected_frame = i break # Set up a new completer and validator for the new grammar. g = self._create_grammar() self.completer = GrammarCompleter( g, completers={ 'enabled_breakpoint': BreakPointListCompleter(only_enabled=True), 'disabled_breakpoint': BreakPointListCompleter(only_disabled=True), 'alias_name': AliasCompleter(self), 'python_code': PythonCompleter(lambda: self.curframe.f_globals, lambda: self.curframe.f_locals), 'breakpoint': BreakPointListCompleter(), 'pdb_command': PdbCommandsCompleter(self), 'python_file': PythonFileCompleter(), 'python_function': PythonFunctionCompleter(self), }) self.validator = GrammarValidator(g, {'python_code': PythonValidator()}) # Make sure not to start in Vi navigation mode. self.python_input.key_bindings_manager.reset(self.cli) self.cli.buffers[DEFAULT_BUFFER].reset() def pre_run(): self._source_code_window.vertical_scroll = 100000 # source_code_doc.line_count try: return self.cli.run(reset_current_buffer=False, pre_run=pre_run).text except EOFError: # Turn Control-D key press into a 'quit' command. return 'quit'
class myCompleter(Completer): def __init__(self, bot): self.pythoncompleter = PythonCompleter(globals, locals) self.bot = bot def get_completions(self, document, complete_event): if document.text.startswith("#"): return WordCompleter(chain(self.bot.commands, self.bot.aliases)).get_completions( document, complete_event) else: return self.pythoncompleter.get_completions( document, complete_event)
def prompt_python(msg: str, get_globals: t.Callable[[str], t.Any], get_locals: t.Callable[[str], t.Any]) -> str: """ Prompt for python code. :param get_globals: function that returns the global variables :param get_locals: function that returns the local variables :return: user input """ from ptpython.completer import PythonCompleter from pygments.lexers.python import Python3Lexer python_completer = PythonCompleter(get_globals, get_locals) return prompt(msg, multiline=True, mouse_support=True, lexer=PygmentsLexer(Python3Lexer), completer=python_completer)
def run_repl_loop(db, data_path): history = FileHistory(str(data_path / 'history')) glos = {} locs = {'db': db} def get_locals(): return locs def get_globals(): return glos while True: try: inp = get_input( '>>> ', completer=PythonCompleter( get_locals=get_locals, get_globals=get_globals, ), history=history, lexer=PythonLexer, ) except KeyboardInterrupt: continue except EOFError: break result = None try: result = eval(inp, glos, locs) except SyntaxError: try: six.exec_(inp, glos, locs) except: print_exc(chain=False) except SystemExit: break except: print_exc(chain=False) if result is None: pass # HACK: Eval iterators automatically so that find() calls and others # return the result without iterating manually. # TODO: Find a better solution for this. elif (six.PY3 and hasattr(result, '__next__') or six.PY2 and hasattr(result, 'next')): output([x for x in result]) else: output(result)
def __init__(self, bot): self.pythoncompleter = PythonCompleter(globals, locals) self.bot = bot
def __init__( self, eventloop, get_globals=None, get_locals=None, stdin=None, stdout=None, vi_mode=False, history_filename=None, style=PythonStyle, # For internal use. _completer=None, _validator=None, _lexer=None, _python_prompt_control=None, _extra_buffers=None, _extra_buffer_processors=None, _extra_sidebars=None): self.settings = PythonCLISettings() self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self.completer = _completer or PythonCompleter(self.get_globals, self.get_locals) self.validator = _validator or PythonValidator() self.history = FileHistory( history_filename) if history_filename else History() self.python_prompt_control = _python_prompt_control or PythonPrompt( self.settings) self._extra_sidebars = _extra_sidebars or [] self._extra_buffer_processors = _extra_buffer_processors or [] self._lexer = _lexer or PythonLexer # Use a KeyBindingManager for loading the key bindings. self.key_bindings_manager = KeyBindingManager( enable_vi_mode=vi_mode, enable_open_in_editor=True, enable_system_prompt=True) load_python_bindings(self.key_bindings_manager, self.settings) self.get_signatures_thread_running = False buffers = { 'default': self._create_python_buffer(), 'docstring': Buffer(), # XXX: make docstring read only. } buffers.update(_extra_buffers or {}) self.cli = CommandLineInterface( eventloop=eventloop, style=style, key_bindings_registry=self.key_bindings_manager.registry, buffers=buffers, paste_mode=Condition(lambda cli: self.settings.paste_mode), layout=self._create_layout(), on_abort=AbortAction.RETRY, on_exit=AbortAction.RAISE_EXCEPTION) def on_input_timeout(): """ When there is no input activity, in another thread, get the signature of the current code. """ if self.cli.focus_stack.current != 'default': return # Never run multiple get-signature threads. if self.get_signatures_thread_running: return self.get_signatures_thread_running = True buffer = self.cli.current_buffer document = buffer.document def run(): script = get_jedi_script_from_document(document, self.get_locals(), self.get_globals()) # Show signatures in help text. if script: try: signatures = script.call_signatures() except ValueError: # e.g. in case of an invalid \\x escape. signatures = [] except Exception: # Sometimes we still get an exception (TypeError), because # of probably bugs in jedi. We can silence them. # See: https://github.com/davidhalter/jedi/issues/492 signatures = [] else: signatures = [] self.get_signatures_thread_running = False # Set signatures and redraw if the text didn't change in the # meantime. Otherwise request new signatures. if buffer.text == document.text: self.settings.signatures = signatures # Set docstring in docstring buffer. if signatures: string = signatures[0].docstring() if not isinstance(string, six.text_type): string = string.decode('utf-8') self.cli.buffers['docstring'].reset( initial_document=Document(string, cursor_position=0)) else: self.cli.buffers['docstring'].reset() self.cli.request_redraw() else: on_input_timeout() self.cli.eventloop.run_in_executor(run) def reset(): self.key_bindings_manager.reset() self.settings.signatures = [] self.cli.onReset += reset self.cli.onInputTimeout += on_input_timeout
def __init__(self, get_globals=None, get_locals=None, history_filename=None, vi_mode=False, # For internal use. _completer=None, _validator=None, _lexer=None, _extra_buffers=None, _extra_buffer_processors=None, _on_start=None, _extra_layout_body=None, _extra_toolbars=None, _input_buffer_height=None, _accept_action=AcceptAction.RETURN_DOCUMENT, _on_exit=AbortAction.RAISE_EXCEPTION): self.get_globals = get_globals or (lambda: {}) self.get_locals = get_locals or self.get_globals self._completer = _completer or PythonCompleter(self.get_globals, self.get_locals) self._validator = _validator or PythonValidator(self.get_compiler_flags) self.history = FileHistory(history_filename) if history_filename else InMemoryHistory() self._lexer = _lexer or PygmentsLexer(PythonLexer) self._extra_buffers = _extra_buffers self._accept_action = _accept_action self._on_exit = _on_exit self._on_start = _on_start self._input_buffer_height = _input_buffer_height self._extra_layout_body = _extra_layout_body or [] self._extra_toolbars = _extra_toolbars or [] self._extra_buffer_processors = _extra_buffer_processors or [] # Settings. self.show_signature = False self.show_docstring = False self.show_meta_enter_message = True self.completion_visualisation = CompletionVisualisation.MULTI_COLUMN self.completion_menu_scroll_offset = 1 self.show_line_numbers = False self.show_status_bar = True self.wrap_lines = True self.complete_while_typing = True self.vi_mode = vi_mode self.paste_mode = False # When True, don't insert whitespace after newline. self.confirm_exit = True # Ask for confirmation when Control-D is pressed. self.accept_input_on_enter = 2 # Accept when pressing Enter 'n' times. # 'None' means that meta-enter is always required. self.enable_open_in_editor = True self.enable_system_bindings = True self.enable_input_validation = True self.enable_auto_suggest = False self.enable_mouse_support = False self.enable_history_search = False # When True, like readline, going # back in history will filter the # history on the records starting # with the current input. self.highlight_matching_parenthesis = False self.show_sidebar = False # Currently show the sidebar. self.show_sidebar_help = True # When the sidebar is visible, also show the help text. self.show_exit_confirmation = False # Currently show 'Do you really want to exit?' self.terminal_title = None # The title to be displayed in the terminal. (None or string.) self.exit_message = 'Do you really want to exit?' # Tokens to be shown at the prompt. self.prompt_style = 'classic' # The currently active style. self.all_prompt_styles = { # Styles selectable from the menu. 'ipython': IPythonPrompt(self), 'classic': ClassicPrompt(), } self.get_input_prompt_tokens = lambda cli: \ self.all_prompt_styles[self.prompt_style].in_tokens(cli) self.get_output_prompt_tokens = lambda cli: \ self.all_prompt_styles[self.prompt_style].out_tokens(cli) #: Load styles. self.code_styles = get_all_code_styles() self.ui_styles = get_all_ui_styles() self._current_code_style_name = 'default' self._current_ui_style_name = 'default' if is_windows(): self._current_code_style_name = 'win32' self._current_style = self._generate_style() self.true_color = False # Options to be configurable from the sidebar. self.options = self._create_options() self.selected_option_index = 0 #: Incremeting integer counting the current statement. self.current_statement_index = 1 # Code signatures. (This is set asynchronously after a timeout.) self.signatures = [] # Use a KeyBindingManager for loading the key bindings. self.key_bindings_manager = KeyBindingManager( enable_abort_and_exit_bindings=True, enable_search=True, enable_vi_mode=Condition(lambda cli: self.vi_mode), enable_open_in_editor=Condition(lambda cli: self.enable_open_in_editor), enable_system_bindings=Condition(lambda cli: self.enable_system_bindings), enable_auto_suggest_bindings=Condition(lambda cli: self.enable_auto_suggest), # Disable all default key bindings when the sidebar or the exit confirmation # are shown. enable_all=Condition(lambda cli: not (self.show_sidebar or self.show_exit_confirmation))) load_python_bindings(self.key_bindings_manager, self) load_sidebar_bindings(self.key_bindings_manager, self) load_confirm_exit_bindings(self.key_bindings_manager, self) # Boolean indicating whether we have a signatures thread running. # (Never run more than one at the same time.) self._get_signatures_thread_running = False
def __init__(self, kernel): self.completers = [ SoS_MagicsCompleter(kernel), SoS_PathCompleter(), PythonCompleter(lambda: env.sos_dict._dict, lambda: env.sos_dict._dict), ]