Пример #1
0
    def enter_history(self):
        """
        Display the history.
        """
        app = get_app()
        app.vi_state.input_mode = InputMode.NAVIGATION

        def done(f):
            result = f.result()
            if result is not None:
                self.default_buffer.text = result

            app.vi_state.input_mode = InputMode.INSERT

        history = History(self, self.default_buffer.document)

        future = run_coroutine_in_terminal(history.app.run_async)
        future.add_done_callback(done)
Пример #2
0
    def enter_history(self):
        """
        Display the history.
        """
        app = get_app()
        app.vi_state.input_mode = InputMode.NAVIGATION

        def done(f):
            result = f.result()
            if result is not None:
                self.default_buffer.text = result

            app.vi_state.input_mode = InputMode.INSERT

        history = History(self, self.default_buffer.document)

        future = run_coroutine_in_terminal(history.app.run_async)
        future.add_done_callback(done)
Пример #3
0
def run_shell_command(command):
    def run_command():
        if not command:
            sys.stdout.write("\n")
            return

        try:
            if sys.platform.startswith('win'):
                cmd_list = command.strip().split(" ", 1)
            else:
                cmd_list = shlex.split(command)
        except Exception as e:
            print(e)
            sys.stdout.write("\n")
            return

        if cmd_list[0] == "cd":
            if len(cmd_list) != 2:
                sys.stdout.write("cd method takes one argument\n\n")
                return
            try:
                path = cmd_list[1].strip()
                if path == "-":
                    oldpwd = os.environ[
                        "OLDPWD"] if "OLDPWD" in os.environ else os.getcwd()
                    os.environ["OLDPWD"] = os.getcwd()
                    os.chdir(oldpwd)
                else:
                    if sys.platform.startswith('win'):
                        path = path.replace("\\", "/")
                        if path.startswith('"') and path.endswith('"'):
                            path = path[1:-1]

                    path = os.path.expanduser(path)
                    path = os.path.expandvars(path)
                    os.environ["OLDPWD"] = os.getcwd()
                    os.chdir(path)

                sys.stdout.write(os.getcwd())
                sys.stdout.write("\n\n")
            except Exception as e:
                print(e)
                sys.stdout.write("\n")
                return

        else:
            if sys.platform.startswith('win'):
                p = subprocess.Popen(command,
                                     shell=True,
                                     stdin=sys.stdin,
                                     stdout=sys.stdout)
            else:
                shell = os.path.basename(os.environ.get("SHELL", "/bin/sh"))
                p = subprocess.Popen([shell, "-c", command],
                                     stdin=sys.stdin,
                                     stdout=sys.stdout)

            p.wait()
            sys.stdout.write("\n")

    return run_coroutine_in_terminal(lambda: run_in_executor(run_command))
def _display_completions_like_readline(app, completions):
    """
    Display the list of completions in columns above the prompt.
    This will ask for a confirmation if there are too many completions to fit
    on a single page and provide a paginator to walk through them.
    """
    from prompt_toolkit.shortcuts.prompt import create_confirm_session
    from prompt_toolkit.formatted_text import to_formatted_text
    assert isinstance(completions, list)

    # Get terminal dimensions.
    term_size = app.output.get_size()
    term_width = term_size.columns
    term_height = term_size.rows

    # Calculate amount of required columns/rows for displaying the
    # completions. (Keep in mind that completions are displayed
    # alphabetically column-wise.)
    max_compl_width = min(
        term_width,
        max(get_cwidth(c.display_text) for c in completions) + 1)
    column_count = max(1, term_width // max_compl_width)
    completions_per_page = column_count * (term_height - 1)
    page_count = int(math.ceil(len(completions) / float(completions_per_page)))

    # Note: math.ceil can return float on Python2.

    def display(page):
        # Display completions.
        page_completions = completions[page * completions_per_page:(page + 1) *
                                       completions_per_page]

        page_row_count = int(
            math.ceil(len(page_completions) / float(column_count)))
        page_columns = [
            page_completions[i * page_row_count:(i + 1) * page_row_count]
            for i in range(column_count)
        ]

        result = []  # FormattedText list: (style,text) tuples.

        for r in range(page_row_count):
            for c in range(column_count):
                try:
                    completion = page_columns[c][r]
                    style = 'class:readline-like-completions.completion ' + (
                        completion.style or '')

                    result.extend(
                        to_formatted_text(completion.display, style=style))

                    # Add padding.
                    padding = max_compl_width - get_cwidth(
                        completion.display_text)
                    result.append((
                        completion.style,
                        ' ' * padding,
                    ))
                except IndexError:
                    pass
            result.append(('', '\n'))

        app.print_text(
            to_formatted_text(result, 'class:readline-like-completions'))

    # User interaction through an application generator function.
    def run_compl():
        " Coroutine. "
        if len(completions) > completions_per_page:
            # Ask confirmation if it doesn't fit on the screen.
            confirm = yield create_confirm_session(
                'Display all {} possibilities?'.format(
                    len(completions)), ).prompt(async_=True)

            if confirm:
                # Display pages.
                for page in range(page_count):
                    display(page)

                    if page != page_count - 1:
                        # Display --MORE-- and go to the next page.
                        show_more = yield _create_more_session(
                            '--MORE--').prompt(async_=True)

                        if not show_more:
                            return
            else:
                app.output.flush()
        else:
            # Display all completions.
            display(0)

    run_coroutine_in_terminal(run_compl, render_cli_done=True)
def _display_completions_like_readline(app, completions):
    """
    Display the list of completions in columns above the prompt.
    This will ask for a confirmation if there are too many completions to fit
    on a single page and provide a paginator to walk through them.
    """
    from prompt_toolkit.shortcuts.prompt import create_confirm_session
    from prompt_toolkit.formatted_text import to_formatted_text
    assert isinstance(completions, list)

    # Get terminal dimensions.
    term_size = app.output.get_size()
    term_width = term_size.columns
    term_height = term_size.rows

    # Calculate amount of required columns/rows for displaying the
    # completions. (Keep in mind that completions are displayed
    # alphabetically column-wise.)
    max_compl_width = min(term_width,
        max(get_cwidth(c.display_text) for c in completions) + 1)
    column_count = max(1, term_width // max_compl_width)
    completions_per_page = column_count * (term_height - 1)
    page_count = int(math.ceil(len(completions) / float(completions_per_page)))
        # Note: math.ceil can return float on Python2.

    def display(page):
        # Display completions.
        page_completions = completions[page * completions_per_page:
                                       (page + 1) * completions_per_page]

        page_row_count = int(math.ceil(len(page_completions) / float(column_count)))
        page_columns = [page_completions[i * page_row_count:(i + 1) * page_row_count]
                   for i in range(column_count)]

        result = []  # FormattedText list: (style,text) tuples.

        for r in range(page_row_count):
            for c in range(column_count):
                try:
                    completion = page_columns[c][r]
                    style = 'class:readline-like-completions.completion ' + (completion.style or '')

                    result.extend(to_formatted_text(completion.display, style=style))

                    # Add padding.
                    padding = max_compl_width - get_cwidth(completion.display_text)
                    result.append((completion.style, ' ' * padding,))
                except IndexError:
                    pass
            result.append(('', '\n'))

        app.print_text(to_formatted_text(result, 'class:readline-like-completions'))

    # User interaction through an application generator function.
    def run_compl():
        " Coroutine. "
        if len(completions) > completions_per_page:
            # Ask confirmation if it doesn't fit on the screen.
            confirm = yield create_confirm_session(
                'Display all {} possibilities?'.format(len(completions)),
                ).prompt(async_=True)

            if confirm:
                # Display pages.
                for page in range(page_count):
                    display(page)

                    if page != page_count - 1:
                        # Display --MORE-- and go to the next page.
                        show_more = yield _create_more_session('--MORE--').prompt(async_=True)

                        if not show_more:
                            return
            else:
                app.output.flush()
        else:
            # Display all completions.
            display(0)

    run_coroutine_in_terminal(run_compl, render_cli_done=True)