Skip to content

Commit 49b7f38

Browse files
authored
Move tokenizer color to _print_tokens() (#82)
2 parents 7d11c7a + 1dda979 commit 49b7f38

1 file changed

Lines changed: 27 additions & 24 deletions

File tree

Lib/tokenize.py

Lines changed: 27 additions & 24 deletions
Original file line numberDiff line numberDiff line change
@@ -532,6 +532,31 @@ def _get_token_colors(syntax, tokenize):
532532
})
533533

534534

535+
def _format_tokens(tokens, *, color=False, exact=False):
536+
theme = _colorize.get_theme(force_no_color=not color)
537+
s = theme.syntax
538+
t = theme.tokenize
539+
token_colors = _get_token_colors(s, t)
540+
for token in tokens:
541+
token_type = token.exact_type if exact else token.type
542+
token_range = (
543+
f"{t.position}{token.start[0]}"
544+
f"{t.delimiter},{t.position}{token.start[1]}"
545+
f"{t.delimiter}-"
546+
f"{t.position}{token.end[0]}"
547+
f"{t.delimiter},{t.position}{token.end[1]}"
548+
f"{t.delimiter}:"
549+
)
550+
token_color = token_colors.get(token_type, s.reset)
551+
token_name = tok_name[token_type]
552+
visible_range = f"{token.start[0]},{token.start[1]}-{token.end[0]},{token.end[1]}:"
553+
yield (
554+
f"{token_range}{' ' * (20 - len(visible_range))}"
555+
f"{token_color}{token_name:<15}"
556+
f"{s.reset}{token.string!r:<15}"
557+
)
558+
559+
535560
def _main(args=None):
536561
import argparse
537562

@@ -572,30 +597,8 @@ def error(message, filename=None, location=None):
572597

573598

574599
# Output the tokenization
575-
_theme = _colorize.get_theme()
576-
s = _theme.syntax
577-
t = _theme.tokenize
578-
_token_colors = _get_token_colors(s, t)
579-
for token in tokens:
580-
token_type = token.type
581-
if args.exact:
582-
token_type = token.exact_type
583-
token_range = (
584-
f"{t.position}{token.start[0]}"
585-
f"{t.delimiter},{t.position}{token.start[1]}"
586-
f"{t.delimiter}-"
587-
f"{t.position}{token.end[0]}"
588-
f"{t.delimiter},{t.position}{token.end[1]}"
589-
f"{t.delimiter}:"
590-
)
591-
color = _token_colors.get(token_type, s.reset)
592-
token_name = tok_name[token_type]
593-
visible_range = f"{token.start[0]},{token.start[1]}-{token.end[0]},{token.end[1]}:"
594-
print(
595-
f"{token_range}{' ' * (20 - len(visible_range))}"
596-
f"{color}{token_name:<15}"
597-
f"{s.reset}{token.string!r:<15}"
598-
)
600+
for line in _format_tokens(tokens, color=True, exact=args.exact):
601+
print(line)
599602
except IndentationError as err:
600603
line, column = err.args[1][1:3]
601604
error(err.args[0], filename, (line, column))

0 commit comments

Comments
 (0)