php-kilo/src/Editor.php

867 lines
19 KiB
PHP

<?php declare(strict_types=1);
namespace Aviat\Kilo;
use Aviat\Kilo\Type\TerminalSize;
use Aviat\Kilo\Enum\{Color, KeyCode, KeyType, Highlight};
use Aviat\Kilo\Type\{Point, StatusMessage};
/**
* // Don't highlight this!
*/
class Editor {
/**
* @var string The screen buffer
*/
private string $outputBuffer = '';
/**
* @var Point The 0-based location of the cursor in the current viewport
*/
protected Point $cursor;
/**
* @var Point The scroll offset of the file in the current viewport
*/
protected Point $offset;
/**
* @var Document The document being edited
*/
protected Document $document;
/**
* @var StatusMessage A disappearing status message
*/
protected StatusMessage $statusMessage;
/**
* @var TerminalSize The size of the terminal in rows and columns
*/
protected TerminalSize $terminalSize;
/**
* @var int The rendered cursor position
*/
protected int $renderX = 0;
/**
* @var bool Should we stop the rendering loop?
*/
protected bool $shouldQuit = false;
/**
* @var int The number of times to confirm you wish to quit
*/
protected int $quitTimes = KILO_QUIT_TIMES;
/**
* Create the Editor instance with CLI arguments
*
* @param int $argc
* @param array $argv
* @return Editor
*/
public static function new(int $argc = 0, array $argv = []): Editor
{
if ($argc >= 2 && ! empty($argv[1]))
{
return new self($argv[1]);
}
return new self();
}
/**
* The real constructor, ladies and gentlemen
*
* @param string|null $filename
*/
private function __construct(?string $filename = NULL)
{
$this->statusMessage = StatusMessage::from('HELP: Ctrl-S = save | Ctrl-Q = quit | Ctrl-F = find');
$this->cursor = Point::new();
$this->offset = Point::new();
$this->terminalSize = Terminal::size();
$this->document = Document::default();
if (is_string($filename))
{
$maybeDocument = Document::open($filename);
if ($maybeDocument === NULL)
{
$this->document = Document::default();
$this->setStatusMessage("ERR: Could not open file: {}", $filename);
}
else
{
$this->document = $maybeDocument;
}
}
}
public function __debugInfo(): array
{
return [
'cursor' => $this->cursor,
'document' => $this->document,
'offset' => $this->offset,
'renderX' => $this->renderX,
'terminalSize' => $this->terminalSize,
'statusMessage' => $this->statusMessage,
];
}
/**
* Start the input loop
*/
public function run(): void
{
while ( ! $this->shouldQuit)
{
$this->refreshScreen();
$this->processKeypress();
}
}
// ------------------------------------------------------------------------
// ! Terminal
// ------------------------------------------------------------------------
protected function readKey(): string
{
$c = Terminal::read();
return match($c)
{
// Unambiguous mappings
KeyCode::ARROW_DOWN => KeyType::ARROW_DOWN,
KeyCode::ARROW_LEFT => KeyType::ARROW_LEFT,
KeyCode::ARROW_RIGHT => KeyType::ARROW_RIGHT,
KeyCode::ARROW_UP => KeyType::ARROW_UP,
KeyCode::DEL_KEY => KeyType::DEL_KEY,
KeyCode::ENTER => KeyType::ENTER,
KeyCode::PAGE_DOWN => KeyType::PAGE_DOWN,
KeyCode::PAGE_UP => KeyType::PAGE_UP,
// Backspace
KeyCode::CTRL('h'), KeyCode::BACKSPACE => KeyType::BACKSPACE,
// Escape
KeyCode::CTRL('l'), KeyCode::ESCAPE => KeyType::ESCAPE,
// Home Key
"\eOH", "\e[7~", "\e[1~", ANSI::RESET_CURSOR => KeyType::HOME_KEY,
// End Key
"\eOF", "\e[4~", "\e[8~", "\e[F" => KeyType::END_KEY,
default => $c,
};
}
// ------------------------------------------------------------------------
// ! Row Operations
// ------------------------------------------------------------------------
/**
* Cursor X to Render X
*
* @param Row $row
* @param int $cx
* @return int
*/
protected function rowCxToRx(Row $row, int $cx): int
{
$rx = 0;
for ($i = 0; $i < $cx; $i++)
{
if ($row->chars[$i] === KeyCode::TAB)
{
$rx += (KILO_TAB_STOP - 1) - ($rx % KILO_TAB_STOP);
}
$rx++;
}
return $rx;
}
/**
* Render X to Cursor X
*
* @param Row $row
* @param int $rx
* @return int
*/
protected function rowRxToCx(Row $row, int $rx): int
{
$cur_rx = 0;
for ($cx = 0; $cx < $row->size; $cx++)
{
if ($row->chars[$cx] === KeyCode::TAB)
{
$cur_rx += (KILO_TAB_STOP - 1) - ($cur_rx % KILO_TAB_STOP);
}
$cur_rx++;
if ($cur_rx > $rx)
{
return $cx;
}
}
return $cx;
}
protected function deleteRow(int $at): void
{
if ($at < 0 || $at >= $this->document->numRows)
{
return;
}
// Remove the row
unset($this->document->rows[$at]);
// Re-index the array of rows
$this->document->rows = array_values($this->document->rows);
for ($i = $at; $i < $this->document->numRows; $i++)
{
$this->document->rows[$i]->idx = $i;
}
// Re-tokenize the file
$this->refreshPHPSyntax();
$this->dirty = true;
}
// ------------------------------------------------------------------------
// ! Editor Operations
// ------------------------------------------------------------------------
protected function insertChar(string $c): void
{
$this->document->insert($this->cursor, $c);
$this->moveCursor(KeyType::ARROW_RIGHT);
}
protected function insertNewline(): void
{
// @TODO attempt smart indentation on newline?
if ($this->cursor->x === 0)
{
$this->document->insert(Point::new(0, $this->cursor->y), '');
}
else
{
$row = $this->document->rows[$this->cursor->y];
$chars = $row->chars;
$newChars = substr($chars, 0, $this->cursor->x);
// Truncate the previous row
$row->chars = $newChars;
// Add a new row, with the contents from the cursor to the end of the line
$this->document->insert(Point::new(0, $this->cursor->y + 1), substr($chars, $this->cursor->x));
// $this->insertRow($this->cursor->y + 1, substr($chars, $this->cursor->x));
}
$this->cursor->y++;
$this->cursor->x = 0;
// Re-tokenize the file
// $this->refreshPHPSyntax();
}
protected function deleteChar(): void
{
if ($this->cursor->y === $this->document->numRows || ($this->cursor->x === 0 && $this->cursor->y === 0))
{
return;
}
$row = $this->document->rows[$this->cursor->y];
if ($this->cursor->x > 0)
{
$row->deleteChar($this->cursor->x - 1);
$this->cursor->x--;
}
else
{
$this->cursor->x = $this->document->rows[$this->cursor->y - 1]->size;
$this->document->rows[$this->cursor->y -1]->appendString($row->chars);
$this->deleteRow($this->cursor->y);
$this->cursor->y--;
}
// Re-tokenize the file
$this->refreshPHPSyntax();
}
// ------------------------------------------------------------------------
// ! File I/O
// ------------------------------------------------------------------------
protected function rowsToString(): string
{
$lines = array_map(fn (Row $row) => (string)$row, $this->document->rows);
return implode('', $lines);
}
protected function save(): void
{
if ($this->document->filename === '')
{
$newFilename = $this->prompt('Save as: %s');
if ($newFilename === '')
{
$this->setStatusMessage('Save aborted');
return;
}
$this->document->filename = $newFilename;
}
$res = $this->document->save();
if ($res !== FALSE)
{
$this->setStatusMessage('%d bytes written to disk', $res);
return;
}
$this->setStatusMessage('Failed to save! I/O error: %s', error_get_last()['message'] ?? '');
}
// ------------------------------------------------------------------------
// ! Find
// ------------------------------------------------------------------------
protected function findCallback(string $query, string $key): void
{
static $lastMatch = -1;
static $direction = 1;
static $savedHlLine = 0;
static $savedHl = [];
if ( ! empty($savedHl))
{
$this->document->rows[$savedHlLine]->hl = $savedHl;
$savedHl = [];
}
switch ($key)
{
case KeyCode::ENTER:
case KeyCode::ESCAPE:
$lastMatch = -1;
$direction = 1;
return;
case KeyType::ARROW_DOWN:
case KeyType::ARROW_RIGHT:
$direction = 1;
break;
case KeyType::ARROW_UP:
case KeyType::ARROW_LEFT:
$direction = -1;
break;
default:
$lastMatch = -1;
$direction = 1;
}
if ($lastMatch === -1)
{
$direction = 1;
}
$current = $lastMatch;
if (empty($query))
{
return;
}
for ($i = 0; $i < $this->document->numRows; $i++)
{
$current += $direction;
if ($current === -1)
{
$current = $this->document->numRows - 1;
}
else if ($current === $this->document->numRows)
{
$current = 0;
}
$row =& $this->document->rows[$current];
$match = strpos($row->render, $query);
if ($match !== FALSE)
{
$lastMatch = $current;
$this->cursor->y = (int)$current;
$this->cursor->x = $this->rowRxToCx($row, $match);
$this->offset->y = $this->document->numRows;
$savedHlLine = $current;
$savedHl = $row->hl;
// Update the highlight array of the relevant row with the 'MATCH' type
array_replace_range($row->hl, $match, strlen($query), Highlight::MATCH);
break;
}
}
}
protected function find(): void
{
$savedCursor = Point::from($this->cursor);
$savedOffset = Point::from($this->offset);
$query = $this->prompt('Search: %s (Use ESC/Arrows/Enter)', [$this, 'findCallback']);
// If they pressed escape, the query will be empty,
// restore original cursor and scroll locations
if ($query === '')
{
$this->cursor = Point::from($savedCursor);
$this->offset = Point::from($savedOffset);
}
}
// ------------------------------------------------------------------------
// ! Output
// ------------------------------------------------------------------------
protected function scroll(): void
{
$this->renderX = 0;
if ($this->cursor->y < $this->document->numRows)
{
$this->renderX = $this->rowCxToRx($this->document->rows[$this->cursor->y], $this->cursor->x);
}
// Vertical Scrolling
if ($this->cursor->y < $this->offset->y)
{
$this->offset->y = $this->cursor->y;
}
else if ($this->cursor->y >= ($this->offset->y + $this->terminalSize->rows))
{
$this->offset->y = $this->cursor->y - $this->terminalSize->rows + 1;
}
// Horizontal Scrolling
if ($this->renderX < $this->offset->x)
{
$this->offset->x = $this->renderX;
}
else if ($this->renderX >= ($this->offset->x + $this->terminalSize->cols))
{
$this->offset->x = $this->renderX - $this->terminalSize->cols + 1;
}
}
protected function drawRows(): void
{
for ($y = 0; $y < $this->terminalSize->rows; $y++)
{
$filerow = $y + $this->offset->y;
$this->outputBuffer .= ANSI::CLEAR_LINE;
($filerow >= $this->document->numRows)
? $this->drawPlaceholderRow($y)
: $this->drawRow($filerow);
$this->outputBuffer .= "\r\n";
}
}
protected function drawRow(int $rowIdx): void
{
$len = $this->document->rows[$rowIdx]->rsize - $this->offset->x;
if ($len < 0)
{
$len = 0;
}
if ($len > $this->terminalSize->cols)
{
$len = $this->terminalSize->cols;
}
$chars = substr($this->document->rows[$rowIdx]->render, $this->offset->x, (int)$len);
$hl = array_slice($this->document->rows[$rowIdx]->hl, $this->offset->x, (int)$len);
$currentColor = -1;
for ($i = 0; $i < $len; $i++)
{
$ch = $chars[$i];
// Handle 'non-printable' characters
if (is_ctrl($ch))
{
$sym = (ord($ch) <= 26)
? chr(ord('@') + ord($ch))
: '?';
$this->outputBuffer .= ANSI::color(Color::INVERT);
$this->outputBuffer .= $sym;
$this->outputBuffer .= ANSI::RESET_TEXT;
if ($currentColor !== -1)
{
$this->outputBuffer .= ANSI::color($currentColor);
}
}
else if ($hl[$i] === Highlight::NORMAL)
{
if ($currentColor !== -1)
{
$this->outputBuffer .= ANSI::RESET_TEXT;
$this->outputBuffer .= ANSI::color(Color::FG_WHITE);
$currentColor = -1;
}
$this->outputBuffer .= $ch;
}
else
{
$color = syntax_to_color($hl[$i]);
if ($color !== $currentColor)
{
$currentColor = $color;
$this->outputBuffer .= ANSI::RESET_TEXT;
$this->outputBuffer .= ANSI::color($color);
}
$this->outputBuffer .= $ch;
}
}
$this->outputBuffer .= ANSI::RESET_TEXT;
$this->outputBuffer .= ANSI::color(Color::FG_WHITE);
}
protected function drawPlaceholderRow(int $y): void
{
if ($this->document->numRows === 0 && $y === (int)($this->terminalSize->rows / 2))
{
$welcome = sprintf('PHP Kilo editor -- version %s', KILO_VERSION);
$welcomelen = strlen($welcome);
if ($welcomelen > $this->terminalSize->cols)
{
$welcomelen = $this->terminalSize->cols;
}
$padding = ($this->terminalSize->cols - $welcomelen) / 2;
if ($padding > 0)
{
$this->outputBuffer .= '~';
$padding--;
}
for ($i = 0; $i < $padding; $i++)
{
$this->outputBuffer .= ' ';
}
$this->outputBuffer .= substr($welcome, 0, $welcomelen);
}
else
{
$this->outputBuffer .= '~';
}
}
protected function drawStatusBar(): void
{
$this->outputBuffer .= ANSI::color(Color::INVERT);
$statusFilename = $this->filename !== '' ? $this->filename : '[No Name]';
$syntaxType = ($this->syntax !== NULL) ? $this->syntax->filetype : 'no ft';
$isDirty = $this->dirty ? '(modified)' : '';
$status = sprintf('%.20s - %d lines %s', $statusFilename, $this->document->numRows, $isDirty);
$rstatus = sprintf('%s | %d/%d', $syntaxType, $this->cursor->y + 1, $this->document->numRows);
$len = strlen($status);
$rlen = strlen($rstatus);
if ($len > $this->terminalSize->cols)
{
$len = $this->terminalSize->cols;
}
$this->outputBuffer .= substr($status, 0, $len);
while ($len < $this->terminalSize->cols)
{
if ($this->terminalSize->cols - $len === $rlen)
{
$this->outputBuffer .= substr($rstatus, 0, $rlen);
break;
}
$this->outputBuffer .= ' ';
$len++;
}
$this->outputBuffer .= ANSI::RESET_TEXT;
$this->outputBuffer .= "\r\n";
}
protected function drawMessageBar(): void
{
$this->outputBuffer .= ANSI::CLEAR_LINE;
$len = strlen($this->statusMessage->text);
if ($len > $this->terminalSize->cols)
{
$len = $this->terminalSize->cols;
}
if ($len > 0 && (time() - $this->statusMessage->time) < 5)
{
$this->outputBuffer .= substr($this->statusMessage->text, 0, $len);
}
}
protected function refreshScreen(): void
{
$this->scroll();
$this->outputBuffer = '';
$this->outputBuffer .= ANSI::HIDE_CURSOR;
$this->outputBuffer .= ANSI::RESET_CURSOR;
$this->drawRows();
$this->drawStatusBar();
$this->drawMessageBar();
// Specify the current cursor position
$this->outputBuffer .= ANSI::moveCursor(
$this->cursor->y - $this->offset->y,
$this->renderX - $this->offset->x
);
$this->outputBuffer .= ANSI::SHOW_CURSOR;
Terminal::write($this->outputBuffer, strlen($this->outputBuffer));
}
public function setStatusMessage(string $fmt, mixed ...$args): void
{
$this->statusMessage = StatusMessage::from($fmt, ...$args);
}
// ------------------------------------------------------------------------
// ! Input
// ------------------------------------------------------------------------
protected function prompt(string $prompt, ?callable $callback = NULL): string
{
$buffer = '';
$modifiers = KeyType::getConstList();
while (TRUE)
{
$this->setStatusMessage($prompt, $buffer);
$this->refreshScreen();
$c = $this->readKey();
$isModifier = in_array($c, $modifiers, TRUE);
if ($c === KeyType::ESCAPE || ($c === KeyType::ENTER && $buffer !== ''))
{
$this->setStatusMessage('');
if ($callback !== NULL)
{
$callback($buffer, $c);
}
return ($c === KeyType::ENTER) ? $buffer : '';
}
if ($c === KeyType::DEL_KEY || $c === KeyType::BACKSPACE)
{
$buffer = substr($buffer, 0, -1);
}
else if (is_ascii($c) && ( ! (is_ctrl($c) || $isModifier)))
{
$buffer .= $c;
}
if ($callback !== NULL)
{
$callback($buffer, $c);
}
}
}
protected function moveCursor(string $key): void
{
$x = $this->cursor->x;
$y = $this->cursor->y;
$row = $this->document->rows[$y];
switch ($key)
{
case KeyType::ARROW_LEFT:
if ($x !== 0)
{
$x--;
}
else if ($y > 0)
{
// Beginning of a line, go to end of previous line
$y--;
$x = $this->document->rows[$y]->size - 1;
}
break;
case KeyType::ARROW_RIGHT:
if ($row && $x < $row->size)
{
$x++;
}
else if ($row && $x === $row->size)
{
$y++;
$x = 0;
}
break;
case KeyType::ARROW_UP:
if ($y !== 0)
{
$y--;
}
break;
case KeyType::ARROW_DOWN:
if ($y < $this->document->numRows)
{
$y++;
}
break;
case KeyType::PAGE_UP:
$y = ($y > $this->terminalSize->rows)
? $y - $this->terminalSize->rows
: 0;
break;
case KeyType::PAGE_DOWN:
$y = ($y + $this->terminalSize->rows < $this->document->numRows)
? $y + $this->terminalSize->rows
: $this->document->numRows;
break;
case KeyType::HOME_KEY:
$x = 0;
break;
case KeyType::END_KEY:
if ($y < $this->document->numRows)
{
$x = $this->document->rows[$y]->size;
}
break;
default:
// Do nothing
}
// Snap cursor to the end of a row when moving
// from a longer row to a shorter one
$row = $this->document->rows[$y];
$rowLen = ($row !== NULL) ? $row->size : 0;
if ($x > $rowLen)
{
$x = $rowLen;
}
$this->cursor->x = $x;
$this->cursor->y = $y;
}
protected function processKeypress(): void
{
$c = $this->readKey();
if ($c === KeyCode::NULL || $c === KeyCode::EMPTY)
{
return;
}
switch ($c)
{
case KeyCode::CTRL('q'):
$this->quitAttempt();
return;
case KeyCode::CTRL('s'):
$this->save();
break;
case KeyCode::CTRL('f'):
$this->find();
break;
case KeyType::ENTER:
$this->insertNewline();
break;
case KeyType::BACKSPACE:
case KeyType::DEL_KEY:
if ($c === KeyType::DEL_KEY)
{
$this->moveCursor(KeyType::ARROW_RIGHT);
}
$this->deleteChar();
break;
case KeyType::ARROW_UP:
case KeyType::ARROW_DOWN:
case KeyType::ARROW_LEFT:
case KeyType::ARROW_RIGHT:
case KeyType::PAGE_UP:
case KeyType::PAGE_DOWN:
case KeyType::HOME_KEY:
case KeyType::END_KEY:
$this->moveCursor($c);
break;
case KeyCode::CTRL('l'):
case KeyType::ESCAPE:
// Do nothing
break;
default:
$this->insertChar($c);
break;
}
// Reset quit confirmation timer on different keypress
if ($this->quitTimes < KILO_QUIT_TIMES)
{
$this->quitTimes = KILO_QUIT_TIMES;
$this->setStatusMessage('');
}
}
protected function quitAttempt(): void
{
if ($this->document->dirty && $this->quitTimes > 0)
{
$this->setStatusMessage(
'WARNING!!! File has unsaved changes. Press Ctrl-Q %d more times to quit.',
$this->quitTimes
);
$this->quitTimes--;
return;
}
Terminal::clear();
$this->shouldQuit = true;
}
}