Created
August 26, 2024 04:48
-
-
Save tinvaan/e7539ab3edaa0bfc6f0fa230bc97c96a to your computer and use it in GitHub Desktop.
Editor autocomplete suggestions example
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| # pylint: disable-all | |
| """ | |
| $ pip install suffix-tree | |
| """ | |
| from suffix_tree import Tree as SuffixTree | |
| WILDCARDS = [ | |
| '.', ' ', ',', ':', ';', '"', '(', ')', '[', ']', '{', '}', | |
| '\'', '"', '_', '+', '-', '*', '/', '%', '=', '\n', '\t' | |
| ] | |
| class MagicEditor: | |
| def __init__(self): | |
| self.tokens = set() | |
| self.tree = SuffixTree() | |
| def save(self, edits): | |
| """Save fresh contents to the lookup""" | |
| contents = edits.strip() | |
| for ch in WILDCARDS: | |
| contents = ' '.join(contents.split(ch)) | |
| for idx, content in enumerate(contents.split(' ')): | |
| if content and content not in WILDCARDS: | |
| content = content.strip().replace(' ', '') | |
| # Add to token to lookup tree | |
| self.tokens.add(content) | |
| self.tree.add(idx, content) | |
| def suggest(self, curr=""): | |
| """Provide a list of completion suggestions for the current word.""" | |
| completions = set() | |
| for _, ref in [m for m in self.tree.find_all(curr)]: | |
| match = ''.join(ref.S[ref.start:ref.end - 1]) | |
| if match in self.tokens and match not in completions: | |
| completions.add(match) | |
| return list(completions) | |
| if __name__ == '__main__': | |
| editor = MagicEditor() | |
| editor.save(''' | |
| def foo(): | |
| return "bar" + "1" | |
| ''') | |
| print("re: ", editor.suggest("re")) | |
| editor.save(''' | |
| def suggest(self, curr=""): | |
| """Provide a list of completion suggestions for the current word.""" | |
| completions = [] | |
| for _, ref in [m for m in self.tree.find_all(curr)]: | |
| match = ''.join(ref.S[ref.start:ref.end - 1]) | |
| if match in self.tokens: | |
| completions.append(match) | |
| return completions | |
| ''') | |
| print("f: ", editor.suggest("f")) | |
| print("fo: ", editor.suggest("fo")) | |
| print("r: ", editor.suggest("r")) | |
| print("s: ", editor.suggest("s")) | |
| print("t: ", editor.suggest("t")) | |
| print("'': ", editor.suggest("")) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Uh oh!
There was an error while loading. Please reload this page.