The user wants a terminal-based text editor in Python. This is a classic programming challenge. I need to think about the features a minimal but functional text editor should have.
Core Requirements:
- Display: Show text on the terminal.
- Input: Capture keystrokes (character keys, special keys like arrows, backspace, enter).
- Cursor Movement: Move the cursor up, down, left, right.
- Editing: Insert and delete characters, handle new lines.
- File I/O: Open a file and save changes.
- Exit: A way to quit the application.
Libraries:
- Standard
input(): Too basic. It's line-oriented. It doesn't handle raw keystrokes well (like arrow keys without pressing Enter).
curses (standard library): This is the industry standard for terminal UIs in Python on Unix/Linux/macOS. It handles screen painting, cursor positioning, and non-blocking input.
- Pros: Powerful, standard.
- Cons: Windows support is historically poor (though
windows-curses exists and is often installable). It can be complex to learn.
curses wrapper: Python provides curses.wrapper() which handles initialization and cleanup (very important so the terminal doesn't get stuck in a weird state if the program crashes).
Architecture (Mental Draft):
-
Initialization:
- Load file content into a list of strings (lines).
- Setup
curses.
-
Main Loop:
- Draw/Refresh: Clear screen, loop through lines and print them. Position the cursor.
- Input:
stdscr.getch() to get a key code.
- Logic:
- Arrow keys: Update (x, y) coordinates. Handle boundary checks (don't go below line 0, don't go past end of line, etc.).
- Enter: Split current line, insert new line.
- Backspace: Delete char or merge lines.
- Regular char: Insert char at current position.
- Ctrl+S (Save): Write list of strings to file.
- Ctrl+Q (Quit): Break loop.
-
Refining the Logic (Edge Cases):
- Horizontal Scrolling: If a line is longer than the screen width, we need to scroll. To keep this example "simple" but functional, I might stick to basic cursor movement within the visible buffer, or implement a simple offset. For a basic tutorial-style editor, simple wrapping or just printing what fits is usually acceptable, but real editors need scrolling. Let's try to implement basic scrolling logic.
- Vertical Scrolling: If the file has more lines than the terminal height.
- Tab handling: Convert tabs to spaces or handle the tab character.
- Status Bar: A line at the bottom to show filename, help messages (Ctrl+S to save, etc.).
Step-by-Step Implementation Plan:
- Step 1: Setup and File Loading. Check
sys.argv for a filename. Open it. Handle "file not found" (start with empty buffer).
- Step 2: The
Editor Class. It's cleaner to encapsulate state (cursor x/y, offset x/y, lines).
- Step 3: Drawing.
- Loop from
top to bottom of screen.
- Print lines corresponding to the scroll position.
- Draw a status bar at the bottom (
LINES - 1).
- Step 4: Input Handling.
- Map
curses.KEY_LEFT, etc.
- ASCII range for printable chars.
curses.ascii.ctrl for commands.
- Step 5: Scrolling Logic.
- If
cursor_y < top_row, scroll up.
- If
cursor_y > bottom_row, scroll down.
- Same for horizontal.
Drafting the Code (Mental or Scratchpad):
-
Import: curses, sys.
-
Structure:
def main(stdscr):
# logic here
if __name__ == "__main__":
curses.wrapper(main)
-
Cursor constraints:
When moving Left: if x > 0: x -= 1
When moving Right: if x < len(current_line): x += 1
When moving Up: if y > 0: y -= 1. Crucial: Snap x to end of new line if new line is shorter.
When moving Down: if y < len(lines) - 1: y += 1. Snap x.
-
Insertion:
Line = line[:x] + char + line[x:]
Update x.
-
Newline:
Current line: line[:x]
Next line: line[x:]
Insert into list.
-
Backspace:
If x > 0: delete char at x-1.
If x == 0 and y > 0: Merge with previous line.
Refining for the User:
The user asked for a "Python program". I should provide a single, copy-pasteable script. I should use the curses library because it's the standard way to do this on Linux/macOS (and works on Windows with pip install windows-curses).
I will add comments explaining the parts.
I will implement a "Status Bar" to give feedback (like "Ctrl+Q to quit").
Self-Correction/Edge Case Check:
- Windows: Standard Python on Windows doesn't include
curses by default (it relies on windows-curses package). I must mention this in the instructions.
- Long lines: If a line is 500 chars and screen is 80,
curses might throw an error if we try to addstr outside window bounds.
- Fix: Use slicing or horizontal offset.
- Simpler approach for a basic script: Just print the slice of the line that fits the screen width based on a horizontal offset. Let's stick to vertical scrolling for simplicity to keep the code readable, but ensure horizontal overflow doesn't crash the program.
Final Code Structure:
Editor class.
__init__: Load file.
draw: Render screen + status bar.
process_input: Handle keys.
save: Write file.
Let's write the code.
Key bindings:
Arrow keys: Move.
Ctrl+S: Save.
Ctrl+Q: Quit.
Enter: New line.
Backspace: Delete.
Implementation details:
self.y is the row in the file (0 to len(lines)).
self.x is the column in the file.
self.offset_y is how much we scrolled down.
Let's go.
Creating a text editor from scratch is a great way to understand how terminal interfaces work. We will use the curses library, which is standard in Python for handling terminal screens, cursor movement, and keyboard input without the need for external graphical interfaces.
Prerequisites
- Linux / macOS: The
curses library is included by default.
- Windows: You must install a wrapper library because
curses is not included by default on Windows. Open your terminal and run:
pip install windows-curses
The Python Code
Save the following code into a file named editor.py.
import curses
import sys
class Editor:
def __init__(self, stdscr):
self.stdscr = stdscr
self.buffer = [] # Stores lines of text
self.cursor_y = 0 # Row position
self.cursor_x = 0 # Column position
self.offset_y = 0 # Vertical scroll offset
self.filename = None
# Initialize colors
curses.init_pair(1, curses.COLOR_WHITE, curses.COLOR_BLUE)
# Load file if provided
if len(sys.argv) > 1:
self.filename = sys.argv[1]
self.load_file()
def load_file(self):
try:
with open(self.filename, 'r') as f:
self.buffer = f.read().splitlines()
except FileNotFoundError:
self.buffer = [""] # Start with empty line if file doesn't exist
self.status_msg(f"New file: {self.filename}")
def save_file(self):
if not self.filename:
self.filename = "untitled.txt"
try:
with open(self.filename, 'w') as f:
f.write('\n'.join(self.buffer))
self.status_msg(f"Saved to {self.filename}")
except Exception as e:
self.status_msg(f"Error saving: {e}")
def status_msg(self, msg):
# Draw status bar at the bottom
height, width = self.stdscr.getmaxyx()
self.stdscr.attron(curses.color_pair(1))
self.stdscr.addstr(height-1, 0, msg.ljust(width))
self.stdscr.attroff(curses.color_pair(1))
self.stdscr.refresh()
def draw(self):
self.stdscr.clear()
height, width = self.stdscr.getmaxyx()
# Draw text buffer
for i, line in enumerate(self.buffer[self.offset_y : self.offset_y + height - 1]):
self.stdscr.addstr(i, 0, line)
# Draw cursor
# Note: curses handles clamping automatically usually, but logic helps
try:
self.stdscr.move(self.cursor_y - self.offset_y, self.cursor_x)
except curses.error:
pass
self.stdscr.refresh()
def handle_input(self, key):
height, width = self.stdscr.getmaxyx()
# --- Navigation ---
if key == curses.KEY_UP:
if self.cursor_y > 0:
self.cursor_y -= 1
self.clamp_cursor_x()
elif key == curses.KEY_DOWN:
if self.cursor_y < len(self.buffer) - 1:
self.cursor_y += 1
self.clamp_cursor_x()
elif key == curses.KEY_LEFT:
if self.cursor_x > 0:
self.cursor_x -= 1
elif key == curses.KEY_RIGHT:
if self.cursor_x < len(self.buffer[self.cursor_y]):
self.cursor_x += 1
# --- Scrolling ---
# If cursor moves outside visible screen, adjust offset
if self.cursor_y < self.offset_y:
self.offset_y = self.cursor_y
elif self.cursor_y >= self.offset_y + height - 1:
self.offset_y = self.cursor_y - (height - 2)
# --- Editing ---
elif key == curses.KEY_BACKSPACE or key == 127 or key == 8:
self.delete_char()
elif key == curses.KEY_ENTER or key == 10:
self.insert_newline()
elif key == 19: # Ctrl+S
self.save_file()
# Standard printable characters
elif 32 <= key <= 126:
self.insert_char(chr(key))
def clamp_cursor_x(self):
# Ensure cursor X doesn't go past the end of the current line
line_len = len(self.buffer[self.cursor_y])
if self.cursor_x > line_len:
self.cursor_x = line_len
def insert_char(self, ch):
line = self.buffer[self.cursor_y]
new_line = line[:self.cursor_x] + ch + line[self.cursor_x:]
self.buffer[self.cursor_y] = new_line
self.cursor_x += 1
def insert_newline(self):
line = self.buffer[self.cursor_y]
# Split line at cursor
self.buffer[self.cursor_y] = line[:self.cursor_x]
self.buffer.insert(self.cursor_y + 1, line[self.cursor_x:])
self.cursor_y += 1
self.cursor_x = 0
def delete_char(self):
if self.cursor_x > 0:
# Delete char in line
line = self.buffer[self.cursor_y]
self.buffer[self.cursor_y] = line[:self.cursor_x - 1] + line[self.cursor_x:]
self.cursor_x -= 1
elif self.cursor_y > 0:
# Merge with previous line
current_line = self.buffer[self.cursor_y]
prev_line = self.buffer[self.cursor_y - 1]
self.cursor_x = len(prev_line)
self.buffer[self.cursor_y - 1] = prev_line + current_line
del self.buffer[self.cursor_y]
self.cursor_y -= 1
def main(stdscr):
# Setup curses
curses.noecho() # Don't echo keypresses
stdscr.keypad(True) # Enable special keys (arrows)
stdscr.idcok(False) # Disable hardware insert/delete line (optional, smoother on some terms)
editor = Editor(stdscr)
# Main Loop
while True:
editor.draw()
key = stdscr.getch()
# Quit on Ctrl+Q (ASCII 17)
if key == 17:
break
editor.handle_input(key)
if __name__ == "__main__":
# Wrapper handles initialization and cleanup automatically
curses.wrapper(main)
How to use it
- Run the editor:
- To create a new file:
python editor.py
- To open an existing file:
python editor.py my_text_file.txt
- Controls:
- Arrow Keys: Move cursor.
- Enter: Insert a new line.
- Backspace: Delete character (or merge lines).
- Ctrl + S: Save the file.
- Ctrl + Q: Quit the editor.
Key Features Explained
curses.wrapper(main): This is crucial. It initializes the terminal screen, handles colors, and—most importantly—guarantees that if your program crashes, your terminal settings are restored so you aren't left with a messed-up terminal.
- The Buffer: We store the text in a Python list of strings (
self.buffer). Each item in the list is a line. This makes it very easy to handle vertical movement and line editing.
- Scrolling (
offset_y): Terminals have limited height. If you have 1000 lines of text but your terminal is 50 lines high, curses won't automatically scroll. We manually calculate offset_y to determine which slice of the buffer to draw on the screen.
- Status Bar: We reserve the bottom line of the screen to show messages (like "Saved") by using
height-1.