4 * This file is part of Psy Shell.
6 * (c) 2012-2017 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\TabCompletion;
14 use Psy\TabCompletion\Matcher\AbstractMatcher;
17 * A readline tab completion service.
19 * @author Marc Garcia <markcial@gmail.com>
23 /** @var Matcher\AbstractMatcher[] */
27 * Register a tab completion Matcher.
29 * @param AbstractMatcher $matcher
31 public function addMatcher(AbstractMatcher $matcher)
33 $this->matchers[] = $matcher;
37 * Activate readline tab completion.
39 public function activate()
41 readline_completion_function(array(&$this, 'callback'));
45 * Handle readline completion.
47 * @param string $input Readline current word
48 * @param int $index Current word index
49 * @param array $info readline_info() data
53 public function processCallback($input, $index, $info = array())
55 $line = substr($info['line_buffer'], 0, $info['end']);
56 $tokens = token_get_all('<?php ' . $line);
58 $tokens = array_filter($tokens, function ($token) {
59 return !AbstractMatcher::tokenIs($token, AbstractMatcher::T_WHITESPACE);
63 foreach ($this->matchers as $matcher) {
64 if ($matcher->hasMatched($tokens)) {
65 $matches = array_merge($matcher->getMatches($tokens), $matches);
69 $matches = array_unique($matches);
71 return !empty($matches) ? $matches : array('');
75 * The readline_completion_function callback handler.
77 * @see processCallback
84 public function callback($input, $index)
86 return $this->processCallback($input, $index, readline_info());
90 * Remove readline callback handler on destruct.
92 public function __destruct()
94 // PHP didn't implement the whole readline API when they first switched
95 // to libedit. And they still haven't.
97 // So this is a thing to make PsySH work on 5.3.x:
98 if (function_exists('readline_callback_handler_remove')) {
99 readline_callback_handler_remove();