Project 5: The Raw Mode Terminal (Text Editor Base)
Enter raw mode, handle keypresses manually, and render your own screen.
Quick Reference
| Attribute | Value |
|---|---|
| Difficulty | Advanced |
| Time Estimate | 1 week |
| Language | C (Alt: Rust) |
| Prerequisites | C basics, bitwise ops |
| Key Topics | termios, raw mode, VT100 escapes |
1. Learning Objectives
By completing this project, you will:
- Disable canonical mode and echo with termios.
- Read input byte-by-byte.
- Render output using VT100 escape codes.
- Restore terminal state on exit or crash.
2. Theoretical Foundation
2.1 Core Concepts
- Cooked vs raw mode: Canonical input buffers line editing; raw mode delivers bytes directly.
- Termios flags:
ECHO,ICANON,ISIGcontrol terminal behavior. - Escape sequences: VT100 codes move the cursor and clear the screen.
2.2 Why This Matters
Every terminal UI (vim, nano, htop) depends on raw mode and escape sequences.
2.3 Historical Context / Background
Terminals evolved from teletype devices; termios preserves legacy behaviors for compatibility.
2.4 Common Misconceptions
- “Backspace deletes”: It is just a byte; you must implement delete.
- “Ctrl+C is special”: It only sends SIGINT when ISIG is enabled.
3. Project Specification
3.1 What You Will Build
A program that toggles raw mode, reads keys, prints their codes, and updates a simple screen view.
3.2 Functional Requirements
- Enter raw mode and disable echo/canonical processing.
- Print key codes for each press.
- Clear and redraw the screen each frame.
- Restore terminal on exit (even on error).
3.3 Non-Functional Requirements
- Safety: Always restore terminal state.
- Usability: Provide a quit key (e.g.,
q).
3.4 Example Usage / Output
$ ./raw_term
[Type 'q' to quit]
You pressed: 'a' (97)
3.5 Real World Outcome
You will press keys and see their raw codes, with full manual screen control:
$ ./raw_term
[Type 'q' to quit]
You pressed: 'a' (97)
4. Solution Architecture
4.1 High-Level Design
save termios -> enable raw -> read bytes -> render -> restore on exit
4.2 Key Components
| Component | Responsibility | Key Decisions |
|---|---|---|
| Termios manager | Save/restore state | Use atexit |
| Input loop | Read bytes | Non-canonical read |
| Renderer | Clear/redraw screen | VT100 escapes |
4.3 Data Structures
struct termios orig;
4.4 Algorithm Overview
Key Algorithm: Raw Read
- Read 1 byte from stdin.
- Interpret control characters.
- Update screen buffer.
Complexity Analysis:
- Time: O(1) per keypress
- Space: O(1)
5. Implementation Guide
5.1 Development Environment Setup
gcc --version
5.2 Project Structure
project-root/
├── raw_term.c
└── README.md
5.3 The Core Question You’re Answering
“Why does Backspace work, and what happens if I turn it off?”
5.4 Concepts You Must Understand First
Stop and research these before coding:
- termios flags
- Control characters
- SIGWINCH (resize signals)
5.5 Questions to Guide Your Design
Before implementing, think through these:
- How will you ensure terminal state is restored?
- How will you interpret escape sequences for arrow keys?
- How do you detect window resize events?
5.6 Thinking Exercise
Stuck terminal
Run stty -echo and fix it with stty echo. Relate this to your program’s cleanup.
5.7 The Interview Questions They’ll Ask
Prepare to answer these:
- “What is canonical mode?”
- “Why does Ctrl+C send SIGINT?”
- “How do TUIs avoid flicker?”
5.8 Hints in Layers
Hint 1: Save original termios
Use tcgetattr and restore on exit.
Hint 2: Disable ECHO/ICANON/ISIG Mask these flags for true raw input.
Hint 3: Use escape codes
[2J clears screen, [H moves cursor home.
5.9 Books That Will Help
| Topic | Book | Chapter |
|---|---|---|
| Terminals | “TLPI” | Ch. 62 |
| Text editor internals | “Build Your Own Text Editor” | All |
5.10 Implementation Phases
Phase 1: Foundation (2-3 days)
Goals:
- Enter and exit raw mode.
Tasks:
- Save/restore termios.
- Disable ECHO/ICANON.
Checkpoint: Typed characters stop echoing.
Phase 2: Core Functionality (2-3 days)
Goals:
- Read keys and display codes.
Tasks:
- Read bytes via read().
- Print codes on screen.
Checkpoint: Key codes appear instantly.
Phase 3: Polish & Edge Cases (2 days)
Goals:
- Add rendering loop and cleanup on crash.
Tasks:
- Add atexit handler.
- Clear/redraw screen.
Checkpoint: Terminal restores after exit.
5.11 Key Implementation Decisions
| Decision | Options | Recommendation | Rationale |
|---|---|---|---|
| Input | blocking vs non-blocking | blocking | Simpler |
| Cleanup | manual vs atexit | atexit | Safety |
6. Testing Strategy
6.1 Test Categories
| Category | Purpose | Examples |
|---|---|---|
| Termios | Raw mode toggles | echo disabled |
| Input | Byte reads | key codes |
| Cleanup | Restore | terminal normal |
6.2 Critical Test Cases
- Raw mode enabled and disabled correctly.
- Ctrl+C does not exit when ISIG disabled.
- Terminal restored after abnormal exit.
6.3 Test Data
Keypress: 'a', Backspace, Ctrl+C
7. Common Pitfalls & Debugging
7.1 Frequent Mistakes
| Pitfall | Symptom | Solution |
|---|---|---|
| Not restoring termios | Broken terminal | Use atexit |
| Ignoring escape sequences | Arrow keys weird | Parse multi-byte sequences |
| Printing with stdio buffering | Delayed output | Use write() |
7.2 Debugging Strategies
- Print raw byte values in hex.
- Use
stty -ato confirm flags.
7.3 Performance Traps
Redrawing the full screen per keypress can flicker; add minimal redraws later.
8. Extensions & Challenges
8.1 Beginner Extensions
- Handle backspace visually.
- Add a simple cursor.
8.2 Intermediate Extensions
- Add arrow key support.
- Add line editing.
8.3 Advanced Extensions
- Build a mini text editor.
- Handle window resize events.
9. Real-World Connections
9.1 Industry Applications
- Terminal UIs, editors, and CLI dashboards.
9.2 Related Open Source Projects
- kilo editor: https://github.com/antirez/kilo
9.3 Interview Relevance
- Termios and raw mode show deep Unix understanding.
10. Resources
10.1 Essential Reading
- termios(3) -
man 3 termios
10.2 Video Resources
- Terminal control tutorials (search “termios raw mode”)
10.3 Tools & Documentation
- stty(1) -
man 1 stty
10.4 Related Projects in This Series
- Mirror Filesystem (FUSE): next step in kernel/user interfaces.
11. Self-Assessment Checklist
11.1 Understanding
- I can explain canonical vs raw mode.
- I can explain control characters.
- I can describe escape sequences.
11.2 Implementation
- Raw mode works.
- Screen redraws correctly.
- Terminal restores on exit.
11.3 Growth
- I can extend to a text editor.
- I can handle resize events.
12. Submission / Completion Criteria
Minimum Viable Completion:
- Raw mode input and key display.
Full Completion:
- Screen clearing and safe restore.
Excellence (Going Above & Beyond):
- Build a minimal editor with cursor and backspace.
This guide was generated from LEARN_LINUX_UNIX_INTERNALS_DEEP_DIVE.md. For the complete learning path, see the parent directory.