@@ -505,6 +505,32 @@ def generate_tokens(readline):
505505 """
506506 return _generate_tokens_from_c_tokenizer (readline , extra_tokens = True )
507507
508+
509+ def _get_token_colors (syntax , tokenize ):
510+ """Map token type numbers to theme colors."""
511+ return frozendict ({
512+ COMMENT : syntax .comment ,
513+ DEDENT : tokenize .whitespace ,
514+ ENCODING : tokenize .whitespace ,
515+ ENDMARKER : tokenize .whitespace ,
516+ ERRORTOKEN : tokenize .error ,
517+ FSTRING_START : syntax .string ,
518+ FSTRING_MIDDLE : syntax .string ,
519+ FSTRING_END : syntax .string ,
520+ INDENT : tokenize .whitespace ,
521+ NAME : syntax .reset ,
522+ NEWLINE : tokenize .whitespace ,
523+ NL : tokenize .whitespace ,
524+ NUMBER : syntax .number ,
525+ OP : syntax .op ,
526+ SOFT_KEYWORD : syntax .soft_keyword ,
527+ STRING : syntax .string ,
528+ TSTRING_START : syntax .string ,
529+ TSTRING_MIDDLE : syntax .string ,
530+ TSTRING_END : syntax .string ,
531+ })
532+
533+
508534def _main (args = None ):
509535 import argparse
510536
@@ -545,13 +571,32 @@ def error(message, filename=None, location=None):
545571
546572
547573 # Output the tokenization
574+ import _colorize
575+
576+ _theme = _colorize .get_theme ()
577+ s = _theme .syntax
578+ t = _theme .tokenize
579+ _token_colors = _get_token_colors (s , t )
548580 for token in tokens :
549581 token_type = token .type
550582 if args .exact :
551583 token_type = token .exact_type
552- token_range = "%d,%d-%d,%d:" % (token .start + token .end )
553- print ("%-20s%-15s%-15r" %
554- (token_range , tok_name [token_type ], token .string ))
584+ token_range = (
585+ f"{ t .position } { token .start [0 ]} "
586+ f"{ t .delimiter } ,{ t .position } { token .start [1 ]} "
587+ f"{ t .delimiter } -"
588+ f"{ t .position } { token .end [0 ]} "
589+ f"{ t .delimiter } ,{ t .position } { token .end [1 ]} "
590+ f"{ t .delimiter } :"
591+ )
592+ color = _token_colors .get (token_type , s .reset )
593+ token_name = tok_name [token_type ]
594+ visible_range = f"{ token .start [0 ]} ,{ token .start [1 ]} -{ token .end [0 ]} ,{ token .end [1 ]} :"
595+ print (
596+ f"{ token_range } { ' ' * (20 - len (visible_range ))} "
597+ f"{ color } { token_name :<15} "
598+ f"{ s .reset } { token .string !r:<15} "
599+ )
555600 except IndentationError as err :
556601 line , column = err .args [1 ][1 :3 ]
557602 error (err .args [0 ], filename , (line , column ))
0 commit comments