Readline.php 30 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187
  1. <?php
  2. /**
  3. * Hoa
  4. *
  5. *
  6. * @license
  7. *
  8. * New BSD License
  9. *
  10. * Copyright © 2007-2017, Hoa community. All rights reserved.
  11. *
  12. * Redistribution and use in source and binary forms, with or without
  13. * modification, are permitted provided that the following conditions are met:
  14. * * Redistributions of source code must retain the above copyright
  15. * notice, this list of conditions and the following disclaimer.
  16. * * Redistributions in binary form must reproduce the above copyright
  17. * notice, this list of conditions and the following disclaimer in the
  18. * documentation and/or other materials provided with the distribution.
  19. * * Neither the name of the Hoa nor the names of its contributors may be
  20. * used to endorse or promote products derived from this software without
  21. * specific prior written permission.
  22. *
  23. * THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
  24. * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  25. * IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  26. * ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDERS AND CONTRIBUTORS BE
  27. * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  28. * CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  29. * SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  30. * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  31. * CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  32. * ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  33. * POSSIBILITY OF SUCH DAMAGE.
  34. */
  35. namespace Hoa\Console\Readline;
  36. use Hoa\Consistency;
  37. use Hoa\Console;
  38. use Hoa\Ustring;
  39. /**
  40. * Class \Hoa\Console\Readline.
  41. *
  42. * Read, edit, bind… a line from the input.
  43. *
  44. * @copyright Copyright © 2007-2017 Hoa community
  45. * @license New BSD License
  46. */
  47. class Readline
  48. {
  49. /**
  50. * State: continue to read.
  51. *
  52. * @const int
  53. */
  54. const STATE_CONTINUE = 1;
  55. /**
  56. * State: stop to read.
  57. *
  58. * @const int
  59. */
  60. const STATE_BREAK = 2;
  61. /**
  62. * State: no output the current buffer.
  63. *
  64. * @const int
  65. */
  66. const STATE_NO_ECHO = 4;
  67. /**
  68. * Current editing line.
  69. *
  70. * @var string
  71. */
  72. protected $_line = null;
  73. /**
  74. * Current editing line seek.
  75. *
  76. * @var int
  77. */
  78. protected $_lineCurrent = 0;
  79. /**
  80. * Current editing line length.
  81. *
  82. * @var int
  83. */
  84. protected $_lineLength = 0;
  85. /**
  86. * Current buffer (most of the time, a char).
  87. *
  88. * @var string
  89. */
  90. protected $_buffer = null;
  91. /**
  92. * Mapping.
  93. *
  94. * @var array
  95. */
  96. protected $_mapping = [];
  97. /**
  98. * History.
  99. *
  100. * @var array
  101. */
  102. protected $_history = [];
  103. /**
  104. * History current position.
  105. *
  106. * @var int
  107. */
  108. protected $_historyCurrent = 0;
  109. /**
  110. * History size.
  111. *
  112. * @var int
  113. */
  114. protected $_historySize = 0;
  115. /**
  116. * Prefix.
  117. *
  118. * @var string
  119. */
  120. protected $_prefix = null;
  121. /**
  122. * Autocompleter.
  123. *
  124. * @var \Hoa\Console\Readline\Autocompleter
  125. */
  126. protected $_autocompleter = null;
  127. /**
  128. * Initialize the readline editor.
  129. *
  130. */
  131. public function __construct()
  132. {
  133. if (OS_WIN) {
  134. return;
  135. }
  136. $this->_mapping["\033[A"] = xcallable($this, '_bindArrowUp');
  137. $this->_mapping["\033[B"] = xcallable($this, '_bindArrowDown');
  138. $this->_mapping["\033[C"] = xcallable($this, '_bindArrowRight');
  139. $this->_mapping["\033[D"] = xcallable($this, '_bindArrowLeft');
  140. $this->_mapping["\001"] = xcallable($this, '_bindControlA');
  141. $this->_mapping["\002"] = xcallable($this, '_bindControlB');
  142. $this->_mapping["\005"] = xcallable($this, '_bindControlE');
  143. $this->_mapping["\006"] = xcallable($this, '_bindControlF');
  144. $this->_mapping["\010"] =
  145. $this->_mapping["\177"] = xcallable($this, '_bindBackspace');
  146. $this->_mapping["\027"] = xcallable($this, '_bindControlW');
  147. $this->_mapping["\n"] = xcallable($this, '_bindNewline');
  148. $this->_mapping["\t"] = xcallable($this, '_bindTab');
  149. return;
  150. }
  151. /**
  152. * Read a line from the input.
  153. *
  154. * @param string $prefix Prefix.
  155. * @return string
  156. */
  157. public function readLine($prefix = null)
  158. {
  159. $input = Console::getInput();
  160. if (true === $input->eof()) {
  161. return false;
  162. }
  163. $direct = Console::isDirect($input->getStream()->getStream());
  164. $output = Console::getOutput();
  165. if (false === $direct || OS_WIN) {
  166. $out = $input->readLine();
  167. if (false === $out) {
  168. return false;
  169. }
  170. $out = substr($out, 0, -1);
  171. if (true === $direct) {
  172. $output->writeAll($prefix);
  173. } else {
  174. $output->writeAll($prefix . $out . "\n");
  175. }
  176. return $out;
  177. }
  178. $this->resetLine();
  179. $this->setPrefix($prefix);
  180. $read = [$input->getStream()->getStream()];
  181. $output->writeAll($prefix);
  182. while (true) {
  183. @stream_select($read, $write, $except, 30, 0);
  184. if (empty($read)) {
  185. $read = [$input->getStream()->getStream()];
  186. continue;
  187. }
  188. $char = $this->_read();
  189. $this->_buffer = $char;
  190. $return = $this->_readLine($char);
  191. if (0 === ($return & self::STATE_NO_ECHO)) {
  192. $output->writeAll($this->_buffer);
  193. }
  194. if (0 !== ($return & self::STATE_BREAK)) {
  195. break;
  196. }
  197. }
  198. return $this->getLine();
  199. }
  200. /**
  201. * Readline core.
  202. *
  203. * @param string $char Char.
  204. * @return string
  205. */
  206. public function _readLine($char)
  207. {
  208. if (isset($this->_mapping[$char]) &&
  209. is_callable($this->_mapping[$char])) {
  210. $mapping = $this->_mapping[$char];
  211. return $mapping($this);
  212. }
  213. if (isset($this->_mapping[$char])) {
  214. $this->_buffer = $this->_mapping[$char];
  215. } elseif (false === Ustring::isCharPrintable($char)) {
  216. Console\Cursor::bip();
  217. return static::STATE_CONTINUE | static::STATE_NO_ECHO;
  218. }
  219. if ($this->getLineLength() == $this->getLineCurrent()) {
  220. $this->appendLine($this->_buffer);
  221. return static::STATE_CONTINUE;
  222. }
  223. $this->insertLine($this->_buffer);
  224. $tail = mb_substr(
  225. $this->getLine(),
  226. $this->getLineCurrent() - 1
  227. );
  228. $this->_buffer = "\033[K" . $tail . str_repeat(
  229. "\033[D",
  230. mb_strlen($tail) - 1
  231. );
  232. return static::STATE_CONTINUE;
  233. }
  234. /**
  235. * Add mappings.
  236. *
  237. * @param array $mappings Mappings.
  238. * @return void
  239. */
  240. public function addMappings(array $mappings)
  241. {
  242. foreach ($mappings as $key => $mapping) {
  243. $this->addMapping($key, $mapping);
  244. }
  245. return;
  246. }
  247. /**
  248. * Add a mapping.
  249. * Supported key:
  250. * • \e[… for \033[…;
  251. * • \C-… for Ctrl-…;
  252. * • abc for a simple mapping.
  253. * A mapping is a callable that has only one parameter of type
  254. * Hoa\Console\Readline and that returns a self::STATE_* constant.
  255. *
  256. * @param string $key Key.
  257. * @param mixed $mapping Mapping (a callable).
  258. * @return void
  259. */
  260. public function addMapping($key, $mapping)
  261. {
  262. if ('\e[' === substr($key, 0, 3)) {
  263. $this->_mapping["\033[" . substr($key, 3)] = $mapping;
  264. } elseif ('\C-' === substr($key, 0, 3)) {
  265. $_key = ord(strtolower(substr($key, 3))) - 96;
  266. $this->_mapping[chr($_key)] = $mapping;
  267. } else {
  268. $this->_mapping[$key] = $mapping;
  269. }
  270. return;
  271. }
  272. /**
  273. * Add an entry in the history.
  274. *
  275. * @param string $line Line.
  276. * @return void
  277. */
  278. public function addHistory($line = null)
  279. {
  280. if (empty($line)) {
  281. return;
  282. }
  283. $this->_history[] = $line;
  284. $this->_historyCurrent = $this->_historySize++;
  285. return;
  286. }
  287. /**
  288. * Clear history.
  289. *
  290. * @return void
  291. */
  292. public function clearHistory()
  293. {
  294. unset($this->_history);
  295. $this->_history = [];
  296. $this->_historyCurrent = 0;
  297. $this->_historySize = 1;
  298. return;
  299. }
  300. /**
  301. * Get an entry in the history.
  302. *
  303. * @param int $i Index of the entry.
  304. * @return string
  305. */
  306. public function getHistory($i = null)
  307. {
  308. if (null === $i) {
  309. $i = $this->_historyCurrent;
  310. }
  311. if (!isset($this->_history[$i])) {
  312. return null;
  313. }
  314. return $this->_history[$i];
  315. }
  316. /**
  317. * Go backward in the history.
  318. *
  319. * @return string
  320. */
  321. public function previousHistory()
  322. {
  323. if (0 >= $this->_historyCurrent) {
  324. return $this->getHistory(0);
  325. }
  326. return $this->getHistory($this->_historyCurrent--);
  327. }
  328. /**
  329. * Go forward in the history.
  330. *
  331. * @return string
  332. */
  333. public function nextHistory()
  334. {
  335. if ($this->_historyCurrent + 1 >= $this->_historySize) {
  336. return $this->getLine();
  337. }
  338. return $this->getHistory(++$this->_historyCurrent);
  339. }
  340. /**
  341. * Get current line.
  342. *
  343. * @return string
  344. */
  345. public function getLine()
  346. {
  347. return $this->_line;
  348. }
  349. /**
  350. * Append to current line.
  351. *
  352. * @param string $append String to append.
  353. * @return void
  354. */
  355. public function appendLine($append)
  356. {
  357. $this->_line .= $append;
  358. $this->_lineLength = mb_strlen($this->_line);
  359. $this->_lineCurrent = $this->_lineLength;
  360. return;
  361. }
  362. /**
  363. * Insert into current line at the current seek.
  364. *
  365. * @param string $insert String to insert.
  366. * @return void
  367. */
  368. public function insertLine($insert)
  369. {
  370. if ($this->_lineLength == $this->_lineCurrent) {
  371. return $this->appendLine($insert);
  372. }
  373. $this->_line = mb_substr($this->_line, 0, $this->_lineCurrent) .
  374. $insert .
  375. mb_substr($this->_line, $this->_lineCurrent);
  376. $this->_lineLength = mb_strlen($this->_line);
  377. $this->_lineCurrent += mb_strlen($insert);
  378. return;
  379. }
  380. /**
  381. * Reset current line.
  382. *
  383. * @return void
  384. */
  385. protected function resetLine()
  386. {
  387. $this->_line = null;
  388. $this->_lineCurrent = 0;
  389. $this->_lineLength = 0;
  390. return;
  391. }
  392. /**
  393. * Get current line seek.
  394. *
  395. * @return int
  396. */
  397. public function getLineCurrent()
  398. {
  399. return $this->_lineCurrent;
  400. }
  401. /**
  402. * Get current line length.
  403. *
  404. * @return int
  405. */
  406. public function getLineLength()
  407. {
  408. return $this->_lineLength;
  409. }
  410. /**
  411. * Set prefix.
  412. *
  413. * @param string $prefix Prefix.
  414. * @return void
  415. */
  416. public function setPrefix($prefix)
  417. {
  418. $this->_prefix = $prefix;
  419. return;
  420. }
  421. /**
  422. * Get prefix.
  423. *
  424. * @return string
  425. */
  426. public function getPrefix()
  427. {
  428. return $this->_prefix;
  429. }
  430. /**
  431. * Get buffer. Not for user.
  432. *
  433. * @return string
  434. */
  435. public function getBuffer()
  436. {
  437. return $this->_buffer;
  438. }
  439. /**
  440. * Set an autocompleter.
  441. *
  442. * @param \Hoa\Console\Readline\Autocompleter $autocompleter Auto-completer.
  443. * @return \Hoa\Console\Readline\Autocompleter
  444. */
  445. public function setAutocompleter(Autocompleter $autocompleter)
  446. {
  447. $old = $this->_autocompleter;
  448. $this->_autocompleter = $autocompleter;
  449. return $old;
  450. }
  451. /**
  452. * Get the autocompleter.
  453. *
  454. * @return \Hoa\Console\Readline\Autocompleter
  455. */
  456. public function getAutocompleter()
  457. {
  458. return $this->_autocompleter;
  459. }
  460. /**
  461. * Read on input. Not for user.
  462. *
  463. * @param int $length Length.
  464. * @return string
  465. */
  466. public function _read($length = 512)
  467. {
  468. return Console::getInput()->read($length);
  469. }
  470. /**
  471. * Set current line. Not for user.
  472. *
  473. * @param string $line Line.
  474. * @return void
  475. */
  476. public function setLine($line)
  477. {
  478. $this->_line = $line;
  479. $this->_lineLength = mb_strlen($this->_line);
  480. $this->_lineCurrent = $this->_lineLength;
  481. return;
  482. }
  483. /**
  484. * Set current line seek. Not for user.
  485. *
  486. * @param int $current Seek.
  487. * @return void
  488. */
  489. public function setLineCurrent($current)
  490. {
  491. $this->_lineCurrent = $current;
  492. return;
  493. }
  494. /**
  495. * Set line length. Not for user.
  496. *
  497. * @param int $length Length.
  498. * @return void
  499. */
  500. public function setLineLength($length)
  501. {
  502. $this->_lineLength = $length;
  503. return;
  504. }
  505. /**
  506. * Set buffer. Not for user.
  507. *
  508. * @param string $buffer Buffer.
  509. * @return string
  510. */
  511. public function setBuffer($buffer)
  512. {
  513. $this->_buffer = $buffer;
  514. return;
  515. }
  516. /**
  517. * Up arrow binding.
  518. * Go backward in the history.
  519. *
  520. * @param \Hoa\Console\Readline $self Self.
  521. * @return int
  522. */
  523. public function _bindArrowUp(Readline $self)
  524. {
  525. if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) {
  526. Console\Cursor::clear('↔');
  527. Console::getOutput()->writeAll($self->getPrefix());
  528. }
  529. $self->setBuffer($buffer = $self->previousHistory());
  530. $self->setLine($buffer);
  531. return static::STATE_CONTINUE;
  532. }
  533. /**
  534. * Down arrow binding.
  535. * Go forward in the history.
  536. *
  537. * @param \Hoa\Console\Readline $self Self.
  538. * @return int
  539. */
  540. public function _bindArrowDown(Readline $self)
  541. {
  542. if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) {
  543. Console\Cursor::clear('↔');
  544. Console::getOutput()->writeAll($self->getPrefix());
  545. }
  546. $self->setBuffer($buffer = $self->nextHistory());
  547. $self->setLine($buffer);
  548. return static::STATE_CONTINUE;
  549. }
  550. /**
  551. * Right arrow binding.
  552. * Move cursor to the right.
  553. *
  554. * @param \Hoa\Console\Readline $self Self.
  555. * @return int
  556. */
  557. public function _bindArrowRight(Readline $self)
  558. {
  559. if ($self->getLineLength() > $self->getLineCurrent()) {
  560. if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) {
  561. Console\Cursor::move('→');
  562. }
  563. $self->setLineCurrent($self->getLineCurrent() + 1);
  564. }
  565. $self->setBuffer(null);
  566. return static::STATE_CONTINUE;
  567. }
  568. /**
  569. * Left arrow binding.
  570. * Move cursor to the left.
  571. *
  572. * @param \Hoa\Console\Readline $self Self.
  573. * @return int
  574. */
  575. public function _bindArrowLeft(Readline $self)
  576. {
  577. if (0 < $self->getLineCurrent()) {
  578. if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) {
  579. Console\Cursor::move('←');
  580. }
  581. $self->setLineCurrent($self->getLineCurrent() - 1);
  582. }
  583. $self->setBuffer(null);
  584. return static::STATE_CONTINUE;
  585. }
  586. /**
  587. * Backspace and Control-H binding.
  588. * Delete the first character at the right of the cursor.
  589. *
  590. * @param \Hoa\Console\Readline $self Self.
  591. * @return int
  592. */
  593. public function _bindBackspace(Readline $self)
  594. {
  595. $buffer = null;
  596. if (0 < $self->getLineCurrent()) {
  597. if (0 === (static::STATE_CONTINUE & static::STATE_NO_ECHO)) {
  598. Console\Cursor::move('←');
  599. Console\Cursor::clear('→');
  600. }
  601. if ($self->getLineLength() == $current = $self->getLineCurrent()) {
  602. $self->setLine(mb_substr($self->getLine(), 0, -1));
  603. } else {
  604. $line = $self->getLine();
  605. $current = $self->getLineCurrent();
  606. $tail = mb_substr($line, $current);
  607. $buffer = $tail . str_repeat("\033[D", mb_strlen($tail));
  608. $self->setLine(mb_substr($line, 0, $current - 1) . $tail);
  609. $self->setLineCurrent($current - 1);
  610. }
  611. }
  612. $self->setBuffer($buffer);
  613. return static::STATE_CONTINUE;
  614. }
  615. /**
  616. * Control-A binding.
  617. * Move cursor to beginning of line.
  618. *
  619. * @param \Hoa\Console\Readline $self Self.
  620. * @return int
  621. */
  622. public function _bindControlA(Readline $self)
  623. {
  624. for ($i = $self->getLineCurrent() - 1; 0 <= $i; --$i) {
  625. $self->_bindArrowLeft($self);
  626. }
  627. return static::STATE_CONTINUE;
  628. }
  629. /**
  630. * Control-B binding.
  631. * Move cursor backward one word.
  632. *
  633. * @param \Hoa\Console\Readline $self Self.
  634. * @return int
  635. */
  636. public function _bindControlB(Readline $self)
  637. {
  638. $current = $self->getLineCurrent();
  639. if (0 === $current) {
  640. return static::STATE_CONTINUE;
  641. }
  642. $words = preg_split(
  643. '#\b#u',
  644. $self->getLine(),
  645. -1,
  646. PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_NO_EMPTY
  647. );
  648. for (
  649. $i = 0, $max = count($words) - 1;
  650. $i < $max && $words[$i + 1][1] < $current;
  651. ++$i
  652. );
  653. for ($j = $words[$i][1] + 1; $current >= $j; ++$j) {
  654. $self->_bindArrowLeft($self);
  655. }
  656. return static::STATE_CONTINUE;
  657. }
  658. /**
  659. * Control-E binding.
  660. * Move cursor to end of line.
  661. *
  662. * @param \Hoa\Console\Readline $self Self.
  663. * @return int
  664. */
  665. public function _bindControlE(Readline $self)
  666. {
  667. for (
  668. $i = $self->getLineCurrent(), $max = $self->getLineLength();
  669. $i < $max;
  670. ++$i
  671. ) {
  672. $self->_bindArrowRight($self);
  673. }
  674. return static::STATE_CONTINUE;
  675. }
  676. /**
  677. * Control-F binding.
  678. * Move cursor forward one word.
  679. *
  680. * @param \Hoa\Console\Readline $self Self.
  681. * @return int
  682. */
  683. public function _bindControlF(Readline $self)
  684. {
  685. $current = $self->getLineCurrent();
  686. if ($self->getLineLength() === $current) {
  687. return static::STATE_CONTINUE;
  688. }
  689. $words = preg_split(
  690. '#\b#u',
  691. $self->getLine(),
  692. -1,
  693. PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_NO_EMPTY
  694. );
  695. for (
  696. $i = 0, $max = count($words) - 1;
  697. $i < $max && $words[$i][1] < $current;
  698. ++$i
  699. );
  700. if (!isset($words[$i + 1])) {
  701. $words[$i + 1] = [1 => $self->getLineLength()];
  702. }
  703. for ($j = $words[$i + 1][1]; $j > $current; --$j) {
  704. $self->_bindArrowRight($self);
  705. }
  706. return static::STATE_CONTINUE;
  707. }
  708. /**
  709. * Control-W binding.
  710. * Delete first backward word.
  711. *
  712. * @param \Hoa\Console\Readline $self Self.
  713. * @return int
  714. */
  715. public function _bindControlW(Readline $self)
  716. {
  717. $current = $self->getLineCurrent();
  718. if (0 === $current) {
  719. return static::STATE_CONTINUE;
  720. }
  721. $words = preg_split(
  722. '#\b#u',
  723. $self->getLine(),
  724. -1,
  725. PREG_SPLIT_OFFSET_CAPTURE | PREG_SPLIT_NO_EMPTY
  726. );
  727. for (
  728. $i = 0, $max = count($words) - 1;
  729. $i < $max && $words[$i + 1][1] < $current;
  730. ++$i
  731. );
  732. for ($j = $words[$i][1] + 1; $current >= $j; ++$j) {
  733. $self->_bindBackspace($self);
  734. }
  735. return static::STATE_CONTINUE;
  736. }
  737. /**
  738. * Newline binding.
  739. *
  740. * @param \Hoa\Console\Readline $self Self.
  741. * @return int
  742. */
  743. public function _bindNewline(Readline $self)
  744. {
  745. $self->addHistory($self->getLine());
  746. return static::STATE_BREAK;
  747. }
  748. /**
  749. * Tab binding.
  750. *
  751. * @param \Hoa\Console\Readline $self Self.
  752. * @return int
  753. */
  754. public function _bindTab(Readline $self)
  755. {
  756. $output = Console::getOutput();
  757. $autocompleter = $self->getAutocompleter();
  758. $state = static::STATE_CONTINUE | static::STATE_NO_ECHO;
  759. if (null === $autocompleter) {
  760. return $state;
  761. }
  762. $current = $self->getLineCurrent();
  763. $line = $self->getLine();
  764. if (0 === $current) {
  765. return $state;
  766. }
  767. $matches = preg_match_all(
  768. '#' . $autocompleter->getWordDefinition() . '$#u',
  769. mb_substr($line, 0, $current),
  770. $words
  771. );
  772. if (0 === $matches) {
  773. return $state;
  774. }
  775. $word = $words[0][0];
  776. if ('' === trim($word)) {
  777. return $state;
  778. }
  779. $solution = $autocompleter->complete($word);
  780. $length = mb_strlen($word);
  781. if (null === $solution) {
  782. return $state;
  783. }
  784. if (is_array($solution)) {
  785. $_solution = $solution;
  786. $count = count($_solution) - 1;
  787. $cWidth = 0;
  788. $window = Console\Window::getSize();
  789. $wWidth = $window['x'];
  790. $cursor = Console\Cursor::getPosition();
  791. array_walk($_solution, function (&$value) use (&$cWidth) {
  792. $handle = mb_strlen($value);
  793. if ($handle > $cWidth) {
  794. $cWidth = $handle;
  795. }
  796. return;
  797. });
  798. array_walk($_solution, function (&$value) use (&$cWidth) {
  799. $handle = mb_strlen($value);
  800. if ($handle >= $cWidth) {
  801. return;
  802. }
  803. $value .= str_repeat(' ', $cWidth - $handle);
  804. return;
  805. });
  806. $mColumns = (int) floor($wWidth / ($cWidth + 2));
  807. $mLines = (int) ceil(($count + 1) / $mColumns);
  808. --$mColumns;
  809. $i = 0;
  810. if (0 > $window['y'] - $cursor['y'] - $mLines) {
  811. Console\Window::scroll('↑', $mLines);
  812. Console\Cursor::move('↑', $mLines);
  813. }
  814. Console\Cursor::save();
  815. Console\Cursor::hide();
  816. Console\Cursor::move('↓ LEFT');
  817. Console\Cursor::clear('↓');
  818. foreach ($_solution as $j => $s) {
  819. $output->writeAll("\033[0m" . $s . "\033[0m");
  820. if ($i++ < $mColumns) {
  821. $output->writeAll(' ');
  822. } else {
  823. $i = 0;
  824. if (isset($_solution[$j + 1])) {
  825. $output->writeAll("\n");
  826. }
  827. }
  828. }
  829. Console\Cursor::restore();
  830. Console\Cursor::show();
  831. ++$mColumns;
  832. $input = Console::getInput();
  833. $read = [$input->getStream()->getStream()];
  834. $mColumn = -1;
  835. $mLine = -1;
  836. $coord = -1;
  837. $unselect = function () use (
  838. &$mColumn,
  839. &$mLine,
  840. &$coord,
  841. &$_solution,
  842. &$cWidth,
  843. $output
  844. ) {
  845. Console\Cursor::save();
  846. Console\Cursor::hide();
  847. Console\Cursor::move('↓ LEFT');
  848. Console\Cursor::move('→', $mColumn * ($cWidth + 2));
  849. Console\Cursor::move('↓', $mLine);
  850. $output->writeAll("\033[0m" . $_solution[$coord] . "\033[0m");
  851. Console\Cursor::restore();
  852. Console\Cursor::show();
  853. return;
  854. };
  855. $select = function () use (
  856. &$mColumn,
  857. &$mLine,
  858. &$coord,
  859. &$_solution,
  860. &$cWidth,
  861. $output
  862. ) {
  863. Console\Cursor::save();
  864. Console\Cursor::hide();
  865. Console\Cursor::move('↓ LEFT');
  866. Console\Cursor::move('→', $mColumn * ($cWidth + 2));
  867. Console\Cursor::move('↓', $mLine);
  868. $output->writeAll("\033[7m" . $_solution[$coord] . "\033[0m");
  869. Console\Cursor::restore();
  870. Console\Cursor::show();
  871. return;
  872. };
  873. $init = function () use (
  874. &$mColumn,
  875. &$mLine,
  876. &$coord,
  877. &$select
  878. ) {
  879. $mColumn = 0;
  880. $mLine = 0;
  881. $coord = 0;
  882. $select();
  883. return;
  884. };
  885. while (true) {
  886. @stream_select($read, $write, $except, 30, 0);
  887. if (empty($read)) {
  888. $read = [$input->getStream()->getStream()];
  889. continue;
  890. }
  891. switch ($char = $self->_read()) {
  892. case "\033[A":
  893. if (-1 === $mColumn && -1 === $mLine) {
  894. $init();
  895. break;
  896. }
  897. $unselect();
  898. $coord = max(0, $coord - $mColumns);
  899. $mLine = (int) floor($coord / $mColumns);
  900. $mColumn = $coord % $mColumns;
  901. $select();
  902. break;
  903. case "\033[B":
  904. if (-1 === $mColumn && -1 === $mLine) {
  905. $init();
  906. break;
  907. }
  908. $unselect();
  909. $coord = min($count, $coord + $mColumns);
  910. $mLine = (int) floor($coord / $mColumns);
  911. $mColumn = $coord % $mColumns;
  912. $select();
  913. break;
  914. case "\t":
  915. case "\033[C":
  916. if (-1 === $mColumn && -1 === $mLine) {
  917. $init();
  918. break;
  919. }
  920. $unselect();
  921. $coord = min($count, $coord + 1);
  922. $mLine = (int) floor($coord / $mColumns);
  923. $mColumn = $coord % $mColumns;
  924. $select();
  925. break;
  926. case "\033[D":
  927. if (-1 === $mColumn && -1 === $mLine) {
  928. $init();
  929. break;
  930. }
  931. $unselect();
  932. $coord = max(0, $coord - 1);
  933. $mLine = (int) floor($coord / $mColumns);
  934. $mColumn = $coord % $mColumns;
  935. $select();
  936. break;
  937. case "\n":
  938. if (-1 !== $mColumn && -1 !== $mLine) {
  939. $tail = mb_substr($line, $current);
  940. $current -= $length;
  941. $self->setLine(
  942. mb_substr($line, 0, $current) .
  943. $solution[$coord] .
  944. $tail
  945. );
  946. $self->setLineCurrent(
  947. $current + mb_strlen($solution[$coord])
  948. );
  949. Console\Cursor::move('←', $length);
  950. $output->writeAll($solution[$coord]);
  951. Console\Cursor::clear('→');
  952. $output->writeAll($tail);
  953. Console\Cursor::move('←', mb_strlen($tail));
  954. }
  955. default:
  956. $mColumn = -1;
  957. $mLine = -1;
  958. $coord = -1;
  959. Console\Cursor::save();
  960. Console\Cursor::move('↓ LEFT');
  961. Console\Cursor::clear('↓');
  962. Console\Cursor::restore();
  963. if ("\033" !== $char && "\n" !== $char) {
  964. $self->setBuffer($char);
  965. return $self->_readLine($char);
  966. }
  967. break 2;
  968. }
  969. }
  970. return $state;
  971. }
  972. $tail = mb_substr($line, $current);
  973. $current -= $length;
  974. $self->setLine(
  975. mb_substr($line, 0, $current) .
  976. $solution .
  977. $tail
  978. );
  979. $self->setLineCurrent(
  980. $current + mb_strlen($solution)
  981. );
  982. Console\Cursor::move('←', $length);
  983. $output->writeAll($solution);
  984. Console\Cursor::clear('→');
  985. $output->writeAll($tail);
  986. Console\Cursor::move('←', mb_strlen($tail));
  987. return $state;
  988. }
  989. }
  990. /**
  991. * Advanced interaction.
  992. */
  993. Console::advancedInteraction();
  994. /**
  995. * Flex entity.
  996. */
  997. Consistency::flexEntity('Hoa\Console\Readline\Readline');