diff --git a/src/Editor.php b/src/Editor.php index a71d0e0..e517814 100644 --- a/src/Editor.php +++ b/src/Editor.php @@ -49,6 +49,23 @@ class Key { } } +class Highlight { + public const NORMAL = 0; + public const NUMBER = 1; +} + +function syntaxToColor(int $hl): int +{ + switch ($hl) + { + case Highlight::NUMBER: + return 31; // Foreground Red + + default: + return 37; // Foreground White + } +} + /** * @property-read int size * @property-read int rsize @@ -59,6 +76,8 @@ class Row { public string $chars = ''; public string $render = ''; + public array $hl = []; + public static function new(string $chars): self { return new self($chars); @@ -108,6 +127,25 @@ class Row { $this->render[$idx++] = $this->chars[$i]; } } + + $this->updateSyntax(); + } + + // ------------------------------------------------------------------------ + // ! Syntax Highlighting + // ------------------------------------------------------------------------ + + protected function updateSyntax(): void + { + $this->hl = array_fill(0, $this->rsize, Highlight::NORMAL); + + for ($i = 0; $i < $this->rsize; $i++) + { + if (isdigit($this->render[$i])) + { + $this->hl[$i] = Highlight::NUMBER; + } + } } } @@ -661,20 +699,34 @@ class Editor { } $c = substr($this->rows[$filerow]->render, $this->colOffset, $len); + $hl = array_slice($this->rows[$filerow]->hl, $this->colOffset, $len); + + $currentColor = -1; for ($i = 0; $i < $len; $i++) { - if (isdigit($c[$i])) + if ($hl[$i] === Highlight::NORMAL) { - $this->ab .= "\x1b[31m"; + if ($currentColor !== -1) + { + $this->ab .= "\x1b[39m"; + $currentColor = -1; + } $this->ab .= $c[$i]; - $this->ab .= "\x1b[39m"; } else { + $color = syntaxToColor($hl[$i]); + if ($color !== $currentColor) + { + $currentColor = $color; + $this->ab .= sprintf("\x1b[%dm", $color); + } $this->ab .= $c[$i]; } } + + $this->ab .= "\x1b[39m"; } $this->ab .= "\x1b[K"; // Clear the current line