Files
2026-10-14 16:16:58 +02:00

103 lines
3.3 KiB
Python

"""Syntax-Highlighting-Logik for the Texteditor.
This module contains KEINE Tkinter-Referencers: it only tokenizes Source
and returns Tag-Ranges. The applying of the Tags on the Text-Widget lies
exclusively in app.py.
Only Python is implemented; other languages are planned for Phase 2.
"""
from __future__ import annotations
import builtins
import keyword
import tokenize
import token
from pathlib import Path
# Language detection per File-Suffix (lowercase).
SUFFIX_LANGUAGES = {".py": "python", ".pyw": "python"}
# Tag-Names which the Highlighter can generate. app.py deletes these Tags
# before a new Highlighting and configures the Colors from TAG_COLORS.
HIGHLIGHT_TAGS = (
"py_keyword",
"py_builtin",
"py_string",
"py_comment",
"py_number",
"py_operator",
)
# Colors for the light Tk-Background.
TAG_COLORS = {
"py_keyword": "#00008B",
"py_builtin": "#006400",
"py_string": "#8B0000",
"py_comment": "#595959",
"py_number": "#005C8A",
"py_operator": "#3F3F3F",
}
KEYWORDS = frozenset(keyword.kwlist)
BUILTINS = frozenset(n for n in dir(builtins) if not n.startswith("_"))
# Tokenize has no KEYWORD-Tokentype: Keywords arrive as NAME and must be
# classified with the keyword-Module. The Token-Type-NUMBERS differ between
# Python-Versions, therefore only the Constants from the token-Module are
# used.
_TOKEN_TAGS = {
token.NUMBER: "py_number",
token.STRING: "py_string",
token.COMMENT: "py_comment",
token.OP: "py_operator",
}
# f-Strings (Python 3.12+) arrive as three separate Token-Types.
for _fstring_type in ("FSTRING_START", "FSTRING_MIDDLE", "FSTRING_END"):
_TOKEN_TAGS[getattr(token, _fstring_type)] = "py_string"
def detect_language(path: str | Path) -> str | None:
"""Returns the Language for a File-Name or None, when unknown."""
return SUFFIX_LANGUAGES.get(Path(path).suffix.lower())
def _tag_for(tok: tokenize.TokenInfo) -> str | None:
"""Maps one Tokenize-Token on its Tag-Name (None = default Color)."""
if tok.type == token.NAME:
if tok.string in KEYWORDS:
return "py_keyword"
if tok.string in BUILTINS:
return "py_builtin"
return None
return _TOKEN_TAGS.get(tok.type)
def tokenize_python(source: str) -> list[tuple[str, tuple[int, int], tuple[int, int]]]:
"""Tokenizes Python-Source and returns (tag, start, end).
Positions are the Tokenize-Positions: row starts at 1, column at 0.
Incomplete or incorrect Source (the User types freely into the Editor)
does not raise: the Tokens until tokenize stops are returned, the rest
stays in the default Color.
Raises:
Never. tokenize.TokenError, SyntaxError and ValueError are caught.
"""
# tokenize.tokenize needs a readline over BYTE-LINES (it detects the
# Encoding); str-Lines would raise a TypeError.
lines = iter([line.encode("utf-8") for line in source.splitlines(keepends=True)])
def readline() -> bytes:
return next(lines, b"")
ranges: list[tuple[str, tuple[int, int], tuple[int, int]]] = []
try:
for tok in tokenize.tokenize(readline):
tag = _tag_for(tok)
if tag and tok.start != tok.end:
ranges.append((tag, tok.start, tok.end))
except (tokenize.TokenError, SyntaxError, ValueError):
pass
return ranges