-
-
Notifications
You must be signed in to change notification settings - Fork 31.7k
gh-131507: Add support for syntax highlighting in PyREPL #131562
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
base: main
Are you sure you want to change the base?
Changes from all commits
File filter
Filter by extension
Conversations
Jump to
Diff view
Diff view
There are no files selected for viewing
Original file line number | Diff line number | Diff line change | ||||||||||||||||||
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
|
@@ -2,12 +2,56 @@ | |||||||||||||||||||
import unicodedata | ||||||||||||||||||||
import functools | ||||||||||||||||||||
|
||||||||||||||||||||
from idlelib import colorizer | ||||||||||||||||||||
from typing import cast, Iterator, Literal, Match, NamedTuple, Pattern, Self | ||||||||||||||||||||
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more. Here are some deprecated aliases. Although there are no issues at present, it would be better to switch to https://docs.python.org/3.14/library/typing.html#typing.Iterator |
||||||||||||||||||||
from _colorize import ANSIColors | ||||||||||||||||||||
|
||||||||||||||||||||
from .types import CharBuffer, CharWidths | ||||||||||||||||||||
from .trace import trace | ||||||||||||||||||||
|
||||||||||||||||||||
ANSI_ESCAPE_SEQUENCE = re.compile(r"\x1b\[[ -@]*[A-~]") | ||||||||||||||||||||
ZERO_WIDTH_BRACKET = re.compile(r"\x01.*?\x02") | ||||||||||||||||||||
ZERO_WIDTH_TRANS = str.maketrans({"\x01": "", "\x02": ""}) | ||||||||||||||||||||
COLORIZE_RE: Pattern[str] = colorizer.prog | ||||||||||||||||||||
IDENTIFIER_RE: Pattern[str] = colorizer.idprog | ||||||||||||||||||||
IDENTIFIERS_AFTER = {"def", "class"} | ||||||||||||||||||||
COLORIZE_GROUP_NAME_MAP: dict[str, str] = colorizer.prog_group_name_to_tag | ||||||||||||||||||||
|
||||||||||||||||||||
type ColorTag = ( | ||||||||||||||||||||
Literal["KEYWORD"] | ||||||||||||||||||||
| Literal["BUILTIN"] | ||||||||||||||||||||
| Literal["COMMENT"] | ||||||||||||||||||||
| Literal["STRING"] | ||||||||||||||||||||
| Literal["DEFINITION"] | ||||||||||||||||||||
| Literal["SYNC"] | ||||||||||||||||||||
) | ||||||||||||||||||||
Comment on lines
+20
to
+27
There was a problem hiding this comment. Choose a reason for hiding this commentThe reason will be displayed to describe this comment to others. Learn more.
Suggested change
|
||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
class Span(NamedTuple): | ||||||||||||||||||||
"""Span indexing that's inclusive on both ends.""" | ||||||||||||||||||||
|
||||||||||||||||||||
start: int | ||||||||||||||||||||
end: int | ||||||||||||||||||||
|
||||||||||||||||||||
@classmethod | ||||||||||||||||||||
def from_re(cls, m: Match[str], group: int | str) -> Self: | ||||||||||||||||||||
re_span = m.span(group) | ||||||||||||||||||||
return cls(re_span[0], re_span[1] - 1) | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
class ColorSpan(NamedTuple): | ||||||||||||||||||||
span: Span | ||||||||||||||||||||
tag: ColorTag | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
TAG_TO_ANSI: dict[ColorTag, str] = { | ||||||||||||||||||||
"KEYWORD": ANSIColors.BOLD_BLUE, | ||||||||||||||||||||
"BUILTIN": ANSIColors.CYAN, | ||||||||||||||||||||
"COMMENT": ANSIColors.RED, | ||||||||||||||||||||
"STRING": ANSIColors.GREEN, | ||||||||||||||||||||
"DEFINITION": ANSIColors.BOLD_WHITE, | ||||||||||||||||||||
"SYNC": ANSIColors.RESET, | ||||||||||||||||||||
} | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
@functools.cache | ||||||||||||||||||||
|
@@ -41,25 +85,82 @@ def unbracket(s: str, including_content: bool = False) -> str: | |||||||||||||||||||
return s.translate(ZERO_WIDTH_TRANS) | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
def disp_str(buffer: str) -> tuple[CharBuffer, CharWidths]: | ||||||||||||||||||||
r"""Decompose the input buffer into a printable variant. | ||||||||||||||||||||
def gen_colors(buffer: str) -> Iterator[ColorSpan]: | ||||||||||||||||||||
"""Returns a list of index spans to color using the given color tag. | ||||||||||||||||||||
|
||||||||||||||||||||
The input `buffer` should be a valid start of a Python code block, i.e. | ||||||||||||||||||||
it cannot be a block starting in the middle of a multiline string. | ||||||||||||||||||||
""" | ||||||||||||||||||||
for match in COLORIZE_RE.finditer(buffer): | ||||||||||||||||||||
yield from gen_color_spans(match) | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
def gen_color_spans(re_match: Match[str]) -> Iterator[ColorSpan]: | ||||||||||||||||||||
"""Generate non-empty color spans.""" | ||||||||||||||||||||
for tag, data in re_match.groupdict().items(): | ||||||||||||||||||||
if not data: | ||||||||||||||||||||
continue | ||||||||||||||||||||
span = Span.from_re(re_match, tag) | ||||||||||||||||||||
tag = COLORIZE_GROUP_NAME_MAP.get(tag, tag) | ||||||||||||||||||||
yield ColorSpan(span, cast(ColorTag, tag)) | ||||||||||||||||||||
if data in IDENTIFIERS_AFTER: | ||||||||||||||||||||
if name_match := IDENTIFIER_RE.match(re_match.string, span.end + 1): | ||||||||||||||||||||
span = Span.from_re(name_match, 1) | ||||||||||||||||||||
yield ColorSpan(span, "DEFINITION") | ||||||||||||||||||||
|
||||||||||||||||||||
|
||||||||||||||||||||
def disp_str( | ||||||||||||||||||||
buffer: str, colors: list[ColorSpan] | None = None, start_index: int = 0 | ||||||||||||||||||||
) -> tuple[CharBuffer, CharWidths]: | ||||||||||||||||||||
r"""Decompose the input buffer into a printable variant with applied colors. | ||||||||||||||||||||
|
||||||||||||||||||||
Returns a tuple of two lists: | ||||||||||||||||||||
- the first list is the input buffer, character by character; | ||||||||||||||||||||
- the first list is the input buffer, character by character, with color | ||||||||||||||||||||
escape codes added (while those codes contain multiple ASCII characters, | ||||||||||||||||||||
each code is considered atomic *and is attached for the corresponding | ||||||||||||||||||||
visible character*); | ||||||||||||||||||||
- the second list is the visible width of each character in the input | ||||||||||||||||||||
buffer. | ||||||||||||||||||||
|
||||||||||||||||||||
Note on colors: | ||||||||||||||||||||
- The `colors` list, if provided, is partially consumed within. We're using | ||||||||||||||||||||
a list and not a generator since we need to hold onto the current | ||||||||||||||||||||
unfinished span between calls to disp_str in case of multiline strings. | ||||||||||||||||||||
- The `colors` list is computed from the start of the input block. `buffer` | ||||||||||||||||||||
is only a subset of that input block, a single line within. This is why | ||||||||||||||||||||
we need `start_index` to inform us which position is the start of `buffer` | ||||||||||||||||||||
actually within user input. This allows us to match color spans correctly. | ||||||||||||||||||||
|
||||||||||||||||||||
Examples: | ||||||||||||||||||||
>>> utils.disp_str("a = 9") | ||||||||||||||||||||
(['a', ' ', '=', ' ', '9'], [1, 1, 1, 1, 1]) | ||||||||||||||||||||
|
||||||||||||||||||||
>>> line = "while 1:" | ||||||||||||||||||||
>>> colors = list(utils.gen_colors(line)) | ||||||||||||||||||||
>>> utils.disp_str(line, colors=colors) | ||||||||||||||||||||
(['\x1b[1;34mw', 'h', 'i', 'l', 'e\x1b[0m', ' ', '1', ':'], [1, 1, 1, 1, 1, 1, 1, 1]) | ||||||||||||||||||||
|
||||||||||||||||||||
""" | ||||||||||||||||||||
chars: CharBuffer = [] | ||||||||||||||||||||
char_widths: CharWidths = [] | ||||||||||||||||||||
|
||||||||||||||||||||
if not buffer: | ||||||||||||||||||||
return chars, char_widths | ||||||||||||||||||||
|
||||||||||||||||||||
for c in buffer: | ||||||||||||||||||||
while colors and colors[0].span.end < start_index: | ||||||||||||||||||||
# move past irrelevant spans | ||||||||||||||||||||
colors.pop(0) | ||||||||||||||||||||
|
||||||||||||||||||||
pre_color = "" | ||||||||||||||||||||
post_color = "" | ||||||||||||||||||||
if colors and colors[0].span.start < start_index: | ||||||||||||||||||||
# looks like we're continuing a previous color (e.g. a multiline str) | ||||||||||||||||||||
pre_color = TAG_TO_ANSI[colors[0].tag] | ||||||||||||||||||||
|
||||||||||||||||||||
for i, c in enumerate(buffer, start_index): | ||||||||||||||||||||
if colors and colors[0].span.start == i: # new color starts now | ||||||||||||||||||||
pre_color = TAG_TO_ANSI[colors[0].tag] | ||||||||||||||||||||
|
||||||||||||||||||||
if c == "\x1a": # CTRL-Z on Windows | ||||||||||||||||||||
chars.append(c) | ||||||||||||||||||||
char_widths.append(2) | ||||||||||||||||||||
|
@@ -73,5 +174,19 @@ def disp_str(buffer: str) -> tuple[CharBuffer, CharWidths]: | |||||||||||||||||||
else: | ||||||||||||||||||||
chars.append(c) | ||||||||||||||||||||
char_widths.append(str_width(c)) | ||||||||||||||||||||
|
||||||||||||||||||||
if colors and colors[0].span.end == i: # current color ends now | ||||||||||||||||||||
post_color = TAG_TO_ANSI["SYNC"] | ||||||||||||||||||||
colors.pop(0) | ||||||||||||||||||||
|
||||||||||||||||||||
chars[-1] = pre_color + chars[-1] + post_color | ||||||||||||||||||||
pre_color = "" | ||||||||||||||||||||
post_color = "" | ||||||||||||||||||||
|
||||||||||||||||||||
if colors and colors[0].span.start < i and colors[0].span.end > i: | ||||||||||||||||||||
# even though the current color should be continued, reset it for now. | ||||||||||||||||||||
# the next call to `disp_str()` will revive it. | ||||||||||||||||||||
chars[-1] += TAG_TO_ANSI["SYNC"] | ||||||||||||||||||||
|
||||||||||||||||||||
trace("disp_str({buffer}) = {s}, {b}", buffer=repr(buffer), s=chars, b=char_widths) | ||||||||||||||||||||
return chars, char_widths |
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
PyREPL now supports syntax highlighing. Contributed by Łukasz Langa. |
There was a problem hiding this comment.
Choose a reason for hiding this comment
The reason will be displayed to describe this comment to others. Learn more.
On Windows, if you do not choose to install Tcl/Tk, IDLE will not be available
See https://github.com/python/cpython/blob/main/Tools%2Fmsi%2Ftcltk%2Ftcltk.wixproj