Ejemplo n.º 1
0
    def print_tokens(tokens, style=None, true_color=False):
        """
        Print a list of (Token, text) tuples in the given style to the output.
        E.g.::
            style = PygmentsStyle.from_defaults(style_dict={
                Token.Hello: '#ff0066',
                Token.World: '#884444 italic',
            })
            tokens = [
                (Token.Hello, 'Hello'),
                (Token.World, 'World'),
            ]
            print_tokens(tokens, style=style)
        :param tokens: List of ``(Token, text)`` tuples.
        :param style: :class:`.Style` instance for the color scheme.
        :param true_color: When True, use 24bit colors instead of 256 colors.

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        This is deprecated and slated for removal after a prompt-toolkit
        v0.57+ release.
        """
        assert isinstance(style, Style)
        output = create_output(true_color=true_color)
        renderer_print_tokens(output, tokens, style)
Ejemplo n.º 2
0
    def init_prompt_toolkit_cli(self):
        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():
                isp = self.input_splitter
                prompt_text = "".join(x[1] for x in self.prompts.in_prompt_tokens())
                prompt_continuation = "".join(x[1] for x in self.prompts.continuation_prompt_tokens())
                while isp.push_accepts_more():
                    line = cast_unicode_py2(input(prompt_text))
                    isp.push(line)
                    prompt_text = prompt_continuation
                return isp.source_reset()
            self.prompt_for_code = prompt
            return

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt(
            enable_open_in_editor=self.extra_open_editor_shortcuts,
        )
        register_ipython_shortcuts(kbmanager.registry, self)

        # 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)
                last_cell = cell

        self._style = self._make_style_from_name_or_cls(self.highlighting_style)
        self.style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        def patch_stdout(**kwargs):
            return self.pt_cli.patch_stdout_context(**kwargs)

        self._pt_app = create_prompt_application(
                            editing_mode=editing_mode,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(shell=self,
                                                    patch_stdout=patch_stdout),
                            enable_history_search=True,
                            style=self.style,
                            mouse_support=self.mouse_support,
                            **self._layout_options()
        )
        self._eventloop = create_eventloop(self.inputhook)
        self.pt_cli = CommandLineInterface(
            self._pt_app, eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))
Ejemplo n.º 3
0
def loop(cmd, history_file):
    key_binding_manager = KeyBindingManager(
        enable_search=True,
        enable_abort_and_exit_bindings=True
    )
    layout = create_prompt_layout(
        message=u'cr> ',
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ]
    )
    buffer = CrashBuffer(
        history=TruncatedFileHistory(history_file, max_length=MAX_HISTORY_LENGTH),
        accept_action=AcceptAction.RETURN_DOCUMENT,
        completer=SQLCompleter(cmd)
    )
    buffer.complete_while_typing = lambda cli=None: cmd.should_autocomplete()
    application = Application(
        layout=layout,
        buffer=buffer,
        style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle),
        key_bindings_registry=key_binding_manager.registry,
        editing_mode=_get_editing_mode(),
        on_exit=AbortAction.RAISE_EXCEPTION,
        on_abort=AbortAction.RETRY,
    )
    eventloop = create_eventloop()
    output = create_output()
    cli = CommandLineInterface(
        application=application,
        eventloop=eventloop,
        output=output
    )

    def get_num_columns_override():
        return output.get_size().columns
    cmd.get_num_columns = get_num_columns_override

    while True:
        try:
            doc = cli.run(reset_current_buffer=True)
            if doc:
                cmd.process(doc.text)
        except KeyboardInterrupt:
            cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it")
        except EOFError:
            cmd.logger.warn(u'Bye!')
            return
Ejemplo n.º 4
0
    def __init__(self, eventloop=None, python_input=None, input=None, output=None):
        assert python_input is None or isinstance(python_input, PythonInput)

        python_input = python_input or PythonInput()

        # Make sure that the prompt_toolkit 'renderer' knows about the
        # 'true_color' property of PythonInput.
        if output is None:
            output=create_output(true_color=Condition(lambda: python_input.true_color))

        super(PythonCommandLineInterface, self).__init__(
            application=python_input.create_application(),
            eventloop=eventloop,
            input=input,
            output=output)
Ejemplo n.º 5
0
    def init_prompt_toolkit_cli(self):
        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

        # Set up keyboard shortcuts
        kbmanager = KeyBindingManager.for_prompt()
        register_ipython_shortcuts(kbmanager.registry, self)

        # 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)
                last_cell = cell

        self._style = self._make_style_from_name_or_cls(self.highlighting_style)
        style = DynamicStyle(lambda: self._style)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())

        self._pt_app = create_prompt_application(
                            editing_mode=editing_mode,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=IPythonPTCompleter(shell=self),
                            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._pt_app, eventloop=self._eventloop,
            output=create_output(true_color=self.true_color))
Ejemplo n.º 6
0
def RunApplication(app):
  """Run a prompt_toolkit Application."""

  eventloop = shortcuts.create_eventloop()

  # Create CommandLineInterface.
  cli = interface.CommandLineInterface(
      application=app, eventloop=eventloop, output=shortcuts.create_output())

  # Note: We pass `reset_current_buffer=False`, because that way it's easy to
  #       give DEFAULT_BUFFER a default value, without it getting erased. We
  #       don't have to reset anyway, because this is the first and only time
  #       that this CommandLineInterface will run.
  try:
    result = cli.run(reset_current_buffer=False)

    if isinstance(result, document.Document):  # Backwards-compatibility.
      return result.text
    return result
  finally:
    eventloop.close()
Ejemplo n.º 7
0
        def _process_input(self, reactor):
            self._print_startup_message()
            while self._ready.wait(0.5) != True:
                if not reactor.is_running():
                    return

            while True:
                expression = ""
                line = ""
                while len(expression) == 0 or line.endswith("\\"):
                    if not reactor.is_running():
                        return
                    try:
                        prompt = "[%s]" % self._prompt_string + "-> " if len(expression) == 0 else "... "

                        # We create the prompt manually instead of using get_input,
                        # so we can use the cli in the _on_stop method
                        eventloop = create_eventloop()

                        self._cli = CommandLineInterface(
                            application=create_prompt_application(prompt, history=self._history, completer=self._completer, lexer=JavascriptLexer),
                            eventloop=eventloop,
                            output=create_output())

                        try:
                            line = None

                            document = self._cli.run()

                            if document:
                                line = document.text
                        finally:
                            eventloop.close()
                    except EOFError:
                        # An extra newline after EOF to exit the REPL cleanly
                        self._print("\nThank you for using Frida!")
                        return
                    except KeyboardInterrupt:
                        line = ""
                        continue
                    if len(line.strip()) > 0:
                        if len(expression) > 0:
                            expression += "\n"
                        expression += line.rstrip("\\")

                if expression.endswith("?"):
                    try:
                        self._print_help(expression)
                    except JavaScriptError as e:
                        error = e.error
                        self._print(Fore.RED + Style.BRIGHT + error['name'] + Style.RESET_ALL + ": " + error['message'])
                    except frida.InvalidOperationError:
                        return
                elif expression.startswith("%"):
                    self._do_magic(expression[1:].rstrip())
                elif expression in ("exit", "quit", "q"):
                    self._print("Thank you for using Frida!")
                    return
                elif expression == "help":
                    self._print("Help: #TODO :)")
                else:
                    self._eval_and_print(expression)
Ejemplo n.º 8
0
    def prompt(self, message="", **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop("patch_stdout", False)
        return_asyncio_coroutine = kwargs.pop("return_asyncio_coroutine", False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop("eventloop", None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if builtins.__xonsh__.env.get("VI_MODE"):
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS
            kwargs["editing_mode"] = editing_mode
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output(),
            )
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {"patch_context": patch_context, "cli": cli}
            exec(
                textwrap.dedent(
                    """
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            """
                ),
                exec_context,
            )
            return exec_context["prompt_coro"]()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)
                    if document:
                        return document.text
            except Exception:
                xt.print_exception()
                # return something to prevent xonsh crash when any
                # exceptions raise
                return ""
            finally:
                eventloop.close()
Ejemplo n.º 9
0
Archivo: repl.py Proyecto: crate/crash
def loop(cmd, history_file):

    key_binding_manager = KeyBindingManager(
        enable_search=True,
        enable_abort_and_exit_bindings=True,
        enable_system_bindings=True,
        enable_open_in_editor=True
    )
    bind_keys(key_binding_manager.registry)
    layout = create_layout(
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda cli: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda cli: [(Token.Prompt, 'cr> ')]
    )
    application = Application(
        layout=layout,
        buffer=create_buffer(cmd, history_file),
        style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle),
        key_bindings_registry=key_binding_manager.registry,
        editing_mode=_get_editing_mode(),
        on_exit=AbortAction.RAISE_EXCEPTION,
        on_abort=AbortAction.RETRY,
    )
    eventloop = create_eventloop()
    output = create_output()
    cli = CommandLineInterface(
        application=application,
        eventloop=eventloop,
        output=output
    )

    def get_num_columns_override():
        return output.get_size().columns
    cmd.get_num_columns = get_num_columns_override

    while True:
        try:
            doc = cli.run(reset_current_buffer=True)
            if doc:
                cmd.process(doc.text)
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: '******'Bye!')
            return
Ejemplo n.º 10
0
  def __init__(self, cli=None, cosh=None, args=None, config=None):
    self.args = args
    self.coshell = cosh
    self.config = config
    self.key_bindings = bindings.KeyBindings(
        edit_mode=self.coshell.edit_mode == 'emacs')

    # Load the default CLI trees.
    self.root = cli_tree.LoadAll(cli=cli)

    # Add the exit command completer node to the CLI tree.
    self.root[parser.LOOKUP_COMMANDS]['exit'] = cli_tree.Node(
        command='exit',
        description='Exit the interactive shell.',
        positionals=[
            {
                'default': '0',
                'description': 'The exit status.',
                'name': 'status',
                'nargs': '?',
                'required': False,
                'value': 'STATUS',
            },
        ],
    )

    # Create the parser and completer.
    shell_parser = parser.Parser(
        self.root,
        context=config.context,
        hidden=config.hidden)
    shell_completer = completer.ShellCliCompleter(shell_parser=shell_parser,
                                                  args=args,
                                                  cosh=self.coshell,
                                                  hidden=config.hidden)

    # Make sure that complete_while_typing is disabled when
    # enable_history_search is enabled. (First convert to SimpleFilter, to
    # avoid doing bitwise operations on bool objects.)
    complete_while_typing = shortcuts.to_simple_filter(True)
    enable_history_search = shortcuts.to_simple_filter(False)
    complete_while_typing &= ~enable_history_search
    history_file = os.path.join(core_config.Paths().global_config_dir,
                                'shell_history')
    multiline = shortcuts.to_simple_filter(False)

    # Create the default buffer.

    self.default_buffer = pt_buffer.Buffer(
        enable_history_search=enable_history_search,
        complete_while_typing=complete_while_typing,
        is_multiline=multiline,
        history=pt_history.FileHistory(history_file),
        validator=None,
        completer=shell_completer,
        auto_suggest=(auto_suggest.AutoSuggestFromHistory()
                      if config.suggest else None),
        accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT,
    )

    # Create the CLI.
    self.cli = CLI(
        config=config,
        cosh=cosh,
        root=self.root,
        shell_parser=shell_parser,
        application=self._CreatePromptApplication(config=config,
                                                  multiline=multiline),
        eventloop=shortcuts.create_eventloop(),
        output=shortcuts.create_output(),
    )
    self.key_bindings.Initialize(self.cli)
Ejemplo n.º 11
0
    def prompt(self, message='', **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop('patch_stdout', False)
        return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop('eventloop', None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if self.major_minor < (0, 57):
                kwargs.pop('reserve_space_for_menu', None)
            if self.major_minor <= (0, 57):
                kwargs.pop('get_rprompt_tokens', None)
                kwargs.pop('get_continuation_tokens', None)
            # VI_Mode handling changed in prompt_toolkit v1.0
            if self.major_minor >= (1, 0):
                from prompt_toolkit.enums import EditingMode
                if builtins.__xonsh_env__.get('VI_MODE'):
                    editing_mode = EditingMode.VI
                else:
                    editing_mode = EditingMode.EMACS
                kwargs['editing_mode'] = editing_mode
                kwargs['vi_mode'] = builtins.__xonsh_env__.get('VI_MODE')
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output())
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {'patch_context': patch_context, 'cli': cli}
            exec(textwrap.dedent('''
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            '''), exec_context)
            return exec_context['prompt_coro']()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)

                    if document:
                        return document.text
            finally:
                eventloop.close()
Ejemplo n.º 12
0
def get_terminal_size():
    return create_output().get_size()
Ejemplo n.º 13
0
    def prompt(self, message='', **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop('patch_stdout', False)
        return_asyncio_coroutine = kwargs.pop('return_asyncio_coroutine', False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop('eventloop', None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if self.major_minor < (0, 57):
                kwargs.pop('reserve_space_for_menu', None)
            if self.major_minor <= (0, 57):
                kwargs.pop('get_rprompt_tokens', None)
                kwargs.pop('get_continuation_tokens', None)
            # VI_Mode handling changed in prompt_toolkit v1.0
            if self.major_minor >= (1, 0):
                from prompt_toolkit.enums import EditingMode
                if builtins.__xonsh_env__.get('VI_MODE'):
                    editing_mode = EditingMode.VI
                else:
                    editing_mode = EditingMode.EMACS

                kwargs['editing_mode'] = editing_mode
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output())
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context() if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {'patch_context': patch_context, 'cli': cli}
            exec_(textwrap.dedent('''
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            '''), exec_context)
            return exec_context['prompt_coro']()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)

                    if document:
                        return document.text
            finally:
                eventloop.close()
Ejemplo n.º 14
0
def loop(cmd, history_file):
    def session_toolbar(cli):
        return _get_toolbar_tokens(cmd.is_conn_available, cmd.username,
                                   cmd.connection.client.active_servers)

    key_binding_manager = KeyBindingManager(
        enable_search=True,
        enable_abort_and_exit_bindings=True,
        enable_system_bindings=True,
        enable_open_in_editor=True)
    bind_keys(key_binding_manager.registry)
    layout = create_layout(
        message='cr> ',
        multiline=True,
        lexer=SqlLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=session_toolbar)
    application = Application(
        layout=layout,
        buffer=create_buffer(cmd, history_file),
        style=PygmentsStyle.from_defaults(pygments_style_cls=CrateStyle),
        key_bindings_registry=key_binding_manager.registry,
        editing_mode=_get_editing_mode(),
        on_exit=AbortAction.RAISE_EXCEPTION,
        on_abort=AbortAction.RETRY,
    )
    eventloop = create_eventloop()
    output = create_output()
    cli = CommandLineInterface(application=application,
                               eventloop=eventloop,
                               output=output)

    def get_num_columns_override():
        return output.get_size().columns

    cmd.get_num_columns = get_num_columns_override

    while True:
        try:
            doc = cli.run(reset_current_buffer=True)
            if doc:
                cmd.process(doc.text)
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: '******'Bye!')
            return
Ejemplo n.º 15
0
    def read(self, prompt_str='λ く'):
        '''
        The main read eval print loop for RIPL.
        Uses prompt_toolkit:
            http://python-prompt-toolkit.readthedocs.io/en/stable/
        '''
        def exit_message():
            print('\nThanks for giving RIPL a try!\nさようなら!\n')

        if not self.global_scope:
            raise EnvironmentError('Things have gone horribly wrong...')

        print(' <({[ RIPL -- RIPL Is Pythonic Lisp ]})>\n'
              '    Ctrl-Space to enter selection mode.\n'
              '    Ctrl-W/Y to cut/paste to system clipboard.\n'
              '    Ctrl-D to exit\n')

        history = InMemoryHistory()
        completer = WordCompleter(self.completions, ignore_case=True)
        kbm = KeyBindingManager.for_prompt(enable_system_bindings=True)
        add_binding = kbm.registry.add_binding

        @add_binding(Keys.Tab, filter=Tab_to_whitespace())
        def _(event):
            '''Either indent or do completion'''
            event.cli.current_buffer.insert_text('  ')

        @add_binding(Keys.ControlJ)
        def __(event):
            '''Either enter a newline or accept input based on context'''
            b = event.current_buffer
            txt = b.document.text

            def at_end(b):
                '''Is the cursor at the end of the buffer?'''
                text = b.document.text_after_cursor
                return text == '' or (text.isspace() and '\n' not in text)

            at_end = at_end(b)
            has_empty_line = txt.replace(' ', '').endswith('\n')
            balanced = is_balanced(b.document.text)
            if (at_end and has_empty_line) or balanced:
                if b.validate():
                    b.accept_action.validate_and_handle(event.cli, b)
            else:
                newline_and_indent(b)

        # Show matching parentheses, but only while editing.
        highlight_parens = ConditionalProcessor(
            processor=HighlightMatchingBracketProcessor(
                chars='[](){}'),
            filter=~IsDone())

        while True:
            repl = create_prompt_application(
                    prompt_str,
                    multiline=True,
                    history=history,
                    style=ripl_style,
                    mouse_support=True,
                    completer=completer,
                    validator=ParenValidator(),
                    enable_history_search=True,
                    complete_while_typing=False,
                    clipboard=PyperclipClipboard(),
                    lexer=PygmentsLexer(RiplLexer),
                    key_bindings_registry=kbm.registry,
                    display_completions_in_columns=True,
                    auto_suggest=AutoSuggestFromHistory(),
                    get_continuation_tokens=self.cont_tokens,
                    extra_input_processors=[highlight_parens])

            try:
                eventloop = create_eventloop()
                cli = CommandLineInterface(
                    application=repl,
                    eventloop=eventloop,
                    output=create_output(true_color=True))

                user_input = cli.run(reset_current_buffer=False)
                if user_input:
                    if isinstance(user_input, Document):
                        user_input = user_input.text
                    lines = user_input.split('\n')
                    expression = ' '.join([l.strip() for l in lines])
                    self.eval_and_print(expression)
            except (EOFError, KeyboardInterrupt):
                # User hit Ctl+d
                exit_message()
                break
            finally:
                eventloop.close()
Ejemplo n.º 16
0
        def _process_input(self, reactor):
            if not self._quiet:
                self._print_startup_message()

            while self._ready.wait(0.5) != True:
                if not reactor.is_running():
                    return

            while True:
                expression = ""
                line = ""
                while len(expression) == 0 or line.endswith("\\"):
                    if not reactor.is_running():
                        return

                    prompt = "[%s]" % self._prompt_string + "-> " if len(
                        expression) == 0 else "... "

                    pending_eval = self._pending_eval
                    if pending_eval is not None:
                        if len(pending_eval) > 0:
                            expression = pending_eval.pop(0)
                            if not self._quiet:
                                self._print(prompt + expression)
                        else:
                            self._pending_eval = None
                    else:
                        if self._quiet:
                            self._exit_status = 0 if self._errors == 0 else 1
                            return

                        try:
                            if self._have_terminal:
                                # We create the prompt manually instead of using get_input,
                                # so we can use the cli in the _on_stop method
                                eventloop = create_eventloop()

                                self._cli = CommandLineInterface(
                                    application=create_prompt_application(
                                        prompt,
                                        history=self._history,
                                        completer=self._completer,
                                        lexer=JavascriptLexer),
                                    eventloop=eventloop,
                                    output=create_output())

                                try:
                                    line = None

                                    document = self._cli.run()

                                    if document:
                                        line = document.text
                                finally:
                                    eventloop.close()
                            else:
                                line = self._dumb_stdin_reader.read_line(
                                    prompt)
                                self._print(line)
                        except EOFError:
                            if not self._have_terminal:
                                while not self._stopping.wait(1):
                                    pass
                            return
                        except KeyboardInterrupt:
                            line = ""
                            if not self._have_terminal:
                                sys.stdout.write("\n" + prompt)
                            continue
                        if len(line.strip()) > 0:
                            if len(expression) > 0:
                                expression += "\n"
                            expression += line.rstrip("\\")

                if expression.endswith("?"):
                    try:
                        self._print_help(expression)
                    except JavaScriptError as e:
                        error = e.error
                        self._print(Fore.RED + Style.BRIGHT + error['name'] +
                                    Style.RESET_ALL + ": " + error['message'])
                    except frida.InvalidOperationError:
                        return
                elif expression.startswith("%"):
                    self._do_magic(expression[1:].rstrip())
                elif expression in ("exit", "quit", "q"):
                    return
                elif expression == "help":
                    self._print("Help: #TODO :)")
                else:
                    if not self._eval_and_print(expression):
                        self._errors += 1
Ejemplo n.º 17
0
    def init_prompt_toolkit_cli(self):
        if 'JUPYTER_CONSOLE_TEST' in os.environ:
            # Simple restricted interface for tests so we can find prompts with
            # pexpect. Multi-line input not supported.
            def prompt():
                return cast_unicode_py2(
                    input('In [%d]: ' % self.execution_count))

            self.prompt_for_code = prompt
            self.print_out_prompt = \
                lambda: print('Out[%d]: ' % self.execution_count, end='')
            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 not (d.on_last_line or d.cursor_position_row >=
                    d.line_count - d.empty_line_count_at_the_end()):
                b.newline()
                return

            more, indent = self.check_complete(d.text)

            if (not more) and b.accept_action.is_returnable:
                b.accept_action.validate_and_handle(event.cli, b)
            else:
                b.insert_text('\n' + indent)

        @kbmanager.registry.add_binding(Keys.ControlC,
                                        filter=HasFocus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        # 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)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
            Token.OutPrompt: '#ff2200',
            Token.OutPromptNum: '#ff0000 bold',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())
        langinfo = self.kernel_info.get('language_info', {})
        lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))
        app = create_prompt_application(
            multiline=True,
            editing_mode=editing_mode,
            lexer=PygmentsLexer(get_pygments_lexer(lexer)),
            get_prompt_tokens=self.get_prompt_tokens,
            get_continuation_tokens=self.get_continuation_tokens,
            key_bindings_registry=kbmanager.registry,
            history=history,
            completer=JupyterPTCompleter(self.Completer),
            enable_history_search=True,
            style=style,
        )

        self._eventloop = create_eventloop()
        self.pt_cli = CommandLineInterface(
            app,
            eventloop=self._eventloop,
            output=create_output(true_color=self.true_color),
        )
Ejemplo n.º 18
0
  def __init__(self, cosh=None, args=None, config=None):
    self.args = args
    self.coshell = cosh
    self.config = config
    self.key_bindings = bindings.KeyBindings(
        edit_mode=self.coshell.edit_mode == 'emacs')

    # Load the default CLI trees. On startup we ignore out of date trees. The
    # alternative is to regenerate them before the first prompt. This could be
    # a noticeable delay for users that accrue a lot of trees. Although ignored
    # at startup, the regen will happen on demand as the individual commands
    # are typed.
    self.root = generate_cli_trees.LoadAll(
        ignore_out_of_date=True, warn_on_exceptions=True)

    # Add the exit command completer node to the CLI tree.
    self.root[parser.LOOKUP_COMMANDS]['exit'] = cli_tree.Node(
        command='exit',
        description='Exit the interactive shell.',
        positionals=[
            {
                'default': '0',
                'description': 'The exit status.',
                'name': 'status',
                'nargs': '?',
                'required': False,
                'value': 'STATUS',
            },
        ],
    )

    # Create the parser and completer.
    interactive_parser = parser.Parser(
        self.root,
        context=config.context,
        hidden=config.hidden)
    interactive_completer = completer.InteractiveCliCompleter(
        interactive_parser=interactive_parser,
        args=args,
        cosh=self.coshell,
        hidden=config.hidden,
        manpage_generator=config.manpage_generator)

    # Make sure that complete_while_typing is disabled when
    # enable_history_search is enabled. (First convert to SimpleFilter, to
    # avoid doing bitwise operations on bool objects.)
    complete_while_typing = shortcuts.to_simple_filter(True)
    enable_history_search = shortcuts.to_simple_filter(False)
    complete_while_typing &= ~enable_history_search
    history_file = os.path.join(core_config.Paths().global_config_dir,
                                'shell_history')
    multiline = shortcuts.to_simple_filter(False)

    # Create the default buffer.

    self.default_buffer = pt_buffer.Buffer(
        enable_history_search=enable_history_search,
        complete_while_typing=complete_while_typing,
        is_multiline=multiline,
        history=pt_history.FileHistory(history_file),
        validator=None,
        completer=interactive_completer,
        auto_suggest=(auto_suggest.AutoSuggestFromHistory()
                      if config.suggest else None),
        accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT,
    )

    # Create the CLI.
    self.cli = CLI(
        config=config,
        cosh=cosh,
        root=self.root,
        interactive_parser=interactive_parser,
        application=self._CreatePromptApplication(config=config,
                                                  multiline=multiline),
        eventloop=shortcuts.create_eventloop(),
        output=shortcuts.create_output(),
    )
    self.key_bindings.Initialize(self.cli)
Ejemplo n.º 19
0
    def init_prompt_toolkit_cli(self):
        if 'JUPYTER_CONSOLE_TEST' in os.environ:
            # Simple restricted interface for tests so we can find prompts with
            # pexpect. Multi-line input not supported.
            def prompt():
                return cast_unicode_py2(input('In [%d]: ' % self.execution_count))
            self.prompt_for_code = prompt
            self.print_out_prompt = \
                lambda: print('Out[%d]: ' % self.execution_count, end='')
            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 not (d.on_last_line or d.cursor_position_row >= d.line_count
                                           - d.empty_line_count_at_the_end()):
                b.newline()
                return

            more, indent = self.check_complete(d.text)

            if (not more) and b.accept_action.is_returnable:
                b.accept_action.validate_and_handle(event.cli, b)
            else:
                b.insert_text('\n' + indent)

        @kbmanager.registry.add_binding(Keys.ControlC, filter=HasFocus(DEFAULT_BUFFER))
        def _(event):
            event.current_buffer.reset()

        # 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)

        style_overrides = {
            Token.Prompt: '#009900',
            Token.PromptNum: '#00ff00 bold',
            Token.OutPrompt: '#ff2200',
            Token.OutPromptNum: '#ff0000 bold',
        }
        if self.highlighting_style:
            style_cls = get_style_by_name(self.highlighting_style)
        else:
            style_cls = get_style_by_name('default')
            # The default theme needs to be visible on both a dark background
            # and a light background, because we can't tell what the terminal
            # looks like. These tweaks to the default theme help with that.
            style_overrides.update({
                Token.Number: '#007700',
                Token.Operator: 'noinherit',
                Token.String: '#BB6622',
                Token.Name.Function: '#2080D0',
                Token.Name.Class: 'bold #2080D0',
                Token.Name.Namespace: 'bold #2080D0',
            })
        style_overrides.update(self.highlighting_style_overrides)
        style = PygmentsStyle.from_defaults(pygments_style_cls=style_cls,
                                            style_dict=style_overrides)

        editing_mode = getattr(EditingMode, self.editing_mode.upper())
        langinfo = self.kernel_info.get('language_info', {})
        lexer = langinfo.get('pygments_lexer', langinfo.get('name', 'text'))
        app = create_prompt_application(multiline=True,
                            editing_mode=editing_mode,
                            lexer=PygmentsLexer(get_pygments_lexer(lexer)),
                            get_prompt_tokens=self.get_prompt_tokens,
                            get_continuation_tokens=self.get_continuation_tokens,
                            key_bindings_registry=kbmanager.registry,
                            history=history,
                            completer=JupyterPTCompleter(self.Completer),
                            enable_history_search=True,
                            style=style,
        )

        self._eventloop = create_eventloop()
        self.pt_cli = CommandLineInterface(app,
                            eventloop=self._eventloop,
                            output=create_output(true_color=self.true_color),
        )
Ejemplo n.º 20
0
    def prompt(self, message="", **kwargs):
        """Get input from the user and return it.

        This is a wrapper around a lot of prompt_toolkit functionality and
        can be a replacement for raw_input. (or GNU readline.) If you want
        to keep your history across several calls, create one
        `~prompt_toolkit.history.History instance and pass it every
        time. This function accepts many keyword arguments. Except for the
        following. they are a proxy to the arguments of
        create_prompt_application().

        Parameters
        ----------
        patch_stdout : file-like, optional
            Replace ``sys.stdout`` by a proxy that ensures that print
            statements from other threads won't destroy the prompt. (They
            will be printed above the prompt instead.)
        return_asyncio_coroutine : bool, optional
            When True, return a asyncio coroutine. (Python >3.3)

        Notes
        -----
        This method was forked from the mainline prompt-toolkit repo.
        Copyright (c) 2014, Jonathan Slenders, All rights reserved.
        """
        patch_stdout = kwargs.pop("patch_stdout", False)
        return_asyncio_coroutine = kwargs.pop("return_asyncio_coroutine",
                                              False)
        if return_asyncio_coroutine:
            eventloop = create_asyncio_eventloop()
        else:
            eventloop = kwargs.pop("eventloop", None) or create_eventloop()

        # Create CommandLineInterface.
        if self.cli is None:
            if builtins.__xonsh_env__.get("VI_MODE"):
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS
            kwargs["editing_mode"] = editing_mode
            cli = CommandLineInterface(
                application=create_prompt_application(message, **kwargs),
                eventloop=eventloop,
                output=create_output(),
            )
            self.cli = cli
        else:
            cli = self.cli

        # Replace stdout.
        patch_context = cli.patch_stdout_context(
        ) if patch_stdout else DummyContext()

        # Read input and return it.
        if return_asyncio_coroutine:
            # Create an asyncio coroutine and call it.
            exec_context = {"patch_context": patch_context, "cli": cli}
            exec(
                textwrap.dedent("""
            import asyncio
            @asyncio.coroutine
            def prompt_coro():
                with patch_context:
                    document = yield from cli.run_async(reset_current_buffer=False)
                    if document:
                        return document.text
            """),
                exec_context,
            )
            return exec_context["prompt_coro"]()
        else:
            # Note: We pass `reset_current_buffer=False`, because that way
            # it's easy to give DEFAULT_BUFFER a default value, without it
            # getting erased. We don't have to reset anyway, because this is
            # the first and only time that this CommandLineInterface will run.
            try:
                with patch_context:
                    document = cli.run(reset_current_buffer=False)
                    if document:
                        return document.text
            except Exception:
                xt.print_exception()
                # return something to prevent xonsh crash when any
                # exceptions raise
                return ""
            finally:
                eventloop.close()
Ejemplo n.º 21
0
    def __init__(self, coshell=None, args=None, config=None, debug=None):
        self.args = args
        self.coshell = coshell
        self.config = config
        self.debug = debug
        self.key_bindings = bindings.KeyBindings()
        self.key_bindings_registry = self.key_bindings.MakeRegistry()

        # Load the default CLI trees. On startup we ignore out of date trees. The
        # alternative is to regenerate them before the first prompt. This could be
        # a noticeable delay for users that accrue a lot of trees. Although ignored
        # at startup, the regen will happen on demand as the individual commands
        # are typed.
        self.root = generate_cli_trees.LoadAll(ignore_out_of_date=True,
                                               warn_on_exceptions=True)

        # Add the interactive default CLI tree nodes.

        _AddCliTreeKeywordsAndBuiltins(self.root)

        # Make sure that complete_while_typing is disabled when
        # enable_history_search is enabled. (First convert to SimpleFilter, to
        # avoid doing bitwise operations on bool objects.)
        complete_while_typing = shortcuts.to_simple_filter(True)
        enable_history_search = shortcuts.to_simple_filter(False)
        complete_while_typing &= ~enable_history_search
        history_file = os.path.join(core_config.Paths().global_config_dir,
                                    'shell_history')
        multiline = shortcuts.to_simple_filter(False)

        # Create the parser.
        interactive_parser = parser.Parser(self.root,
                                           context=config.context,
                                           hidden=config.hidden)

        # Create the completer.
        interactive_completer = completer.InteractiveCliCompleter(
            coshell=coshell,
            debug=debug,
            interactive_parser=interactive_parser,
            args=args,
            hidden=config.hidden,
            manpage_generator=config.manpage_generator)

        # Create the default buffer.
        self.default_buffer = pt_buffer.Buffer(
            enable_history_search=enable_history_search,
            complete_while_typing=complete_while_typing,
            is_multiline=multiline,
            history=pt_history.FileHistory(history_file),
            validator=None,
            completer=interactive_completer,
            auto_suggest=(auto_suggest.AutoSuggestFromHistory()
                          if config.suggest else None),
            accept_action=pt_buffer.AcceptAction.RETURN_DOCUMENT,
        )

        # Create the CLI.
        self.cli = CLI(
            config=config,
            coshell=coshell,
            debug=debug,
            root=self.root,
            interactive_parser=interactive_parser,
            interactive_completer=interactive_completer,
            application=self._CreatePromptApplication(config=config,
                                                      multiline=multiline),
            eventloop=shortcuts.create_eventloop(),
            output=shortcuts.create_output(),
        )

        # The interactive completer is friends with the CLI.
        interactive_completer.cli = self.cli

        # Initialize the bindings.
        self.key_bindings.Initialize(self.cli)
        bindings_vi.LoadViBindings(self.key_bindings_registry)
Ejemplo n.º 22
0
        def _process_input(self, reactor):
            self._print_startup_message()
            while self._ready.wait(0.5) != True:
                if not reactor.is_running():
                    return

            while True:
                expression = ""
                line = ""
                while len(expression) == 0 or line.endswith("\\"):
                    if not reactor.is_running():
                        return
                    try:
                        prompt = "[%s]" % self._prompt_string + "-> " if len(
                            expression) == 0 else "... "

                        # We create the prompt manually instead of using get_input,
                        # so we can use the cli in the _on_stop method
                        eventloop = create_eventloop()

                        self._cli = CommandLineInterface(
                            application=create_prompt_application(
                                prompt,
                                history=self._history,
                                completer=self._completer,
                                lexer=JavascriptLexer),
                            eventloop=eventloop,
                            output=create_output())

                        try:
                            line = None

                            document = self._cli.run()

                            if document:
                                line = document.text
                        finally:
                            eventloop.close()
                    except EOFError:
                        # An extra newline after EOF to exit the REPL cleanly
                        self._print("\nThank you for using Frida!")
                        return
                    except KeyboardInterrupt:
                        line = ""
                        continue
                    if len(line.strip()) > 0:
                        if len(expression) > 0:
                            expression += "\n"
                        expression += line.rstrip("\\")

                if expression.endswith("?"):
                    try:
                        self._print_help(expression)
                    except JavaScriptError as e:
                        error = e.error
                        self._print(Fore.RED + Style.BRIGHT + error['name'] +
                                    Style.RESET_ALL + ": " + error['message'])
                    except frida.InvalidOperationError:
                        return
                elif expression.startswith("%"):
                    self._do_magic(expression[1:].rstrip())
                elif expression in ("exit", "quit", "q"):
                    self._print("Thank you for using Frida!")
                    return
                elif expression == "help":
                    self._print("Help: #TODO :)")
                else:
                    self._eval_and_print(expression)