Used by dict_key_matches, matching the prefix to a list of keys Parameters ========== keys: list of keys in dictionary currently being completed. prefix: Part of the text already typed by the user. e.g. `mydict[b'fo` delims: String of delimiters to consid
(keys: List[str], prefix: str, delims: str)
| 744 | |
| 745 | |
| 746 | def match_dict_keys(keys: List[str], prefix: str, delims: str): |
| 747 | """Used by dict_key_matches, matching the prefix to a list of keys |
| 748 | |
| 749 | Parameters |
| 750 | ========== |
| 751 | keys: |
| 752 | list of keys in dictionary currently being completed. |
| 753 | prefix: |
| 754 | Part of the text already typed by the user. e.g. `mydict[b'fo` |
| 755 | delims: |
| 756 | String of delimiters to consider when finding the current key. |
| 757 | |
| 758 | Returns |
| 759 | ======= |
| 760 | |
| 761 | A tuple of three elements: ``quote``, ``token_start``, ``matched``, with |
| 762 | ``quote`` being the quote that need to be used to close current string. |
| 763 | ``token_start`` the position where the replacement should start occurring, |
| 764 | ``matches`` a list of replacement/completion |
| 765 | |
| 766 | """ |
| 767 | if not prefix: |
| 768 | return None, 0, [repr(k) for k in keys |
| 769 | if isinstance(k, (str, bytes))] |
| 770 | quote_match = re.search('["\']', prefix) |
| 771 | quote = quote_match.group() |
| 772 | try: |
| 773 | prefix_str = eval(prefix + quote, {}) |
| 774 | except Exception: |
| 775 | return None, 0, [] |
| 776 | |
| 777 | pattern = '[^' + ''.join('\\' + c for c in delims) + ']*$' |
| 778 | token_match = re.search(pattern, prefix, re.UNICODE) |
| 779 | token_start = token_match.start() |
| 780 | token_prefix = token_match.group() |
| 781 | |
| 782 | matched = [] |
| 783 | for key in keys: |
| 784 | try: |
| 785 | if not key.startswith(prefix_str): |
| 786 | continue |
| 787 | except (AttributeError, TypeError, UnicodeError): |
| 788 | # Python 3+ TypeError on b'a'.startswith('a') or vice-versa |
| 789 | continue |
| 790 | |
| 791 | # reformat remainder of key to begin with prefix |
| 792 | rem = key[len(prefix_str):] |
| 793 | # force repr wrapped in ' |
| 794 | rem_repr = repr(rem + '"') if isinstance(rem, str) else repr(rem + b'"') |
| 795 | if rem_repr.startswith('u') and prefix[0] not in 'uU': |
| 796 | # Found key is unicode, but prefix is Py2 string. |
| 797 | # Therefore attempt to interpret key as string. |
| 798 | try: |
| 799 | rem_repr = repr(rem.encode('ascii') + '"') |
| 800 | except UnicodeEncodeError: |
| 801 | continue |
| 802 | |
| 803 | rem_repr = rem_repr[1 + rem_repr.index("'"):-2] |