Python prompt_toolkit.styles.pygments.style_from_pygments_cls() Examples

The following are 8 code examples of prompt_toolkit.styles.pygments.style_from_pygments_cls(). 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.styles.pygments , or try the search function .
Example #1
Source File: util.py    From coconut with Apache License 2.0 6 votes vote down vote up
def prompt(self, msg):
        """Get input using prompt_toolkit."""
        try:
            # prompt_toolkit v2
            prompt = prompt_toolkit.PromptSession(history=self.history).prompt
        except AttributeError:
            # prompt_toolkit v1
            prompt = partial(prompt_toolkit.prompt, history=self.history)
        return prompt(
            msg,
            multiline=self.multiline,
            vi_mode=self.vi_mode,
            wrap_lines=self.wrap_lines,
            enable_history_search=self.history_search,
            lexer=PygmentsLexer(CoconutLexer),
            style=style_from_pygments_cls(
                pygments.styles.get_style_by_name(self.style),
            ),
        ) 
Example #2
Source File: printers.py    From fuzzowski with GNU General Public License v2.0 6 votes vote down vote up
def print_packets(path: list, nodes: dict) -> None:
    tokens = []
    for e in path[:-1]:
        node = nodes[e.dst]
        p = node.render()
        line = '{} = {}'.format(node.name.replace('-', '_'), repr(p))
        tokens.extend(list(pygments.lex(line, lexer=Python3Lexer())))

    # p = self.fuzz_node.render()
    node = nodes[path[-1].dst]
    p = node.render()
    line = '{} = {}'.format(node.name.replace('-', '_'), repr(p))

    print(pygments.highlight(line, Python3Lexer(), Terminal256Formatter(style='rrt')))

    # tokens.extend(list(pygments.lex(line, lexer=Python3Lexer())))
    # style = style_from_pygments_cls(get_style_by_name('colorful'))
    # print_formatted_text(PygmentsTokens(tokens), style=style)


# --------------------------------------------------------------- # 
Example #3
Source File: pgstyle.py    From pgcli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native")

    prompt_styles = []
    # prompt-toolkit used pygments tokens for styling before, switched to style
    # names in 2.0. Convert old token types to new style names, for backwards compatibility.
    for token in cli_style:
        if token.startswith("Token."):
            # treat as pygments token (1.0)
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            if token_type in TOKEN_TO_PROMPT_STYLE:
                prompt_style = TOKEN_TO_PROMPT_STYLE[token_type]
                prompt_styles.append((prompt_style, style_value))
            else:
                # we don't want to support tokens anymore
                logger.error("Unhandled style / class name: %s", token)
        else:
            # treat as prompt style name (2.0). See default style names here:
            # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py
            prompt_styles.append((token, cli_style[token]))

    override_style = Style([("bottom-toolbar", "noreverse")])
    return merge_styles(
        [style_from_pygments_cls(style), override_style, Style(prompt_styles)]
    ) 
Example #4
Source File: style.py    From ptpython with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_all_code_styles() -> Dict[str, BaseStyle]:
    """
    Return a mapping from style names to their classes.
    """
    result: Dict[str, BaseStyle] = {
        name: style_from_pygments_cls(get_style_by_name(name))
        for name in get_all_styles()
    }
    result["win32"] = Style.from_dict(win32_code_style)
    return result 
Example #5
Source File: clistyle.py    From litecli with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def style_factory(name, cli_style):
    try:
        style = pygments.styles.get_style_by_name(name)
    except ClassNotFound:
        style = pygments.styles.get_style_by_name("native")

    prompt_styles = []
    # prompt-toolkit used pygments tokens for styling before, switched to style
    # names in 2.0. Convert old token types to new style names, for backwards compatibility.
    for token in cli_style:
        if token.startswith("Token."):
            # treat as pygments token (1.0)
            token_type, style_value = parse_pygments_style(token, style, cli_style)
            if token_type in TOKEN_TO_PROMPT_STYLE:
                prompt_style = TOKEN_TO_PROMPT_STYLE[token_type]
                prompt_styles.append((prompt_style, style_value))
            else:
                # we don't want to support tokens anymore
                logger.error("Unhandled style / class name: %s", token)
        else:
            # treat as prompt style name (2.0). See default style names here:
            # https://github.com/jonathanslenders/python-prompt-toolkit/blob/master/prompt_toolkit/styles/defaults.py
            prompt_styles.append((token, cli_style[token]))

    override_style = Style([("bottom-toolbar", "noreverse")])
    return merge_styles(
        [style_from_pygments_cls(style), override_style, Style(prompt_styles)]
    ) 
Example #6
Source File: style.py    From pyvim with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def get_editor_style_by_name(name):
    """
    Get Style class.
    This raises `pygments.util.ClassNotFound` when there is no style with this
    name.
    """
    if name == 'vim':
        vim_style = Style.from_dict(default_vim_style)
    else:
        vim_style = style_from_pygments_cls(get_style_by_name(name))

    return merge_styles([
        vim_style,
        Style.from_dict(style_extensions),
    ]) 
Example #7
Source File: repl.py    From crash with Apache License 2.0 4 votes vote down vote up
def loop(cmd, history_file):
    buf = create_buffer(cmd, history_file)
    key_bindings = KeyBindings()
    bind_keys(buf, key_bindings)
    layout = create_layout(
        buffer=buf,
        multiline=True,
        lexer=PostgresLexer,
        extra_input_processors=[
            ConditionalProcessor(
                processor=HighlightMatchingBracketProcessor(chars='[](){}'),
                filter=HasFocus(DEFAULT_BUFFER) & ~IsDone())
        ],
        get_bottom_toolbar_tokens=lambda: get_toolbar_tokens(cmd),
        get_prompt_tokens=lambda: [('class:prompt', 'cr> ')]
    )
    output = get_default_output()
    app = Application(
        layout=layout,
        style=style_from_pygments_cls(CrateStyle),
        key_bindings=merge_key_bindings([
            key_bindings,
            load_open_in_editor_bindings()
        ]),
        editing_mode=_get_editing_mode(),
        output=output
    )
    cmd.get_num_columns = lambda: output.get_size().columns

    while True:
        try:
            text = app.run()
            if text:
                cmd.process(text)
            buf.reset()
        except ProgrammingError as e:
            if '401' in e.message:
                username = cmd.username
                password = cmd.password
                cmd.username = input('Username: ')
                cmd.password = getpass()
                try:
                    cmd.process(text)
                except ProgrammingError as ex:
                    # fallback to existing user/pw
                    cmd.username = username
                    cmd.password = password
                    cmd.logger.warn(str(ex))
            else:
                cmd.logger.warn(str(e))
        except KeyboardInterrupt:
            if isinstance(app.layout.current_control, SearchBufferControl):
                app.layout.current_control = app.layout.previous_control
            else:
                cmd.logger.warn("Query not cancelled. Run KILL <jobId> to cancel it")
                buf.reset()
        except EOFError:
            cmd.logger.warn('Bye!')
            return 
Example #8
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!')