-
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathHighlighter.php
75 lines (59 loc) · 1.83 KB
/
Highlighter.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
<?php
declare(strict_types=1);
/*
* This file is part of the CLI-SYNTAX package.
*
* (c) Jitendra Adhikari <[email protected]>
* <https://github.com/adhocore>
*
* Licensed under MIT license.
*/
namespace Ahc\CliSyntax;
class Highlighter extends Pretty
{
/** @var string Output string */
protected $out = '';
public function __toString(): string
{
return $this->highlight();
}
public function highlight(string $code = null, array $options = []): string
{
$this->setOptions($options);
$this->parse($code ?? $this->code);
return \trim($this->out, "\n") . "\n";
}
protected function doReset()
{
$this->out = '';
}
protected function visit(\DOMNode $el)
{
$type = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw';
$text = \str_replace([' ', '<', '>'], [' ', '<', '>'], $el->textContent);
$lastLine = 0;
$lines = \explode("\n", $text);
foreach ($lines as $i => $line) {
$this->out .= $this->formatLine($type, $line);
if (isset($lines[$i + 1])) {
$this->out .= "\n";
}
$this->lengths[$this->lineNo++] = \strlen($line);
}
}
protected function formatLine(string $type, string $line)
{
static $formats = [
'comment' => "\033[0;34;40m%s\033[0m",
'default' => "\033[0;32;40m%s\033[0m",
'keyword' => "\033[0;31;40m%s\033[0m",
'string' => "\033[0;33;40m%s\033[0m",
'lineno' => "\033[2;36;40m%s\033[0m",
'raw' => '%s',
];
if ('' !== $lineNo = $this->formatLineNo()) {
$lineNo = \sprintf($formats['lineno'], $lineNo);
}
return $lineNo . \sprintf($formats[$type], $line);
}
}