From 80abee3b12fe91dcba885578176a5b8bacc1ab17 Mon Sep 17 00:00:00 2001 From: Dominique Fournier Date: Tue, 12 Jun 2018 18:47:33 +0000 Subject: [PATCH] console : Allow to autocomplete with value+help, or value only git-svn-id: https://svn.fournier38.fr/svn/ProgSVN/trunk@4235 bf3deb0d-5f1a-0410-827f-c0cc1f45334c --- console.php | 38 +++++++++++++++++++++++++++++--------- 1 file changed, 29 insertions(+), 9 deletions(-) diff --git a/console.php b/console.php index c895e7f..da22604 100644 --- a/console.php +++ b/console.php @@ -240,30 +240,50 @@ class console // {{{ { $completeArr = call_user_func ($this->completionFunction, $string); + $isAssoc = is_array ($completeArr) && + array_diff_key ($completeArr, array_keys (array_keys ($completeArr))); if (count ($completeArr) === 1) { - if (substr ($string, -1) === " ") - { - // Next word is unique : add this to the string - $string .= reset ($completeArr); - } - else + if (substr ($string, -1) !== " ") { // Continuous word is unique : replace the last word by the proposal $pos = mb_strrpos ($string, " "); if ($pos === false) - $string = reset ($completeArr); + $string = ""; else { $string = mb_substr ($string, 0, $pos +1); - $string .= reset ($completeArr); } } + else + { + // Next word is unique : add this to the string + } + if ($isAssoc) + $string .= key ($completeArr); + else + $string .= reset ($completeArr); } else { // Multiple answers : display them - echo "\n".implode ("\n", $completeArr)."\n"; + if ($isAssoc) + { + // In associative array, the key is the possible answer to + // autocompletion, and the value is the helper message + // Get the largest key length to make a beautiful alignment + $maxlen = 0; + foreach ($completeArr as $key => $val) + $maxlen = max ($maxlen, mb_strlen ($key)); + $maxlen = $maxlen + 5; + echo "\n"; + foreach ($completeArr as $key => $val) + printf ("%-${maxlen}s %s\n", $key, $val); + } + else + { + echo "\n".implode ("\n", $completeArr)."\n"; + } } $cursorPos = mb_strlen ($prompt.$string); $this->rewriteLine ($prompt.$string);