Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added an edit magic command #942

Open
wants to merge 6 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
73 changes: 73 additions & 0 deletions interpreter/terminal_interface/magic_commands.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,11 +2,48 @@
import os
import subprocess
import time
import platform
import tempfile

from ..core.utils.system_debug_info import system_info
from .utils.count_tokens import count_messages_tokens
from .utils.display_markdown_message import display_markdown_message

programming_languages = {
"python": ".py",
"javascript": ".js",
"java": ".java",
"c": ".c",
"c++": ".cpp",
"c#": ".cs",
"swift": ".swift",
"kotlin": ".kt",
"ruby": ".rb",
"php": ".php",
"html": ".html",
"css": ".css",
"typescript": ".ts",
"go": ".go",
"rust": ".rs",
"perl": ".pl",
"shell": ".sh",
"objective-c": ".m",
"r": ".r",
"scala": ".scala",
"haskell": ".hs",
"lua": ".lua",
"dart": ".dart",
"groovy": ".groovy",
"matlab": ".m",
"sql": ".sql",
"assembly": ".asm",
"fortran": ".f",
"vbscript": ".vbs",
"powershell": ".ps1",
"racket": ".rkt",
"clojure": ".clj"
}


def handle_undo(self, arguments):
# Removes all messages after the most recent user entry (and the entry itself).
Expand Down Expand Up @@ -55,6 +92,7 @@ def handle_help(self, arguments):
"%tokens [prompt]": "EXPERIMENTAL: Calculate the tokens used by the next request based on the current conversation's messages and estimate the cost of that request; optionally provide a prompt to also calulate the tokens used by that prompt and the total amount of tokens that will be sent with the next request",
"%help": "Show this help message.",
"%info": "Show system and interpreter information",
"%edit": "Edit the last code"
}

base_message = ["> **Available Commands:**\n\n"]
Expand Down Expand Up @@ -172,6 +210,40 @@ def handle_count_tokens(self, prompt):

display_markdown_message("\n".join(outputs))

def handle_edit(self, arguments):
lang = 'python'
code = ''
for i in self.messages[::-1]:
if i["type"] == 'code':
lang = i['format']
code = i['content']

with tempfile.NamedTemporaryFile(mode='w+', delete=False, suffix=programming_languages[lang.lower()]) as temp_file:
temp_file.write(code)
temp_file.seek(0)
temp_filename = temp_file.name

try:
if platform.system() == 'Windows':
os.system(f'start {temp_filename}')
elif platform.system() == 'Darwin':
subprocess.call(('open', temp_filename))
elif platform.system() == 'Linux':
subprocess.call(('xdg-open', temp_filename))
else:
print(f"Unsupported OS: {platform.system()}")
except Exception as e:
print(f"Error opening file: {e}")

input("Press Enter when you have finished editing...")

with open(temp_filename, 'r') as modified_file:
modified_code = modified_file.read()

os.remove(temp_filename)

self.messages.append({'role': 'assistant', 'type': 'code', 'format': lang, 'content': modified_code})


def handle_magic_command(self, user_input):
# Handle shell
Expand All @@ -191,6 +263,7 @@ def handle_magic_command(self, user_input):
"undo": handle_undo,
"tokens": handle_count_tokens,
"info": handle_info,
"edit": handle_edit
}

user_input = user_input[1:].strip() # Capture the part after the `%`
Expand Down
3 changes: 3 additions & 0 deletions interpreter/terminal_interface/terminal_interface.py
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@

import os
import platform
import tempfile
import random
import re
import subprocess
Expand Down Expand Up @@ -44,6 +45,7 @@


def terminal_interface(interpreter, message):
global language
# Auto run and offline (this.. this isnt right) don't display messages.
# Probably worth abstracting this to something like "debug_cli" at some point.
if not interpreter.auto_run and not interpreter.offline:
Expand Down Expand Up @@ -268,6 +270,7 @@ def terminal_interface(interpreter, message):
active_block.margin_top = False # <- Aesthetic choice
active_block.language = language
active_block.code = code
break
else:
# User declined to run code.
interpreter.messages.append(
Expand Down
Loading