4 * This file is part of Psy Shell.
6 * (c) 2012-2018 Justin Hileman
8 * For the full copyright and license information, please view the LICENSE
9 * file that was distributed with this source code.
12 namespace Psy\Readline;
17 * A Libedit-based Readline implementation.
19 * This is largely the same as the Readline implementation, but it emulates
20 * support for `readline_list_history` since PHP decided it was a good idea to
21 * ship a fake Readline implementation that is missing history support.
23 class Libedit extends GNUReadline
26 * Let's emulate GNU Readline by manually reading and parsing the history file!
30 public static function isSupported()
32 return function_exists('readline') && !function_exists('readline_list_history');
38 public function listHistory()
40 $history = file_get_contents($this->historyFile);
45 // libedit doesn't seem to support non-unix line separators.
46 $history = explode("\n", $history);
48 // shift the history signature, ensure it's valid
49 if (array_shift($history) !== '_HiStOrY_V2_') {
54 $history = array_map([$this, 'parseHistoryLine'], $history);
55 // filter empty lines & comments
56 return array_values(array_filter($history));
60 * From GNUReadline (readline/histfile.c & readline/histexpand.c):
61 * lines starting with "\0" are comments or timestamps;
62 * if "\0" is found in an entry,
63 * everything from it until the next line is a comment.
65 * @param string $line The history line to parse
67 * @return string | null
69 protected function parseHistoryLine($line)
71 // empty line, comment or timestamp
72 if (!$line || $line[0] === "\0") {
75 // if "\0" is found in an entry, then
76 // everything from it until the end of line is a comment.
77 if (($pos = strpos($line, "\0")) !== false) {
78 $line = substr($line, 0, $pos);
81 return ($line !== '') ? Str::unvis($line) : null;