Debian Codegraph @

vendor/clue/stdio-react/README.md

raw
1 # clue/reactphp-stdio
2
3 [![CI status](https://github.com/clue/reactphp-stdio/actions/workflows/ci.yml/badge.svg)](https://github.com/clue/reactphp-stdio/actions)
4 [![code coverage](https://img.shields.io/badge/code%20coverage-100%25-success)](#tests)
5 [![installs on Packagist](https://img.shields.io/packagist/dt/clue/stdio-react?color=blue&label=installs%20on%20Packagist)](https://packagist.org/packages/clue/stdio-react)
6
7 Async, event-driven and UTF-8 aware console input & output (STDIN, STDOUT) for
8 truly interactive CLI applications, built on top of [ReactPHP](https://reactphp.org/).
9
10 You can use this library to build truly interactive and responsive command
11 line (CLI) applications, that immediately react when the user types in
12 a line or hits a certain key. Inspired by `ext-readline`, but supports UTF-8
13 and interleaved I/O (typing while output is being printed), history and
14 autocomplete support and takes care of proper TTY settings under the hood
15 without requiring any extensions or special installation.
16
17 **Table of contents**
18
19 * [Support us](#support-us)
20 * [Quickstart example](#quickstart-example)
21 * [Usage](#usage)
22 * [Stdio](#stdio)
23 * [Output](#output)
24 * [Input](#input)
25 * [Prompt](#prompt)
26 * [Echo](#echo)
27 * [Input buffer](#input-buffer)
28 * [Cursor](#cursor)
29 * [History](#history)
30 * [Autocomplete](#autocomplete)
31 * [Keys](#keys)
32 * [Bell](#bell)
33 * [~~Readline~~](#readline)
34 * [Pitfalls](#pitfalls)
35 * [Install](#install)
36 * [Tests](#tests)
37 * [License](#license)
38 * [More](#more)
39
40 ## Support us
41
42 I maintain an ecosystem of open-source projects that have been downloaded
43 hundreds of millions of times and are actively maintained and continuously
44 improved. If you find any of these projects useful, please consider
45 [becoming a sponsor on GitHub](https://github.com/sponsors/clue). Your support
46 helps ensure long-term maintenance and continued development. Thank you! 🚀
47
48 ## Quickstart example
49
50 Once [installed](#install), you can use the following code to present a prompt in a CLI program:
51
52 ```php
53 <?php
54
55 require __DIR__ . '/vendor/autoload.php';
56
57 $stdio = new Clue\React\Stdio\Stdio();
58 $stdio->setPrompt('Input > ');
59
60 $stdio->on('data', function ($line) use ($stdio) {
61 $line = rtrim($line, "\r\n");
62 $stdio->write('Your input: ' . $line . PHP_EOL);
63
64 if ($line === 'quit') {
65 $stdio->end();
66 }
67 });
68 ```
69
70 See also the [examples](examples).
71
72 ## Usage
73
74 ### Stdio
75
76 The `Stdio` is the main interface to this library.
77 It is responsible for orchestrating the input and output streams
78 by registering and forwarding the corresponding events.
79
80 ```php
81 $stdio = new Clue\React\Stdio\Stdio();
82 ```
83
84 This class takes an optional `LoopInterface|null $loop` parameter that can be used to
85 pass the event loop instance to use for this object. You can use a `null` value
86 here in order to use the [default loop](https://github.com/reactphp/event-loop#loop).
87 This value SHOULD NOT be given unless you're sure you want to explicitly use a
88 given event loop instance.
89
90 See below for waiting for user input and writing output.
91 The `Stdio` class is a well-behaving duplex stream
92 (implementing ReactPHP's `DuplexStreamInterface`) that emits each complete
93 line as a `data` event, including the trailing newline.
94
95 #### Output
96
97 The `Stdio` is a well-behaving writable stream
98 implementing ReactPHP's `WritableStreamInterface`.
99
100 The `write($text)` method can be used to print the given text characters to console output.
101 This is useful if you need more control or want to output individual bytes or binary output:
102
103 ```php
104 $stdio->write('hello');
105 $stdio->write(" world\n");
106 ```
107
108 Because the `Stdio` is a well-behaving writable stream,
109 you can also `pipe()` any readable stream into this stream.
110
111 ```php
112 $logger->pipe($stdio);
113 ```
114
115 #### Input
116
117 The `Stdio` is a well-behaving readable stream
118 implementing ReactPHP's `ReadableStreamInterface`.
119
120 It will emit a `data` event for every line read from console input.
121 The event will contain the input buffer as-is, including the trailing newline.
122 You can register any number of event handlers like this:
123
124 ```php
125 $stdio->on('data', function ($line) {
126 if ($line === "start\n") {
127 doSomething();
128 }
129 });
130 ```
131
132 Note that this class takes care of buffering incomplete lines and will only emit
133 complete lines.
134 This means that the line will usually end with the trailing newline character.
135 If the stream ends without a trailing newline character, it will not be present
136 in the `data` event.
137 As such, it's usually recommended to remove the trailing newline character
138 before processing command line input like this:
139
140 ```php
141 $stdio->on('data', function ($line) {
142 $line = rtrim($line, "\r\n");
143 if ($line === "start") {
144 doSomething();
145 }
146 });
147 ```
148
149 Similarly, if you copy and paste a larger chunk of text, it will properly emit
150 multiple complete lines with a separate `data` event for each line.
151
152 Because the `Stdio` is a well-behaving readable stream that will emit incoming
153 data as-is, you can also use this to `pipe()` this stream into other writable
154 streams.
155
156 ```php
157 $stdio->pipe($logger);
158 ```
159
160 You can control various aspects of the console input through this interface,
161 so read on..
162
163 #### Prompt
164
165 The *prompt* will be written at the beginning of the *user input line*, right before the *user input buffer*.
166
167 The `setPrompt($prompt)` method can be used to change the input prompt.
168 The prompt will be printed to the *user input line* as-is, so you will likely want to end this with a space:
169
170 ```php
171 $stdio->setPrompt('Input: ');
172 ```
173
174 The default input prompt is empty, i.e. the *user input line* contains only the actual *user input buffer*.
175 You can restore this behavior by passing an empty prompt:
176
177 ```php
178 $stdio->setPrompt('');
179 ```
180
181 The `getPrompt()` method can be used to get the current input prompt.
182 It will return an empty string unless you've set anything else:
183
184 ```php
185 assert($stdio->getPrompt() === '');
186 ```
187
188 #### Echo
189
190 The *echo mode* controls how the actual *user input buffer* will be presented in the *user input line*.
191
192 The `setEcho($echo)` method can be used to control the echo mode.
193 The default is to print the *user input buffer* as-is.
194
195 You can disable printing the *user input buffer*, e.g. for password prompts.
196 The user will still be able to type, but will not receive any indication of the current *user input buffer*.
197 Please note that this often leads to a bad user experience as users will not even see their cursor position.
198 Simply pass a boolean `false` like this:
199
200 ```php
201 $stdio->setEcho(false);
202 ```
203
204 Alternatively, you can also *hide* the *user input buffer* by using a replacement character.
205 One replacement character will be printed for each character in the *user input buffer*.
206 This is useful for password prompts to give users an indicatation that their key presses are registered.
207 This often provides a better user experience and allows users to still control their cursor position.
208 Simply pass a string replacement character likes this:
209
210 ```php
211 $stdio->setEcho('*');
212 ```
213
214 To restore the original behavior where every character appears as-is, simply pass a boolean `true`:
215
216 ```php
217 $stdio->setEcho(true);
218 ```
219
220 #### Input buffer
221
222 Everything the user types will be buffered in the current *user input buffer*.
223 Once the user hits enter, the *user input buffer* will be processed and cleared.
224
225 The `addInput($input)` method can be used to add text to the *user input
226 buffer* at the current cursor position.
227 The given text will be inserted just like the user would type in a text and as
228 such adjusts the current cursor position accordingly.
229 The user will be able to delete and/or rewrite the buffer at any time.
230 Changing the *user input buffer* can be useful for presenting a preset input to
231 the user (like the last password attempt).
232 Simply pass an input string like this:
233
234 ```php
235 $stdio->addInput('hello');
236 ```
237
238 The `setInput($buffer)` method can be used to control the *user input buffer*.
239 The given text will be used to replace the entire current *user input buffer*
240 and as such adjusts the current cursor position to the end of the new buffer.
241 The user will be able to delete and/or rewrite the buffer at any time.
242 Changing the *user input buffer* can be useful for presenting a preset input to
243 the user (like the last password attempt).
244 Simply pass an input string like this:
245
246 ```php
247 $stdio->setInput('lastpass');
248 ```
249
250 The `getInput()` method can be used to access the current *user input buffer*.
251 This can be useful if you want to append some input behind the current *user input buffer*.
252 You can simply access the buffer like this:
253
254 ```php
255 $buffer = $stdio->getInput();
256 ```
257
258 #### Cursor
259
260 By default, users can control their (horizontal) cursor position by using their arrow keys on the keyboard.
261 Also, every character pressed on the keyboard advances the cursor position.
262
263 The `setMove($toggle)` method can be used to control whether users are allowed to use their arrow keys.
264 To disable the left and right arrow keys, simply pass a boolean `false` like this:
265
266 ```php
267 $stdio->setMove(false);
268 ```
269
270 To restore the default behavior where the user can use the left and right arrow keys,
271 simply pass a boolean `true` like this:
272
273 ```php
274 $stdio->setMove(true);
275 ```
276
277 The `getCursorPosition()` method can be used to access the current cursor position,
278 measured in number of characters.
279 This can be useful if you want to get a substring of the current *user input buffer*.
280 Simply invoke it like this:
281
282 ```php
283 $position = $stdio->getCursorPosition();
284 ```
285
286 The `getCursorCell()` method can be used to get the current cursor position,
287 measured in number of monospace cells.
288 Most *normal* characters (plain ASCII and most multi-byte UTF-8 sequences) take a single monospace cell.
289 However, there are a number of characters that have no visual representation
290 (and do not take a cell at all) or characters that do not fit within a single
291 cell (like some Asian glyphs).
292 This method is mostly useful for calculating the visual cursor position on screen,
293 but you may also invoke it like this:
294
295 ```php
296 $cell = $stdio->getCursorCell();
297 ```
298
299 The `moveCursorTo($position)` method can be used to set the current cursor position to the given absolute character position.
300 For example, to move the cursor to the beginning of the *user input buffer*, simply call:
301
302 ```php
303 $stdio->moveCursorTo(0);
304 ```
305
306 The `moveCursorBy($offset)` method can be used to change the cursor position
307 by the given number of characters relative to the current position.
308 A positive number will move the cursor to the right - a negative number will move the cursor to the left.
309 For example, to move the cursor one character to the left, simply call:
310
311 ```php
312 $stdio->moveCursorBy(-1);
313 ```
314
315 #### History
316
317 By default, users can access the history of previous commands by using their
318 UP and DOWN cursor keys on the keyboard.
319 The history will start with an empty state, thus this feature is effectively
320 disabled, as the UP and DOWN cursor keys have no function then.
321
322 Note that the history is not maintained automatically.
323 Any input the user submits by hitting enter will *not* be added to the history
324 automatically.
325 This may seem inconvenient at first, but it actually gives you more control over
326 what (and when) lines should be added to the history.
327 If you want to automatically add everything from the user input to the history,
328 you may want to use something like this:
329
330 ```php
331 $stdio->on('data', function ($line) use ($stdio) {
332 $line = rtrim($line);
333 $all = $stdio->listHistory();
334
335 // skip empty line and duplicate of previous line
336 if ($line !== '' && $line !== end($all)) {
337 $stdio->addHistory($line);
338 }
339 });
340 ```
341
342 The `listHistory(): string[]` method can be used to
343 return an array with all lines in the history.
344 This will be an empty array until you add new entries via `addHistory()`.
345
346 ```php
347 $list = $stdio->listHistory();
348
349 assert(count($list) === 0);
350 ```
351
352 The `addHistory(string $line): void` method can be used to
353 add a new line to the (bottom position of the) history list.
354 A following `listHistory()` call will return this line as the last element.
355
356 ```php
357 $stdio->addHistory('a');
358 $stdio->addHistory('b');
359
360 $list = $stdio->listHistory();
361 assert($list === array('a', 'b'));
362 ```
363
364 The `clearHistory(): void` method can be used to
365 clear the complete history list.
366 A following `listHistory()` call will return an empty array until you add new
367 entries via `addHistory()` again.
368 Note that the history feature will effectively be disabled if the history is
369 empty, as the UP and DOWN cursor keys have no function then.
370
371 ```php
372 $stdio->clearHistory();
373
374 $list = $stdio->listHistory();
375 assert(count($list) === 0);
376 ```
377
378 The `limitHistory(?int $limit): void` method can be used to
379 set a limit of history lines to keep in memory.
380 By default, only the last 500 lines will be kept in memory and everything else
381 will be discarded.
382 You can use an integer value to limit this to the given number of entries or
383 use `null` for an unlimited number (not recommended, because everything is
384 kept in RAM).
385 If you set the limit to `0` (int zero), the history will effectively be
386 disabled, as no lines can be added to or returned from the history list.
387 If you're building a CLI application, you may also want to use something like
388 this to obey the `HISTSIZE` environment variable:
389
390 ```php
391 $limit = getenv('HISTSIZE');
392 if ($limit === '' || $limit < 0) {
393 // empty string or negative value means unlimited
394 $stdio->limitHistory(null);
395 } elseif ($limit !== false) {
396 // apply any other value if given
397 $stdio->limitHistory($limit);
398 }
399 ```
400
401 There is no such thing as a `readHistory()` or `writeHistory()` method
402 because filesystem operations are inherently blocking and thus beyond the scope
403 of this library.
404 Using your favorite filesystem API and an appropriate number of `addHistory()`
405 or a single `listHistory()` call respectively should be fairly straight
406 forward and is left up as an exercise for the reader of this documentation
407 (i.e. *you*).
408
409 #### Autocomplete
410
411 By default, users can use autocompletion by using their TAB keys on the keyboard.
412 The autocomplete function is not registered by default, thus this feature is
413 effectively disabled, as the TAB key has no function then.
414
415 The `setAutocomplete(?callable $autocomplete): void` method can be used to
416 register a new autocomplete handler.
417 In its most simple form, you won't need to assign any arguments and can simply
418 return an array of possible word matches from a callable like this:
419
420 ```php
421 $stdio->setAutocomplete(function () {
422 return array(
423 'exit',
424 'echo',
425 'help',
426 );
427 });
428 ```
429
430 If the user types `he [TAB]`, the first two matches will be skipped as they do
431 not match the current word prefix and the last one will be picked automatically,
432 so that the resulting input buffer is `hello `.
433
434 If the user types `e [TAB]`, then this will match multiple entries and the user
435 will be presented with a list of up to 8 available word completions to choose
436 from like this:
437
438 ```php
439 > e [TAB]
440 exit echo
441 > e
442 ```
443
444 Unless otherwise specified, the matches will be performed against the current
445 word boundaries in the input buffer.
446 This means that if the user types `hello [SPACE] ex [TAB]`, then the resulting
447 input buffer is `hello exit `, which may or may not be what you need depending
448 on your particular use case.
449
450 In order to give you more control over this behavior, the autocomplete function
451 actually receives three arguments (similar to `ext-readline`'s
452 [`readline_completion_function()`](https://www.php.net/manual/en/function.readline-completion-function.php)):
453 The first argument will be the current incomplete word according to current
454 cursor position and word boundaries, while the second and third argument will be
455 the start and end offset of this word within the complete input buffer measured
456 in (Unicode) characters.
457 The above examples will be invoked as `$fn('he', 0, 2)`, `$fn('e', 0, 1)` and
458 `$fn('ex', 6, 8)` respectively.
459 You may want to use this as an `$offset` argument to check if the current word
460 is an argument or a root command and the `$word` argument to autocomplete
461 partial filename matches like this:
462
463 ```php
464 $stdio->setAutocomplete(function ($word, $offset) {
465 if ($offset <= 1) {
466 // autocomplete root commands at offset=0/1 only
467 return array('cat', 'rm', 'stat');
468 } else {
469 // autocomplete all command arguments as glob pattern
470 return glob($word . '*', GLOB_MARK);
471 }
472 });
473 ```
474
475 > Note that the user may also use quotes and/or leading whitespace around the
476 root command, for example `"hell [TAB]`, in which case the offset will be
477 advanced such as this will be invoked as `$fn('hell', 1, 4)`.
478 Unless you use a more sophisticated argument parser, a decent approximation may
479 be using `$offset <= 1` to check this is a root command.
480
481 If you need even more control over autocompletion, you may also want to access
482 and/or manipulate the [input buffer](#input-buffer) and [cursor](#cursor)
483 directly like this:
484
485 ```php
486 $stdio->setAutocomplete(function () use ($stdio) {
487 if ($stdio->getInput() === 'run') {
488 $stdio->setInput('run --test --value=42');
489 $stdio->moveCursorBy(-2);
490 }
491
492 // return empty array so normal autocompletion doesn't kick in
493 return array();
494 });
495 ```
496
497 You can use a `null` value to remove the autocomplete function again and thus
498 disable the autocomplete function:
499
500 ```php
501 $stdio->setAutocomplete(null);
502 ```
503
504 #### Keys
505
506 The `Readline` class is responsible for reading user input from `STDIN` and
507 registering appropriate key events.
508 By default, `Readline` uses a hard-coded key mapping that resembles the one
509 usually found in common terminals.
510 This means that normal Unicode character keys ("a" and "b", but also "?", "ä",
511 "µ" etc.) will be processed as user input, while special control keys can be
512 used for [cursor movement](#cursor), [history](#history) and
513 [autocomplete](#autocomplete) functions.
514 Unknown special keys will be ignored and will not processed as part of the user
515 input by default.
516
517 Additionally, you can bind custom functions to any key code you want.
518 If a custom function is bound to a certain key code, the default behavior will
519 no longer trigger.
520 This allows you to register entirely new functions to keys or to overwrite any
521 of the existing behavior.
522
523 For example, you can use the following code to print some help text when the
524 user hits a certain key:
525
526 ```php
527 $stdio->on('?', function () use ($stdio) {
528 $stdio->write('Here\'s some help: …' . PHP_EOL);
529 });
530 ```
531
532 Similarly, this can be used to manipulate the user input and replace some of the
533 input when the user hits a certain key:
534
535 ```php
536 $stdio->on('ä', function () use ($stdio) {
537 $stdio->addInput('a');
538 });
539 ```
540
541 The `Readline` uses raw binary key codes as emitted by the terminal.
542 This means that you can use the normal UTF-8 character representation for normal
543 Unicode characters.
544 Special keys use binary control code sequences (refer to ANSI / VT100 control
545 codes for more details).
546 For example, the following code can be used to register a custom function to the
547 UP arrow cursor key:
548
549 ```php
550 $stdio->on("\033[A", function () use ($stdio) {
551 $stdio->setInput(strtoupper($stdio->getInput()));
552 });
553 ```
554
555 #### Bell
556
557 By default, this project will emit an audible/visible BELL signal when the user
558 tries to execute an otherwise disabled function, such as using the
559 <kbd>left</kbd> or <kbd>backspace</kbd> keys when already at the beginning of the line.
560
561 Whether or not the BELL is audible/visible depends on the termin and its
562 settings, i.e. some terminals may "beep" or flash the screen or emit a short
563 vibration.
564
565 The `setBell(bool $bell): void` method can be used to
566 enable or disable emitting the BELL signal when using a disabled function:
567
568 ```php
569 $stdio->setBell(false);
570 ```
571
572 ### ~~Readline~~
573
574 > Deprecated since v2.3.0, see [`Stdio`](#stdio) instead.
575
576 The deprecated `Readline` class is responsible for reacting to user input and
577 presenting a prompt to the user. It does so by reading individual bytes from the
578 input stream and writing the current *user input line* to the output stream.
579
580 The deprecated `Readline` class is only used internally and should no longer be
581 referenced from consuming projects.
582
583 You can access the current instance through the [`Stdio`](#stdio):
584
585 ```php
586 // deprecated
587 $readline = $stdio->getReadline();
588 ```
589
590 All methods that are available on the `Readline` instance are now available on
591 the `Stdio` class. For BC reasons, they remain available on the `Readline` class
592 until the next major release, see also above for more details.
593
594 ```php
595 // deprecated
596 $readline->setPrompt('> ');
597
598 // new
599 $stdio->setPrompt('> ');
600 ```
601
602 Internally, the `Readline` is also a well-behaving readable stream
603 (implementing ReactPHP's `ReadableStreamInterface`) that emits each complete
604 line as a `data` event, including the trailing newline.
605 This is considered advanced usage.
606
607 ## Pitfalls
608
609 The [`Stdio`](#stdio) has to redraw the current user
610 input line whenever output is written to the `STDOUT`.
611 Because of this, it is important to make sure any output is always
612 written like this instead of using `echo` statements:
613
614 ```php
615 // echo 'hello world!' . PHP_EOL;
616 $stdio->write('hello world!' . PHP_EOL);
617 ```
618
619 Depending on your program, it may or may not be reasonable to
620 replace all such occurrences.
621 As an alternative, you may utilize output buffering that will
622 automatically forward all write events to the [`Stdio`](#stdio)
623 instance like this:
624
625 ```php
626 ob_start(function ($chunk) use ($stdio) {
627 // forward write event to Stdio instead
628 $stdio->write($chunk);
629
630 // discard data from normal output handling
631 return '';
632 }, 1);
633 ```
634
635 ## Install
636
637 The recommended way to install this library is [through Composer](https://getcomposer.org/).
638 [New to Composer?](https://getcomposer.org/doc/00-intro.md)
639
640 This project follows [SemVer](https://semver.org/).
641 This will install the latest supported version:
642
643 ```bash
644 composer require clue/stdio-react:^2.7
645 ```
646
647 See also the [CHANGELOG](CHANGELOG.md) for details about version upgrades.
648
649 This project aims to run on any platform and thus does not require any PHP
650 extensions and supports running on legacy PHP 5.3 through current PHP 8+ and
651 HHVM.
652 It's *highly recommended to use the latest supported PHP version* for this project.
653
654 Internally, it will use the `ext-mbstring` to count and measure string sizes.
655 If this extension is missing, then this library will use a slightly slower Regex
656 work-around that should otherwise work equally well.
657 Installing `ext-mbstring` is highly recommended.
658
659 Internally, it will use the `ext-readline` to enable raw terminal input mode.
660 If this extension is missing, then this library will manually set the required
661 TTY settings on start and will try to restore previous settings on exit.
662 Input line editing is handled entirely within this library and does not rely on
663 `ext-readline`.
664 Installing `ext-readline` is entirely optional.
665
666 Note that *Microsoft Windows is not supported*.
667 Due to platform constraints, PHP does not provide support for reading from
668 standard console input without blocking on Windows.
669 Unfortunately, until the underlying PHP feature request is implemented (which
670 is unlikely to happen any time soon), there's little we can do in this library.
671 However, this package does work on Windows Subsystem for Linux (or WSL) without
672 issues. We suggest [installing WSL](https://msdn.microsoft.com/en-us/commandline/wsl/install_guide)
673 when you want to run this package on Windows.
674 See also [#18](https://github.com/clue/reactphp-stdio/issues/18) for more details.
675
676 ## Tests
677
678 To run the test suite, you first need to clone this repo and then install all
679 dependencies [through Composer](https://getcomposer.org/):
680
681 ```bash
682 composer install
683 ```
684
685 To run the test suite, go to the project root and run:
686
687 ```bash
688 vendor/bin/phpunit
689 ```
690
691 The test suite is set up to always ensure 100% code coverage across all
692 supported environments. If you have the Xdebug extension installed, you can also
693 generate a code coverage report locally like this:
694
695 ```bash
696 XDEBUG_MODE=coverage vendor/bin/phpunit --coverage-text
697 ```
698
699 ## License
700
701 This project is released under the permissive [MIT license](LICENSE).
702
703 > Do you use this project in a commercial setting? Sponsoring with invoicing is
704 available, contact me ([@clue](https://github.com/clue)) for details.
705
706 ## More
707
708 * If you want to learn more about processing streams of data, refer to the documentation of
709 the underlying [react/stream](https://github.com/reactphp/stream) component.
710
711 * If you build an interactive CLI tool that reads a command line from STDIN, you
712 may want to use [clue/arguments](https://github.com/clue/php-arguments) in
713 order to split this string up into its individual arguments and then use
714 [clue/commander](https://github.com/clue/php-commander) to route to registered
715 commands and their required arguments.