TR
games/alis / src / Editor / SourceBuffer.php · commit 9c722cf
<?phpnamespace App\Editor;/** * The text being edited: lines, a cursor (line, column in characters), a selection, undo / redo. * Columns count UTF-8 characters (the sources write the game's accents as such). */final class SourceBuffer{    /** @var list<string> */    public array $lines = [''];    public int $line = 0;    public int $col = 0;    /** the other end of the selection: [line, col], or null */    public ?array $anchor = null;    /** the column the cursor wants when it moves up / down through shorter lines */    private int $wantCol = 0;    /** @var list<array{0: list<string>, 1: int, 2: int}> */    private array $undo = [];    /** @var list<array{0: list<string>, 1: int, 2: int}> */    private array $redo = [];    /** what the last change was ('type' while typing: one undo step for a word) */    private string $lastKind = '';    public bool $dirty = false;    public function __construct(string $text = '')    {        $this->setText($text);    }    public function setText(string $text): void    {        $this->lines = explode("\n", str_replace(["\r\n", "\r"], "\n", $text));        $this->line = $this->col = $this->wantCol = 0;        $this->anchor = null;        $this->undo = $this->redo = [];        $this->dirty = false;        $this->lastKind = '';    }    public function text(): string    {        return implode("\n", $this->lines);    }    public static function len(string $s): int    {        return (int) preg_match_all('/./us', $s);    }    public static function sub(string $s, int $start, ?int $length = null): string    {        $chars = preg_split('//u', $s, -1, PREG_SPLIT_NO_EMPTY) ?: [];        return implode('', array_slice($chars, $start, $length));    }    // --- moving --------------------------------------------------------------------------------    public function moveTo(int $line, int $col, bool $select = false): void    {        $this->startSelection($select);        $this->line = max(0, min(count($this->lines) - 1, $line));        $this->col = max(0, min(self::len($this->lines[$this->line]), $col));        $this->wantCol = $this->col;        $this->endSelection($select);    }    public function left(bool $select = false, bool $word = false): void    {        if (!$select && $this->anchor !== null) {            [$a] = $this->ordered();            $this->anchor = null;            $this->moveTo($a[0], $a[1]);            return;        }        if ($this->col > 0) {            $col = $this->col - 1;            if ($word) {                $chars = preg_split('//u', $this->lines[$this->line], -1, PREG_SPLIT_NO_EMPTY) ?: [];                while ($col > 0 && !self::isWord($chars[$col] ?? ' ')) {                    $col--;                }                while ($col > 0 && self::isWord($chars[$col - 1])) {                    $col--;                }            }            $this->moveTo($this->line, $col, $select);        } elseif ($this->line > 0) {            $this->moveTo($this->line - 1, PHP_INT_MAX, $select);        }    }    public function right(bool $select = false, bool $word = false): void    {        if (!$select && $this->anchor !== null) {            [, $b] = $this->ordered();            $this->anchor = null;            $this->moveTo($b[0], $b[1]);            return;        }        $len = self::len($this->lines[$this->line]);        if ($this->col < $len) {            $col = $this->col + 1;            if ($word) {                $chars = preg_split('//u', $this->lines[$this->line], -1, PREG_SPLIT_NO_EMPTY) ?: [];                while ($col < $len && self::isWord($chars[$col - 1]) && self::isWord($chars[$col])) {                    $col++;                }                while ($col < $len && !self::isWord($chars[$col])) {                    $col++;                }            }            $this->moveTo($this->line, $col, $select);        } elseif ($this->line < count($this->lines) - 1) {            $this->moveTo($this->line + 1, 0, $select);        }    }    public function vertical(int $delta, bool $select = false): void    {        $want = $this->wantCol;        $this->moveTo($this->line + $delta, $want, $select);        $this->wantCol = $want;    }    public function home(bool $select = false): void    {        // first the indentation's end, then column 0        $indent = strlen($this->lines[$this->line]) - strlen(ltrim($this->lines[$this->line]));        $this->moveTo($this->line, $this->col === $indent ? 0 : $indent, $select);    }    public function end(bool $select = false): void    {        $this->moveTo($this->line, PHP_INT_MAX, $select);    }    public function selectAll(): void    {        $this->anchor = [0, 0];        $this->line = count($this->lines) - 1;        $this->col = self::len($this->lines[$this->line]);    }    private function startSelection(bool $select): void    {        if ($select && $this->anchor === null) {            $this->anchor = [$this->line, $this->col];        } elseif (!$select) {            $this->anchor = null;        }    }    private function endSelection(bool $select): void    {        if ($select && $this->anchor === [$this->line, $this->col]) {            $this->anchor = null;        }    }    private static function isWord(string $c): bool    {        return (bool) preg_match('/[\w\[\]]/u', $c);    }    /** The selection's two ends, first one first. @return array{0: array{0: int, 1: int}, 1: array{0: int, 1: int}} */    public function ordered(): array    {        $a = $this->anchor ?? [$this->line, $this->col];        $b = [$this->line, $this->col];        return $a <= $b ? [$a, $b] : [$b, $a];    }    public function selected(): string    {        if ($this->anchor === null) {            return '';        }        [$a, $b] = $this->ordered();        if ($a[0] === $b[0]) {            return self::sub($this->lines[$a[0]], $a[1], $b[1] - $a[1]);        }        $out = [self::sub($this->lines[$a[0]], $a[1])];        for ($l = $a[0] + 1; $l < $b[0]; $l++) {            $out[] = $this->lines[$l];        }        $out[] = self::sub($this->lines[$b[0]], 0, $b[1]);        return implode("\n", $out);    }    // --- changing ------------------------------------------------------------------------------    private function remember(string $kind): void    {        if ($kind !== 'type' || $this->lastKind !== 'type') {            $this->undo[] = [$this->lines, $this->line, $this->col];            if (count($this->undo) > 200) {                array_shift($this->undo);            }            $this->redo = [];        }        $this->lastKind = $kind;        $this->dirty = true;    }    /** Removes the selection (no undo step of its own). */    private function cut(): void    {        if ($this->anchor === null) {            return;        }        [$a, $b] = $this->ordered();        $head = self::sub($this->lines[$a[0]], 0, $a[1]);        $tail = self::sub($this->lines[$b[0]], $b[1]);        array_splice($this->lines, $a[0], $b[0] - $a[0] + 1, [$head . $tail]);        $this->anchor = null;        $this->line = $a[0];        $this->col = $this->wantCol = $a[1];    }    /** Types text at the cursor (over the selection). */    public function insert(string $text, string $kind = 'type'): void    {        if ($text === '') {            return;        }        $this->remember(str_contains($text, "\n") || preg_match('/\s/', $text) ? 'other' : $kind);        $this->cut();        $current = $this->lines[$this->line];        $head = self::sub($current, 0, $this->col);        $tail = self::sub($current, $this->col);        $parts = explode("\n", str_replace(["\r\n", "\r"], "\n", $text));        $last = count($parts) - 1;        $parts[0] = $head . $parts[0];        $endCol = self::len($parts[$last]);        $parts[$last] .= $tail;        array_splice($this->lines, $this->line, 1, $parts);        $this->line += $last;        $this->col = $this->wantCol = $endCol;    }    /** Return: a new line with the same indentation (one more after a "{"). */    public function newline(): void    {        $current = $this->lines[$this->line];        preg_match('/^\s*/', $current, $m);        $indent = $m[0];        if (str_ends_with(rtrim(self::sub($current, 0, $this->col)), '{')) {            $indent .= '    ';        }        $this->insert("\n" . $indent, 'other');    }    public function backspace(bool $word = false): void    {        if ($this->anchor === null) {            if ($this->line === 0 && $this->col === 0) {                return;            }            $this->anchor = [$this->line, $this->col];            // inside the indentation: back to the previous tab stop            $before = self::sub($this->lines[$this->line], 0, $this->col);            if (!$word && $this->col > 0 && trim($before) === '') {                $this->col = intdiv($this->col - 1, 4) * 4;            } else {                $anchor = $this->anchor;                $this->left(true, $word);                $this->anchor = $anchor;            }        }        $this->remember('delete');        $this->cut();    }    public function delete(bool $word = false): void    {        if ($this->anchor === null) {            if ($this->line === count($this->lines) - 1 && $this->col >= self::len($this->lines[$this->line])) {                return;            }            $this->anchor = [$this->line, $this->col];            $anchor = $this->anchor;            $this->right(true, $word);            $this->anchor = $anchor;        }        $this->remember('delete');        $this->cut();    }    /** Tab: indents the selected lines (or types 4 spaces); with shift, unindents. */    public function indent(bool $out = false): void    {        if ($this->anchor === null && !$out) {            $this->insert(str_repeat(' ', 4 - $this->col % 4), 'other');            return;        }        $this->remember('other');        [$a, $b] = $this->ordered();        for ($l = $a[0]; $l <= $b[0]; $l++) {            $this->lines[$l] = $out ? preg_replace('/^ {1,4}/', '', $this->lines[$l]) : '    ' . $this->lines[$l];        }        $this->col = min($this->col, self::len($this->lines[$this->line]));        if ($this->anchor !== null) {            $this->anchor[1] = min($this->anchor[1], self::len($this->lines[$this->anchor[0]]));        }    }    public function undo(): bool    {        $state = array_pop($this->undo);        if ($state === null) {            return false;        }        $this->redo[] = [$this->lines, $this->line, $this->col];        [$this->lines, $this->line, $this->col] = $state;        $this->anchor = null;        $this->lastKind = '';        $this->dirty = true;        return true;    }    public function redo(): bool    {        $state = array_pop($this->redo);        if ($state === null) {            return false;        }        $this->undo[] = [$this->lines, $this->line, $this->col];        [$this->lines, $this->line, $this->col] = $state;        $this->anchor = null;        $this->lastKind = '';        $this->dirty = true;        return true;    }    /** The next place of $needle after the cursor (wraps around), case-insensitive (ASCII); selects it. */    public function find(string $needle, bool $backwards = false): bool    {        if ($needle === '') {            return false;        }        $needle = strtolower($needle);        $n = count($this->lines);        $nlen = self::len($needle);        // the byte where the search starts in the cursor's line (forwards: the cursor; backwards: the selection's start)        [$a] = $this->ordered();        $startCol = $backwards ? $a[1] : $this->col;        $startByte = strlen(self::sub($this->lines[$this->line], 0, $startCol));        for ($i = 0; $i <= $n; $i++) {            $l = $backwards ? ($this->line - $i + $n) % $n : ($this->line + $i) % $n;            $hay = strtolower($this->lines[$l]);            if ($backwards) {                $limit = $i === 0 ? $startByte : strlen($hay);                $p = $limit - strlen($needle) >= 0 ? strrpos(substr($hay, 0, $limit), $needle) : false;            } else {                $p = strpos($hay, $needle, $i === 0 ? min($startByte, strlen($hay)) : 0);            }            if ($p !== false) {                $col = self::len(substr($this->lines[$l], 0, $p));                $this->anchor = [$l, $col];                $this->line = $l;                $this->col = $this->wantCol = $col + $nlen;                return true;            }        }        return false;    }}