@@ -23,30 +23,53 @@ public function __toString(): string
2323 return $ this ->highlight ();
2424 }
2525
26- public function highlight (string $ code = null ): string
26+ public function highlight (string $ code = null , array $ options = [] ): string
2727 {
28- $ this ->parse ($ code );
28+ $ this ->setOptions ($ options );
29+
30+ $ this ->parse ($ code ?? $ this ->code );
2931
3032 return \trim ($ this ->out , "\n" ) . "\n" ;
3133 }
3234
33- protected function reset ()
35+ protected function doReset ()
3436 {
3537 $ this ->out = '' ;
3638 }
3739
3840 protected function visit (\DOMNode $ el )
41+ {
42+ $ type = $ el instanceof \DOMElement ? $ el ->getAttribute ('data-type ' ) : 'raw ' ;
43+ $ text = \str_replace ([' ' , '< ' , '> ' ], [' ' , '< ' , '> ' ], $ el ->textContent );
44+
45+ $ lastLine = 0 ;
46+ $ lines = \explode ("\n" , $ text );
47+ foreach ($ lines as $ i => $ line ) {
48+ $ this ->out .= $ this ->formatLine ($ type , $ line );
49+
50+ if (isset ($ lines [$ i + 1 ])) {
51+ $ this ->out .= "\n" ;
52+ }
53+
54+ $ this ->lengths [$ this ->lineNo ++] = \strlen ($ line );
55+ }
56+ }
57+
58+ protected function formatLine (string $ type , string $ line )
3959 {
4060 static $ formats = [
4161 'comment ' => "\033[0;34;40m%s \033[0m " ,
4262 'default ' => "\033[0;32;40m%s \033[0m " ,
4363 'keyword ' => "\033[0;31;40m%s \033[0m " ,
4464 'string ' => "\033[0;33;40m%s \033[0m " ,
65+ 'lineno ' => "\033[2;36;40m%s \033[0m " ,
66+ 'raw ' => '%s ' ,
4567 ];
4668
47- $ type = $ el instanceof \DOMElement ? $ el ->getAttribute ('data-type ' ) : 'raw ' ;
48- $ text = \str_replace ([' ' , '< ' , '> ' ], [' ' , '< ' , '> ' ], $ el ->textContent );
69+ if ('' !== $ lineNo = $ this ->formatLineNo ()) {
70+ $ lineNo = \sprintf ($ formats ['lineno ' ], $ lineNo );
71+ }
4972
50- $ this -> out .= \sprintf ($ formats [$ type ] ?? ' %s ' , $ text );
73+ return $ lineNo . \sprintf ($ formats [$ type ], $ line );
5174 }
5275}
0 commit comments