Styling, abbreviated commands

This commit is contained in:
Chris 2024-02-27 22:07:38 +01:00
parent 17064e7e43
commit ba27d840ea
2 changed files with 20 additions and 3 deletions

View File

@ -13,6 +13,8 @@ class CommandHandler implements EventEmitterInterface
private array $commands = []; private array $commands = [];
private bool $allowAbbreviatedCommands = true;
public function add(string $command, callable $handler, array $signature=[]): self public function add(string $command, callable $handler, array $signature=[]): self
{ {
$this->commands[$command] = [ 'handler' => $handler, 'signature' => $signature ]; $this->commands[$command] = [ 'handler' => $handler, 'signature' => $signature ];
@ -28,6 +30,19 @@ class CommandHandler implements EventEmitterInterface
{ {
$command = array_shift($line); $command = array_shift($line);
if ($this->allowAbbreviatedCommands) {
$candidates = array_filter(
array_keys($this->commands),
fn($c)=>str_starts_with($c,$command)
);
if (count($candidates)>2) {
$this->emit("candidates", [ $candidates, $shell ]);
return;
}
if (count($candidates)==1) {
$command = array_shift($candidates);
}
}
if (!array_key_exists($command, $this->commands)) { if (!array_key_exists($command, $this->commands)) {
$this->emit("command", [ $command, $line, $shell ]); $this->emit("command", [ $command, $line, $shell ]);
return; return;

View File

@ -35,7 +35,9 @@ class Shell implements WritableStreamInterface, EventEmitterInterface
private int $promptWidth = 0; private int $promptWidth = 0;
private string $promptStyle = "35;1"; private string $promptStyle = "36;1";
private string $inputStyle = "36";
public function __construct(?ReadableStreamInterface $input=null, ?WritableStreamInterface $output=null) public function __construct(?ReadableStreamInterface $input=null, ?WritableStreamInterface $output=null)
{ {
@ -191,8 +193,8 @@ class Shell implements WritableStreamInterface, EventEmitterInterface
$obuf = "\r" . "\e[{$this->promptStyle}m" . $this->prompt . "\e[0m"; $obuf = "\r" . "\e[{$this->promptStyle}m" . $this->prompt . "\e[0m";
$ostr = mb_substr($this->buffer, $this->scrollOffset) . " "; $ostr = mb_substr($this->buffer, $this->scrollOffset) . " ";
$ostr = mb_substr($ostr, 0, $this->termWidth - $this->promptWidth); $ostr = mb_substr($ostr, 0, $this->termWidth - $this->promptWidth);
$obuf .= $ostr . "\e[K\e[" . $pos . "G"; $obuf .= "\e[{$this->inputStyle}m" . $ostr . "\e[K\e[0m\e[" . $pos . "G";
$this->ostream->write($obuf); $this->ostream->write($obuf);
} }
} }