Python prompt_toolkit.lexers.PygmentsLexer() Examples

The following are 11 code examples of prompt_toolkit.lexers.PygmentsLexer(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module prompt_toolkit.lexers , or try the search function .
Example #1
Source File: sqlite-cli.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main(database):
    connection = sqlite3.connect(database)
    session = PromptSession(
        lexer=PygmentsLexer(SqlLexer), completer=sql_completer, style=style
    )

    while True:
        try:
            text = session.prompt("> ")
        except KeyboardInterrupt:
            continue  # Control-C pressed. Try again.
        except EOFError:
            break  # Control-D pressed.

        with connection:
            try:
                messages = connection.execute(text)
            except Exception as e:
                print(repr(e))
            else:
                for message in messages:
                    print(message)

    print("GoodBye!") 
Example #2
Source File: inputhook.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def main():
    # Create user interface.
    hello_world_window()

    # Enable threading in GTK. (Otherwise, GTK will keep the GIL.)
    gtk.gdk.threads_init()

    # Read input from the command line, using an event loop with this hook.
    # We use `patch_stdout`, because clicking the button will print something;
    # and that should print nicely 'above' the input line.
    with patch_stdout():
        session = PromptSession(
            "Python >>> ", inputhook=inputhook, lexer=PygmentsLexer(PythonLexer)
        )
        result = session.prompt()
    print("You said: %s" % result) 
Example #3
Source File: __init__.py    From edgedb with Apache License 2.0 5 votes vote down vote up
def _render_sdl(self, sdl: str) -> None:
        desc_doc = pt_document.Document(sdl)
        lexer = pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer)
        formatter = lexer.lex_document(desc_doc)

        for line in range(desc_doc.line_count):
            pt_shortcuts.print_formatted_text(
                pt_formatted_text.FormattedText(formatter(line)),
                style=self.style
            )
        print() 
Example #4
Source File: ipython.py    From ptpython with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_lexer():
    g = create_ipython_grammar()

    return GrammarLexer(
        g,
        lexers={
            "percent": SimpleLexer("class:pygments.operator"),
            "magic": SimpleLexer("class:pygments.keyword"),
            "filename": SimpleLexer("class:pygments.name"),
            "python": PygmentsLexer(PythonLexer),
            "system": PygmentsLexer(BashLexer),
        },
    ) 
Example #5
Source File: html-input.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    text = prompt("Enter HTML: ", lexer=PygmentsLexer(HtmlLexer))
    print("You said: %s" % text) 
Example #6
Source File: swap-light-and-dark-colors.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def main():
    swapped = [False]  # Nonlocal
    bindings = KeyBindings()

    @bindings.add("c-t")
    def _(event):
        " When ControlT has been pressed, toggle light/dark colors. "
        swapped[0] = not swapped[0]

    def bottom_toolbar():
        if swapped[0]:
            on = "on=true"
        else:
            on = "on=false"

        return (
            HTML(
                'Press <style bg="#222222" fg="#ff8888">[control-t]</style> '
                "to swap between dark/light colors. "
                '<style bg="ansiblack" fg="ansiwhite">[%s]</style>'
            )
            % on
        )

    text = prompt(
        HTML('<style fg="#aaaaaa">Give some animals</style>: '),
        completer=html_completer,
        complete_while_typing=True,
        bottom_toolbar=bottom_toolbar,
        key_bindings=bindings,
        lexer=PygmentsLexer(HtmlLexer),
        swap_light_and_dark_colors=Condition(lambda: swapped[0]),
    )
    print("You said: %s" % text) 
Example #7
Source File: lexer.py    From pyvim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def create_command_lexer():
    """
    Lexer for highlighting of the command line.
    """
    return GrammarLexer(COMMAND_GRAMMAR, lexers={
        'command': SimpleLexer('class:commandline.command'),
        'location': SimpleLexer('class:commandline.location'),
        'shell_command': PygmentsLexer(BashLexer),
    }) 
Example #8
Source File: __init__.py    From edgedb with Apache License 2.0 4 votes vote down vote up
def build_propmpt(self) -> pt_shortcuts.PromptSession:
        history = pt_history.FileHistory(
            os.path.expanduser('~/.edgedbhistory'))

        bindings = pt_key_binding.KeyBindings()
        handle = bindings.add

        @handle('f3')  # type: ignore
        def _mode_toggle(event: Any) -> None:
            self.context.toggle_query_mode()

        @handle('f4')  # type: ignore
        def _implicit_toggle(event: Any) -> None:
            self.context.toggle_implicit()

        @handle('f5')  # type: ignore
        def _introspect_toggle(event: Any) -> None:
            self.context.toggle_introspect_types()

            if self.context.introspect_types:
                self.ensure_connection()
                self.introspect_db(self.connection)
            else:
                self.context.typenames = None

        @handle('tab')  # type: ignore
        def _tab(event: Any) -> None:
            b = prompt.app.current_buffer
            before_cursor = b.document.current_line_before_cursor
            if b.text and (not before_cursor or before_cursor.isspace()):
                b.insert_text('    ')

        prompt = pt_shortcuts.PromptSession(
            lexer=pt_lexers.PygmentsLexer(eql_pygments.EdgeQLLexer),
            include_default_pygments_style=False,

            completer=pt_complete.DummyCompleter(),
            reserve_space_for_menu=6,

            message=self.get_prompt_tokens,
            prompt_continuation=self.get_continuation_tokens,
            bottom_toolbar=self.get_toolbar_tokens,
            multiline=is_multiline,
            history=history,
            complete_while_typing=pt_filters.Always(),
            key_bindings=bindings,
            style=self.style,
            editing_mode=pt_enums.EditingMode.VI,
            search_ignore_case=True,
        )

        return prompt 
Example #9
Source File: main.py    From athenacli with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def _build_prompt_app(self, history):
        key_bindings = cli_bindings(self)

        def get_message():
            prompt = self.get_prompt(self.prompt)
            if len(prompt) > self.MAX_LEN_PROMPT:
                prompt = self.get_prompt('\\r:\\d> ')
            return [('class:prompt', prompt)]

        def get_continuation(width, line_number, is_soft_wrap):
            continuation = ' ' * (width -1) + ' '
            return [('class:continuation', continuation)]

        def show_suggestion_tip():
            return self.iterations < 2

        get_toolbar_tokens = create_toolbar_tokens_func(
            self, show_suggestion_tip)

        with self._completer_lock:
            if self.key_bindings == 'vi':
                editing_mode = EditingMode.VI
            else:
                editing_mode = EditingMode.EMACS

            self.prompt_app = PromptSession(
                lexer=PygmentsLexer(Lexer),
                reserve_space_for_menu=self.get_reserved_space(),
                message=get_message,
                prompt_continuation=get_continuation,
                bottom_toolbar=get_toolbar_tokens,
                complete_style=CompleteStyle.COLUMN,
                input_processors=[ConditionalProcessor(
                    processor=HighlightMatchingBracketProcessor(
                        chars='[](){}'),
                    filter=HasFocus(DEFAULT_BUFFER) & ~IsDone()
                )],
                tempfile_suffix='.sql',
                completer=DynamicCompleter(lambda: self.completer),
                history=history,
                auto_suggest=AutoSuggestFromHistory(),
                complete_while_typing=True,
                multiline=cli_is_multiline(self),
                style=style_factory(self.syntax_style, self.cli_style),
                include_default_pygments_style=False,
                key_bindings=key_bindings,
                enable_open_in_editor=True,
                enable_system_prompt=True,
                editing_mode=editing_mode,
                search_ignore_case=True
            ) 
Example #10
Source File: asyncssh-server.py    From python-prompt-toolkit with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def interact(ssh_session: PromptToolkitSSHSession) -> None:
    """
    The application interaction.

    This will run automatically in a prompt_toolkit AppSession, which means
    that any prompt_toolkit application (dialogs, prompts, etc...) will use the
    SSH channel for input and output.
    """
    prompt_session = PromptSession()

    # Alias 'print_formatted_text', so that 'print' calls go to the SSH client.
    print = print_formatted_text

    print("We will be running a few prompt_toolkit applications through this ")
    print("SSH connection.\n")

    # Simple progress bar.
    with ProgressBar() as pb:
        for i in pb(range(50)):
            await asyncio.sleep(0.1)

    # Normal prompt.
    text = await prompt_session.prompt_async("(normal prompt) Type something: ")
    print("You typed", text)

    # Prompt with auto completion.
    text = await prompt_session.prompt_async(
        "(autocompletion) Type an animal: ", completer=animal_completer
    )
    print("You typed", text)

    # prompt with syntax highlighting.
    text = await prompt_session.prompt_async(
        "(HTML syntax highlighting) Type something: ", lexer=PygmentsLexer(HtmlLexer)
    )
    print("You typed", text)

    # Show yes/no dialog.
    await prompt_session.prompt_async("Showing yes/no dialog... [ENTER]")
    await yes_no_dialog("Yes/no dialog", "Running over asyncssh").run_async()

    # Show input dialog
    await prompt_session.prompt_async("Showing input dialog... [ENTER]")
    await input_dialog("Input dialog", "Running over asyncssh").run_async() 
Example #11
Source File: console.py    From gsheets-db-api with MIT License 4 votes vote down vote up
def main():
    history = FileHistory(os.path.expanduser('~/.gsheetsdb_history'))

    arguments = docopt(__doc__, version=__version__.__version__)

    auth = {
        'service_account_file': arguments['--service-account-file'],
        'subject': arguments['--subject'],
    }
    credentials = get_credentials_from_auth(**auth)
    connection = connect(credentials)
    headers = int(arguments['--headers'])
    cursor = connection.cursor()

    lexer = PygmentsLexer(SqlLexer)
    words = keywords + aggregate_functions + scalar_functions
    completer = WordCompleter(words, ignore_case=True)
    style = style_from_pygments_cls(get_style_by_name('manni'))

    while True:
        try:
            query = prompt(
                'sql> ', lexer=lexer, completer=completer,
                style=style, history=history)
        except (EOFError, KeyboardInterrupt):
            break  # Control-D pressed.

        # run query
        query = query.strip('; ').replace('%', '%%')
        if query:
            try:
                result = cursor.execute(query, headers=headers)
            except Exception as e:
                if arguments['--raise']:
                    raise
                print(e)
                continue

            columns = [t[0] for t in cursor.description or []]
            print(tabulate(result, headers=columns))

    print('See ya!')