如何使用带有readline的pygments根据标记对输入文本进行着色?

问题描述:

我想开发一个Python主题,该主题执行Python代码,并在用户键入一些文本时为input()中的标记着色.

I want to develop a Python theme which executes Python codes and which colorize the tokens in input() while users typing some text.

最近,我已经开始学习readline和pygments.

Recently I have started to learn readline and pygments.

我可以将关键字标记添加到制表符完成中.我也可以使用pygments高亮功能为stdout文本着色.

I can add keyword tokens to the tab completion. Also i can colorize the stdout text with pygments highlight function.

但是我仍然无法为input()中的标记着色.

But still i can't colorize the tokens in input().

有没有人给我一个做我想做的主意?

Is there anyone to give me an idea to do what i want?

下面的代码来自示例应用程序.

The codes below are from an example application.

import readline
from pygments.token import Token
from pygments.style import Style
from pygments.lexers import Python3Lexer
from pygments import highlight
from pygments.formatters import Terminal256Formatter
import keyword


class Completer:
    def __init__(self, words):
        self.words = words
        self.prefix = None
        self.match = None

    def complete(self, prefix, index):
        if prefix != self.prefix:
            self.match = [i for i in self.words if i.startswith(prefix)]
            self.prefix = prefix
        try:
            return self.match[index]
        except IndexError:
            return None


class MyStyle(Style):
    styles = {
        Token.String: '#ansiwhite',
        Token.Number: '#ansired',
        Token.Keyword: '#ansiyellow',
        Token.Operator: '#ansiyellow',
        Token.Name.Builtin: '#ansiblue',
        Token.Literal.String.Single: '#ansired',
        Token.Punctuation: '#ansiwhite'
    }


if __name__ == "__main__":
    code = highlight("print('hello world')", Python3Lexer(), Terminal256Formatter(style=MyStyle))
    readline.parse_and_bind('tab: complete')
    readline.set_completer(Completer(keyword.kwlist).complete)
    print(code)
    while True:
        _input = input(">>> ")
        if _input == "quit":
            break
        else:
            print(_input)

这是此应用程序工作原理的屏幕截图.如您所见,程序启动时,将使用pygments高亮显示"print('hello world')"字符串.然后,按两次TAB键即可得到关键字.

And this is the screenshot of how this application works. As you can see, when the program starts, a "print('hello world')" string is highlighted with pygments. And after that pressing the TAB 2 times gives the keywords.

先谢谢了.

问题可以通过以下代码解决:

The problem is solved with the below codes:

from pygments.lexers import Python3Lexer
from prompt_toolkit.shortcuts import prompt
from prompt_toolkit.layout.lexers import PygmentsLexer
text = prompt('>>> ', lexer=PygmentsLexer(Python3Lexer))