I try to highlight texts according to tokens. Tokens can be highlighted by the below codes but there are some unwanted results. Some examples:
Suppose to, i typed:
a = "a"
Both a's are highlighted with the same color despite the first 'a' is Token.Name, the second 'a' is Token.Literal.String.Double
Another unwanted case is, when i typed "if", the word is highlighted and if i continue to add some letters to the word "if", the color of the word is changed as expected. However when i delete some letters of this word until the word becomes "if" again, this word is not highlighted as before.
Can you help me to understand this problem here?
Codes:
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
from pygments import lex
from pygments.token import Token
from pygments.lexers import Python3Lexer
try:
import Tkinter as tk
except ImportError:
import tkinter as tk
ROOT = tk.Tk()
TEXT = tk.Text(master=ROOT, fg="white", bg="black", font="TkDefaultFont 10")
TEXT.pack(fill="both", expand=True)
def tag(event):
def colorize(word, color):
index = []
index1 = TEXT.search(word, "1.0", "end")
while index1:
index2 = ".".join([index1.split(".")[0], str(int(index1.split(".")[1]) + len(word))])
index.append((index1, index2))
index1 = TEXT.search(word, index2, "end")
for i, j in index:
TEXT.tag_add(word, i, j)
TEXT.tag_configure(word, foreground=color)
for token, content in lex(TEXT.get("1.0", "end"), Python3Lexer()):
if token == Token.Literal.Number.Integer:
colorize(content, color="purple")
elif token == Token.Keyword:
colorize(content, color="orange")
elif token == Token.Operator.Word:
colorize(content, color="red")
elif token == Token.Name.Builtin:
colorize(content, color="blue")
elif token == Token.Comment.Hashbang or token == Token.Comment.Single:
colorize(content, color="grey")
elif token == Token.Keyword.Namespace:
colorize(content, color="yellow")
elif token == Token.Namespace:
colorize(content, color="green")
elif token == Token.Punctuation:
colorize(content, color="brown")
elif token == Token.Literal.String.Double:
colorize(content, color="cyan")
elif token == Token.Name:
colorize(content, color="white")
TEXT.bind("<KeyRelease>", tag)
ROOT.mainloop()
`