Skip to content

Commit

Permalink
feat(highlighter): support lineno
Browse files Browse the repository at this point in the history
  • Loading branch information
adhocore committed Jan 8, 2020
1 parent dffe047 commit 5ad19fa
Showing 1 changed file with 29 additions and 6 deletions.
35 changes: 29 additions & 6 deletions src/Highlighter.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,30 +23,53 @@ public function __toString(): string
return $this->highlight();
}

public function highlight(string $code = null): string
public function highlight(string $code = null, array $options = []): string
{
$this->parse($code);
$this->setOptions($options);

$this->parse($code ?? $this->code);

return \trim($this->out, "\n") . "\n";
}

protected function reset()
protected function doReset()
{
$this->out = '';
}

protected function visit(\DOMNode $el)
{
$type = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw';
$text = \str_replace(['&nbsp;', '&lt;', '&gt;'], [' ', '<', '>'], $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',
];

$type = $el instanceof \DOMElement ? $el->getAttribute('data-type') : 'raw';
$text = \str_replace(['&nbsp;', '&lt;', '&gt;'], [' ', '<', '>'], $el->textContent);
if ('' !== $lineNo = $this->formatLineNo()) {
$lineNo = \sprintf($formats['lineno'], $lineNo);
}

$this->out .= \sprintf($formats[$type] ?? '%s', $text);
return $lineNo . \sprintf($formats[$type], $line);
}
}

0 comments on commit 5ad19fa

Please sign in to comment.