Add autocompletion based on the contents of the files in self.fnames.

# Context:
USER: have prompt_toolkit autocomplete based on the contents of the files in self.fnames
ASSISTANT: To add autocompletion based on the contents of the files in `self.fnames`, you can use the `Completer` class from `prompt_toolkit`. Here's how to implement it:

1. Import the necessary classes and functions from `prompt_toolkit`.
2. Create a custom completer class that inherits from `Completer`.
3. Override the `get_completions` method to provide completions based on the contents of the files.
4. Use the custom completer when calling the `prompt` function.

Here are the changes to the code:

```python
coder.py
<<<<<<< ORIGINAL
from prompt_toolkit import prompt
=======
from prompt_toolkit import prompt
from prompt_toolkit.completion import Completer, Completion
>>>>>>> UPDATED
```

```python
coder.py
<<<<<<< ORIGINAL
class Coder:
    fnames = dict()
    last_modified = 0
    repo = None
=======
class FileContentCompleter(Completer):
    def __init__(self, fnames):
        self.fnames = fnames

    def get_completions(self, document, complete_event):
        text = document.text_before_cursor
        words = text.split()
        if not words:
            return

        last_word = words[-1]
        for fname in self.fnames:
            with open(fname, "r") as f:
                content = f.read()
            for word in content.split():
                if word.startswith(last_word):
                    yield Completion(word, start_position=-len(last_word))

class Coder:
    fnames = dict()
    last_modified = 0
    repo = None
>>>>>>> UPDATED
```

```python
coder.py
<<<<<<< ORIGINAL
line = prompt("> ")
=======
completer = FileContentCompleter(self.fnames)
line = prompt("> ", completer=completer)
>>>>>>> UPDATED
```

These changes will add autocompletion based on the contents of the files in `self.fnames`.
This commit is contained in:
Paul Gauthier 2023-05-09 09:11:29 -07:00
parent 18b1809159
commit 36d15d5f37

View file

@ -5,6 +5,7 @@ import sys
import re
import traceback
from prompt_toolkit import prompt
from prompt_toolkit.completion import Completer, Completion
from rich.console import Console
from rich.prompt import Confirm, Prompt
from colorama import Fore, Style
@ -26,11 +27,28 @@ import prompts
openai.api_key = os.getenv("OPENAI_API_KEY")
class FileContentCompleter(Completer):
def __init__(self, fnames):
self.fnames = fnames
def get_completions(self, document, complete_event):
text = document.text_before_cursor
words = text.split()
if not words:
return
last_word = words[-1]
for fname in self.fnames:
with open(fname, "r") as f:
content = f.read()
for word in content.split():
if word.startswith(last_word):
yield Completion(word, start_position=-len(last_word))
class Coder:
fnames = dict()
last_modified = 0
repo = None
def __init__(self, main_model, files, pretty, history_file=".coder.history"):
self.history_file = history_file
try: