Write a Python program to create a terminal-based text editor.
- User
Write a Python program to create a terminal-based text editor.
Assistant
Conceptualizing the Interface
I'm starting to visualize the interface. Need to nail down the core interactions: how the cursor moves, how text input works, and the commands for saving and exiting. Thinking about the minimal features for a usable editor. It needs to be easy to use from the command line, with clear keystrokes. I'm focusing on the essential features for now.
Considering Core Functionality
I'm now prioritizing fundamental features within the
cursesframework. Initializing the screen and handling basic input is crucial. Considering the use ofcurses.wrapperfor setup and teardown. Next, I need to design the data structure to store the text and establish a simple input loop.Decomposing the Requirements
My approach is breaking down the editor into modular components. I'm focusing on the core aspects: setting up the screen with
curses.wrapper, handling user input through a main loop, and managing text storage. I'm now drafting thecurseseditor structure step-by-step, starting with essential initialization and data structures, and then, defining the control flow.Evaluating Implementation Details
I'm now focusing on core mechanics. The
scroll_offsetis a critical optimization for files larger than the screen. Then, I'm working through the complexities of backspace and enter. Backspace's edge cases, like deleting characters at the start of a line and merging lines, require precise handling. Enter needs to split lines correctly. The draw function's logic is already clear, so implementing these tricky components is next.Evaluating The Architecture
I'm now consolidating the design. I've broken down requirements, but the specifics of backspace, enter, and scrolling need a precise structure. Considering the data structure, input loop, and the crucial
scroll_offset. I need to ensure cursor movement syncs with the buffer properly. I'm focusing on the input logic now.Creating a terminal-based text editor is a classic programming project. In Python, the standard library module
cursesis the best tool for this. It gives you low-level control over the terminal screen, cursor positioning, and keyboard input.Note for Windows Users: The
cursesmodule is built-in on macOS and Linux. If you are on Windows, you must install a helper library first by running:pip install windows-curses.Here is a complete, functional, minimal text editor.
The Python Text Editor Code
Save this code as
editor.py.import curses import sys import os def main(stdscr): # Application configuration curses.raw() # Disable special line handling stdscr.nodelay(False) # Make getch() wait for input # Colors curses.start_color() curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLACK) # Text curses.init_pair(2, curses.COLOR_BLACK, curses.COLOR_WHITE) # Status Bar # Check if a filename argument was provided filename = "untitled.txt" buffer = [""] # The text content (list of lines) if len(sys.argv) > 1: filename = sys.argv[1] if os.path.exists(filename): try: with open(filename, 'r') as f: buffer = f.read().splitlines() if not buffer: buffer = [""] except IOError: pass # Cursor and interface variables cx, cy = 0, 0 # Cursor x, Cursor y (relative to buffer) scroll_offset = 0 while True: # 1. Clear screen and get dimensions stdscr.clear() height, width = stdscr.getmaxyx() # 2. Draw the Text Buffer # We only draw the lines that fit within the screen height (minus status bar) for i in range(height - 1): buffer_row = i + scroll_offset if buffer_row < len(buffer): # Ensure line fits within width so it doesn't crash line_content = buffer[buffer_row][:width-1] stdscr.addstr(i, 0, line_content) # 3. Draw Status Bar status_text = f" File: {filename} | Pos: {cy + 1},{cx + 1} | Ctrl+S: Save | Ctrl+Q: Quit " # Fill the rest of the line with whitespace for the background color status_text += " " * (width - len(status_text) - 1) stdscr.attron(curses.color_pair(2)) stdscr.addstr(height - 1, 0, status_text) stdscr.attroff(curses.color_pair(2)) # 4. Move Cursor # Calculate where the cursor should be on screen (not in buffer) screen_y = cy - scroll_offset # Keep cursor inside screen bounds try: stdscr.move(screen_y, cx) except: pass # Ignore edge case errors # 5. Wait for User Input key = stdscr.getch() # --- INPUT HANDLING --- # Quit (Ctrl+Q is ASCII 17) if key == 17: break # Save (Ctrl+S is ASCII 19) elif key == 19: with open(filename, 'w') as f: f.write("\n".join(buffer)) stdscr.addstr(height - 1, 0, " Saved! ", curses.color_pair(2)) stdscr.refresh() curses.napms(500) # Pause briefly to show message # Navigation (Arrow Keys) elif key == curses.KEY_UP: if cy > 0: cy -= 1 if cy < scroll_offset: scroll_offset -= 1 # Scroll Up elif key == curses.KEY_DOWN: if cy < len(buffer) - 1: cy += 1 if cy >= scroll_offset + height - 1: scroll_offset += 1 # Scroll Down elif key == curses.KEY_LEFT: if cx > 0: cx -= 1 elif cy > 0: # move to end of previous line cy -= 1 cx = len(buffer[cy]) elif key == curses.KEY_RIGHT: if cx < len(buffer[cy]): cx += 1 elif cy < len(buffer) - 1: # move to start of next line cy += 1 cx = 0 # Enter Key (New Line) elif key == 10 or key == 13: current_line = buffer[cy] # Split line at cursor buffer[cy] = current_line[:cx] buffer.insert(cy + 1, current_line[cx:]) cy += 1 cx = 0 # Scroll if we hit bottom if cy >= scroll_offset + height - 1: scroll_offset += 1 # Backspace (ASCII 127 or curses.KEY_BACKSPACE) elif key in (curses.KEY_BACKSPACE, 127, 8): if cx > 0: # Remove character on current line row = buffer[cy] buffer[cy] = row[:cx-1] + row[cx:] cx -= 1 elif cy > 0: # Merge with previous line current_line = buffer.pop(cy) cy -= 1 cx = len(buffer[cy]) buffer[cy] += current_line # Standard Characters elif 32 <= key <= 126: char = chr(key) row = buffer[cy] buffer[cy] = row[:cx] + char + row[cx:] cx += 1 # Ensure X cursor doesn't linger past the end of a line after moving Y if cx > len(buffer[cy]): cx = len(buffer[cy]) if __name__ == "__main__": # Wrapper initializes curses, and cleanly resets terminal on exit/crash curses.wrapper(main)How to Run It
- Open your terminal or command prompt.
- Run the file directly:
python editor.py - Or provide a filename to open/create:
python editor.py my_notes.txt
Key Features Implemented
- The Buffer: The text is stored in a list of strings (
buffer). This is easier to manage than one giant string. - Scrolling: The editor handles files longer than the screen height using
scroll_offset. - Key Bindings:
- Arrows: Move the cursor.
- Type: Inserts characters at the cursor position.
- Enter: Splits the current line into two lines.
- Backspace: Deletes characters or merges lines if you are at the start of a line.
- Ctrl+S: Saves the file to disk.
- Ctrl+Q: Exits the program.
- Safety: The code is wrapped in
curses.wrapper(main). If your code errors out, this wrapper ensures your terminal doesn't stay "glitched" (invisible cursor, weird colors, etc.) by restoring the default settings.
How it Works (Internal Logic)
- The Infinite Loop: The editor is essentially an infinite
while Trueloop that redraws the screen approx. 60+ times a second (or whenever a key is pressed). - Rendering: In every loop, we
stdscr.clear()(wipe the screen) and then loop through ourbufferlist tostdscr.addstr()(print) the text. - Coordinates: We track
cx(column) andcy(row) internally. We map these to screen coordinates. For example, if you are editing line 50, but the screen only shows 20 lines, the screen Y coordinate iscy - scroll_offset.
Other models, same or similar prompt
Responses were produced in different, uncontrolled contexts (system prompts, settings, prior turns). This is not a benchmark.