Skip to content

Instantly share code, notes, and snippets.

@tinvaan
Created August 26, 2024 04:48
Show Gist options
  • Select an option

  • Save tinvaan/e7539ab3edaa0bfc6f0fa230bc97c96a to your computer and use it in GitHub Desktop.

Select an option

Save tinvaan/e7539ab3edaa0bfc6f0fa230bc97c96a to your computer and use it in GitHub Desktop.
Editor autocomplete suggestions example
# 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(""))
@tinvaan
Copy link
Author

tinvaan commented Aug 26, 2024

$ pip install suffix-tree

$ python autocmp.py

re:  ['return']
f:  ['for', 'foo', 'find']
fo:  ['for', 'foo']
r:  ['ref', 'return']
s:  ['suggestions', 'start', 'suggest', 'self']
t:  ['tree', 'the', 'tokens']
'':  ['find', 'foo', 'current', 'Provide', 'of', 'tokens', 'word', 'bar', 'the', 'all', 'end', 'self', '1', 'tree', 'suggestions', 'ref', 'append', 'match', 'def', 'curr', 'suggest', 'start', 'completions', 'in', 'return', 'if', 'for', 'S', 'list', 'completion', 'a', 'join', 'm']

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment