Skip to content

7 3 terminal editor r1 editor

TransCompilator edited this page Nov 26, 2026 · 1 revision

7.3 Terminal Editor (r1-editor)

Source: https://deepwiki.com/PonvasanthPon/TransCompilator/7-3-terminal-editor-r1-editor

Terminal Editor (r1-editor)

Relevant source files

The following files were used as context for generating this wiki page:

Purpose and Scope

The tc-editor crate (binary r1-editor, library crate tc_editor) provides a native, terminal-based interactive editing environment designed specifically for structured English (.eng) source files. It integrates directly with the tc_r1 compiler pipeline (tc-semantics, tc-ir, and tc-codegen-x86) to offer sub-second, in-process compilation, native ELF64 execution, reference interpreter parity checks, canonical paraphrase generation, and per-sentence syntax tracing.

This page documents the internal architecture of tc-editor, covering its UTF-8-safe text buffer, raw-mode terminal control, ANSI byte-stream key decoder, cohesive truecolor themes, syntax highlighting engine, synchronized UI canvas renderer, in-process compiler bridge, and headless testing suites.

Sources: [crates/tc-editor/src/lib.rs:1-38], [crates/tc-editor/src/runner.rs:1-61]()


1. Editor Architecture & Core State Machine (EditorApp)

The editor runs as a single-threaded event loop driven by synchronous terminal input. The global application state is encapsulated in the EditorApp struct, which manages the active editing buffer, interactive modes, prompt inputs, output tabs, diagnostic line states, and theme palettes.

graph TD
    subgraph "Editor Application State"
        A["EditorApp"] --> B["TextBuffer"]
        A --> C["RunResult"]
        A --> D["OutputTab"]
        A --> E["Mode"]
        A --> F["Theme"]
    end
    subgraph "Interactive Modes"
        E -->|"Editing"| G["Normal Text Editing"]
        E -->|"Prompt"| H["Inline Prompt: SaveAs / Open / Find / Stdin"]
        E -->|"PresetPicker"| I["Built-in .eng Preset Selection Overlay"]
        E -->|"Help"| J["Keybindings & Documentation Modal"]
        E -->|"OutputFocus"| K["Output Pane Scrolling & Navigation"]
    end

    Sources: [crates/tc-editor/src/app.rs:56-93](), [crates/tc-editor/src/app.rs:15-28]()
Loading

The user interacts with the editor through mode-dependent key dispatchers. When in Mode::Editing, printable characters, navigation keys, and shortcut keys (such as F5 for compilation/run, F6 for paraphrase, F7 for trace, and F4 for theme cycling) update the TextBuffer or trigger compiler actions.

Sources: [crates/tc-editor/src/app.rs:15-28], [crates/tc-editor/tests/r1_editor_tui_tests.rs:117-131]()


2. Text Buffer and UTF-8 Character Handling (TextBuffer)

The TextBuffer struct maintains multi-line text contents where the cursor column is indexed by unicode characters, never raw UTF-8 bytes. This guarantees that multi-byte symbols, emoji (😀), and Indic scripts (வணக்கம்) can be navigated, inserted, and deleted without corrupting code point boundaries.

graph TD
    subgraph "Code Entity Space: TextBuffer & Snapshot"
        TB["TextBuffer"] -->|"lines: Vec<String>"| LS["Multi-line strings"]
        TB -->|"cursor_row / cursor_col"| CC["Character-indexed position"]
        TB -->|"undo_stack / redo_stack"| US["Vec<Snapshot> (Max 200)"]
        US -->|"Snapshot"| SS["lines, cursor_row, cursor_col"]
    end
    subgraph "File I/O & Normalization"
        TB -->|"load_from_file()"| IO1["fs::read_to_string() + CRLF normalization"]
        TB -->|"save_to_file()"| IO2["Atomic save (.eng extension + .tmp rename)"]
    end

    Sources: [crates/tc-editor/src/buffer.rs:18-35](), [crates/tc-editor/src/buffer.rs:106-133]()
Loading

Key Buffer Mechanisms

  • Character Offset Translation: char_offset(line, column) converts a character-based column index into a byte offset using .char_indices().
  • Undo/Redo History: Edits automatically push a Snapshot containing line vectors and cursor coordinates onto undo_stack (bounded at MAX_UNDO = 200 entries) while clearing redo_stack.
  • Atomic File I/O: save_to_file() ensures safety by writing contents to a .tmp sibling file before performing an atomic fs::rename() to the target .eng path. If no extension is specified, .eng is automatically appended.
  • Smart Indenting: Pressing Enter after a trailing colon : automatically indents the new line with four spaces.

Sources: [crates/tc-editor/src/buffer.rs:37-51], [crates/tc-editor/src/buffer.rs:120-133], [crates/tc-editor/tests/r1_editor_tests.rs:87-95]()


3. Terminal Control, Raw Mode, and Panic Safety (RawTerminal)

To render a full-screen text user interface without line buffering or local echo, tc-editor implements a Linux termios raw mode wrapper with RAII guards and panic safety hooks.

graph TD
    subgraph "Code Entity Space: terminal.rs"
        RT["RawTerminal"] -->|"enter()"| TCGETS["ioctl(0, TCGETS, &original)"]
        TCGETS -->|"Clear Flags"| FLAGS["ICANON, ECHO, ISIG, IEXTEN, IXON, ICRNL"]
        FLAGS -->|"Apply Termios"| TCSETS["ioctl(0, TCSETS, &raw)"]
        TCSETS -->|"Screen Init"| SEQ["Stdout: \\x1b[?1049h (Alt Screen), \\x1b[2J (Clear), \\x1b[?25l (Hide Cursor)"]
        RT -->|"Drop / Panic"| REST["restore_from_static() -> TCSETS original + \\x1b[?1049l + \\x1b[?25h"]
    end

    Sources: [crates/tc-editor/src/terminal.rs:97-154](), [crates/tc-editor/src/terminal.rs:70-92]()
Loading

Synchronization and Output Safety

  • Synchronized Output: To prevent screen tearing during complex full-screen redraws, the renderer brackets frame outputs with DEC private mode synchronized output sequences (SYNC_BEGIN: \x1b[?2026h and SYNC_END: \x1b[?2026l).
  • Panic Hook Restoration: If the editor encounters a panic during operation, a custom panic hook intercepts the unwind, restores the original terminal termios settings, leaves the alternate screen buffer, and restores the terminal cursor.

Sources: [crates/tc-editor/src/terminal.rs:11-14], [crates/tc-editor/src/terminal.rs:83-92], [crates/tc-editor/src/ui.rs:110-138]()


4. ANSI/VT100 Byte-Stream Key Decoder (keys.rs)

The decode_keys() function translates raw byte slices read from stdin into structured KeyEvent enums, handling plain ASCII, control characters, multi-byte UTF-8 sequences, ANSI Control Sequence Introducer (CSI) sequences, and Single Shift 3 (SS3) function key mappings.

graph TD
    subgraph "Code Entity Space: keys.rs"
        BS["Byte Slice from Stdin"] -->|"decode_keys()"| LOOP["Byte Stream Scanner"]
        LOOP -->|"0x1b (ESC)"| ESC["Check CSI / SS3 / Escape"]
        ESC -->|"\\x1b [ ... [A-Z~]"| CSI["csi_key(): Arrows, Home, End, F1-F12, PageUp/Dn"]
        ESC -->|"\\x1b O [P-S]"| SS3["ss3_key(): F1-F4"]
        LOOP -->|"0x01..=0x1a"| CTRL["KeyEvent::Ctrl(letter)"]
        LOOP -->|"0x80..=0xff"| UTF8["UTF-8 multi-byte sequence validation"]
    end

    Sources: [crates/tc-editor/src/keys.rs:115-202]()
Loading

Key Categories Handled

  • Navigation & Editing: KeyEvent::Up, Down, Left, Right, CtrlLeft, CtrlRight, Home, End, PageUp, PageDown, Backspace, Delete.
  • Function Keys: KeyEvent::F(1) through F(12).
  • Control Modifiers: KeyEvent::Ctrl('r'), Ctrl('p'), Ctrl('t'), Ctrl('q'), etc.

Sources: [crates/tc-editor/src/keys.rs:3-44], [crates/tc-editor/src/keys.rs:60-110]()


5. Theming and Lexicon-Aware Syntax Highlighting (theme.rs, highlight.rs)

tc-editor provides four built-in color palettes via ThemeId: Midnight (deep slate truecolor), HighContrast (vivid black-background), Monochrome (no ANSI color escape sequences), and Light (paper-gray ink).

graph TD
    subgraph "Code Entity Space: Highlighting Pipeline"
        L["Source Line text"] --> HL["highlight_line()"]
        HL -->|"Lexicon Match"| TV["ActionVerb (Remove, Add, Transfer)"]
        HL -->|"ACE Keywords"| CA["ControlAnchor (If, Unless, For every)"]
        HL -->|"Anaphors"| AN["AnaphorOrQuantifier (it, its, every)"]
        HL -->|"Types & Literals"| TL["Type (i64, f64), Number, String"]
        HL -->|"Line State Overlay"| LS["LineState::ProseOmitted / Error / SearchMatch"]
    end

    Sources: [crates/tc-editor/src/theme.rs:93-128](), [crates/tc-editor/tests/r1_editor_tui_tests.rs:38-103]()
Loading

Highlighting Rules

  • Computational Verbs: Highlighted using TokenStyle::ActionVerb (e.g., Add, Remove, Transfer).
  • Control Anchors: Highlighted using TokenStyle::ControlAnchor (e.g., If, Unless, For every).
  • Anaphors: Highlighted using TokenStyle::AnaphorOrQuantifier (e.g., it, its).
  • Prose Omission: Lines classified by the intent gate as narrative prose omitted from compilation receive LineState::ProseOmitted, rendering them dimmed and italicized.

Sources: [crates/tc-editor/tests/r1_editor_tui_tests.rs:38-80]()


6. Synchronized ANSI User Interface & Canvas Renderer (ui.rs)

The UI engine renders the editor inside an off-screen Canvas grid of character cells, flushing the result as a single atomic ANSI escape sequence string wrapped in synchronized output markers.

Layout Anatomy

  • Header Bar: Displays editor version, active file path, dirty indicator ([*]), active theme name, and compilation status.
  • Main Editor Pane: Left pane showing line numbers, active line highlighting, source text, syntax highlighting spans, cursor position, and scroll offsets.
  • Output Pane: Right pane featuring output tabs (RUN, PARAPHRASE, TRACE, IR, BUILD), status summary, and detailed execution logs or diagnostics.
  • Footer Status Bar: Displays current mode keybindings (e.g., F5/^R Run, F6/^P Paraphrase, F7/^T Trace, F2 Presets, F4 Theme).
  • Centered Modals: Overlay dialogs for Preset Picker, Help documentation, and inline prompts (Save as, Open, Find, Stdin).

Sources: [crates/tc-editor/src/ui.rs:1-141], [crates/tc-editor/tests/r1_editor_tui_tests.rs:145-195]()


7. In-Process Compiler Runner and Presets (runner.rs)

The runner.rs module bridges tc-editor directly to the tc_r1 compiler crates without spawning external compiler processes for fast, in-memory evaluation.

graph TD
    subgraph "Natural Language Space to Code Entity Space: Compiler Runner Bridge"
        NL["English Source Text (.eng)"] -->|"runner.rs actions"| CP["tc_semantics::compile_english_to_ir()"]
        CP -->|"OutputTab::Run"| PAR["run_elf_with_parity() -> ELF64 Execution + tc_ir::interpret()"]
        CP -->|"OutputTab::Paraphrase"| PARAPH["tc_semantics::format_paraphrase()"]
        CP -->|"OutputTab::Trace"| TRC["run_trace() -> Per-sentence Intent & Syntax Trace"]
        CP -->|"OutputTab::Ir"| IR["tc_ir::format_module() -> Verified Core-7 IR"]
        CP -->|"OutputTab::Build"| BLD["tc_codegen_x86::compile_to_elf() -> Static ELF64 Binary"]
    end

    Sources: [crates/tc-editor/src/runner.rs:1-61](), [crates/tc-editor/src/runner.rs:128-202]()
Loading

Built-in Presets

The editor bundles 8 verified .eng starter programs (PRESETS) that demonstrate language features and pass exact interpreter/ELF64 parity checks:

  1. 01_discourse_cash.eng: ACE discourse, expletive prose, comma precedence, and For every loops.
  2. 02_struct_anaphora.eng: Struct field access with its, the point's y, and appositive names.
  3. 03_quantifiers_prime.eng: Pure-English primality testing with local range quantifiers.
  4. 04_phrase_syscall_hello.eng: Declarative Phrase wrapping a raw Linux write syscall.
  5. 05_passive_and_transfers.eng: Narrative omission, Transfer, passive voice, and Unless conditionals.
  6. 06_std_io_and_math.eng: Natural-English std/io formatting and std/math roots.

Sources: [crates/tc-editor/src/runner.rs:128-202]


8. Testing and Headless Verification

tc-editor is thoroughly validated by headless integration and TUI tests that simulate key presses, verify buffer modifications, check multi-byte UTF-8 safety, inspect ANSI rendering rows, and cycle through color themes without requiring a physical terminal.

graph TD
    subgraph "Testing Infrastructure"
        T1["r1_editor_tests.rs"] -->|"Buffer Operations"| B1["Insert, backspace, undo/redo, auto-indent, file roundtrips"]
        T1 -->|"Key Decoding"| B2["CSI, SS3, function keys, plain ASCII"]
        T2["r1_editor_tui_tests.rs"] -->|"Syntax Highlighting"| C1["Lexicon verbs, types, omitted prose, error lines"]
        T2 -->|"TUI Layouts"| C2["140x40 and 80x24 grid cell alignment, border integrity"]
        T2 -->|"Theme Cycles"| C3["Midnight -> HighContrast -> Monochrome -> Light"]
    end

    Sources: [crates/tc-editor/tests/r1_editor_tests.rs:1-223](), [crates/tc-editor/tests/r1_editor_tui_tests.rs:1-195]()
Loading

Sources: [crates/tc-editor/tests/r1_editor_tests.rs:1-223], [crates/tc-editor/tests/r1_editor_tui_tests.rs:1-195]


Clone this wiki locally