1+ package hscript ;
2+
3+ class ColorScheme {
4+
5+ public var keyword : Int = 0x8080FF ;
6+ public var specialIdent : Int = 0xC0C0FF ;
7+ public var comment : Int = 0x80E080 ;
8+ public var braces : Int = 0xC08080 ;
9+ public var parents : Int = 0xC0B0B0 ;
10+ public var string : Int = 0xFFA0A0 ;
11+ public var constant : Int = 0xB0F0B0 ;
12+ public var operand : Int = 0xC0B0B0 ;
13+
14+ public function new () {
15+ }
16+
17+ }
18+
19+
20+ class Colorizer extends Parser {
21+
22+ var segs : Array <Int >;
23+ var startPos : Int ;
24+ var defaultColor : Int ;
25+ var inComment : Bool ;
26+ var lastPos : Int ;
27+
28+ public var color : ColorScheme = new ColorScheme ();
29+
30+ static var KEYWORDS = [for ( k in " for|if|else|switch|case|var|final|while|do|function|return|break|continue|inline|new|throw|try|catch|default|cast|in" .split (" |" ) ) k => true ];
31+ static var IDENTS = [for ( k in " true|false|null|this|super" .split (" |" ) ) k => true ];
32+
33+ public function getColorSegments ( code : String , defaultColor : Int ) {
34+ resumeErrors = true ;
35+ this .defaultColor = defaultColor ;
36+ segs = [];
37+ parseString (code );
38+ var prev = segs ;
39+ segs = null ;
40+ return prev ;
41+ }
42+
43+ function addSeg ( color : Int ) {
44+ var prev = segs .length == 0 ? - 1 : segs [segs .length - 2 ];
45+ if ( prev == startPos ) {
46+ segs .pop ();
47+ segs .pop ();
48+ prev = segs [segs .length - 2 ];
49+ }
50+ if ( prev >= startPos )
51+ return ;
52+ segs .push (startPos );
53+ segs .push (color );
54+ segs .push (getPos ());
55+ segs .push (defaultColor );
56+ }
57+
58+ function getPos () {
59+ return readPos - (this .char == - 1 ? 0 : 1 );
60+ }
61+
62+ override function tokenComment (op ,char ) {
63+ inComment = true ;
64+ var tk = super .tokenComment (op , char );
65+ inComment = false ;
66+ return tk ;
67+ }
68+
69+ override function _token (): hscript. Parser . Token {
70+ if ( inComment ) {
71+ addSeg (color .comment );
72+ inComment = false ;
73+ }
74+ startPos = getPos ();
75+ var tk = super ._token ();
76+ switch ( tk ) {
77+ case TId (id ) if ( KEYWORDS .exists (id ) ):
78+ addSeg (color .keyword );
79+ case TId (id ) if ( IDENTS .exists (id ) ):
80+ addSeg (color .specialIdent );
81+ case TBrOpen , TBrClose :
82+ addSeg (color .braces );
83+ case TPOpen , TPClose :
84+ addSeg (color .parents );
85+ case TConst (c ):
86+ switch ( c ) {
87+ case CString (_ ): addSeg (color .string );
88+ default : addSeg (color .constant );
89+ }
90+ case TOp (_ ):
91+ addSeg (color .operand );
92+ default :
93+ }
94+ return tk ;
95+ }
96+
97+ }
0 commit comments