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)
| 97 | |
| 98 | |
| 99 | def 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 | |
| 126 | def recover_unterminated_string( |
searching dependent graphs…