MCPcopy Index your code
hub / github.com/python/cpython / gen_colors

Function gen_colors

Lib/_pyrepl/utils.py:99–123  ·  view source on GitHub ↗

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.

(buffer: str)

Source from the content-addressed store, hash-verified

97
98
99def gen_colors(buffer: str) -> Iterator[ColorSpan]:
100 """Returns a list of index spans to color using the given color tag.
101
102 The input `buffer` should be a valid start of a Python code block, i.e.
103 it cannot be a block starting in the middle of a multiline string.
104 """
105 sio = StringIO(buffer)
106 line_lengths = [0] + [len(line) for line in sio.readlines()]
107 # make line_lengths cumulative
108 for i in range(1, len(line_lengths)):
109 line_lengths[i] += line_lengths[i-1]
110
111 sio.seek(0)
112 gen = tokenize.generate_tokens(sio.readline)
113 last_emitted: ColorSpan | None = None
114 try:
115 for color in gen_colors_from_token_stream(gen, line_lengths):
116 yield color
117 last_emitted = color
118 except SyntaxError:
119 return
120 except tokenize.TokenError as te:
121 yield from recover_unterminated_string(
122 te, line_lengths, last_emitted, buffer
123 )
124
125
126def recover_unterminated_string(

Callers 2

calc_screenMethod · 0.85

Calls 5

StringIOClass · 0.90
readlinesMethod · 0.45
seekMethod · 0.45

Tested by 1

Used in the wild real call sites across dependent graphs

searching dependent graphs…