fresh-editor 0.4.0

A lightweight, fast terminal-based text editor with LSP support and TypeScript plugins
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
use crate::common::harness::EditorTestHarness;
use fresh::config::Config;
use fresh::config_io::DirectoryContext;
use tempfile::TempDir;

/// Files under the app data dir (e.g. terminal scrollback backing files
/// surfaced by Universal Search) open read-only so a stray keystroke can't
/// corrupt persisted state.
#[test]
fn test_file_under_data_dir_is_read_only() {
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    // A terminal-scrollback-like text file living under the data dir.
    let scrollback = dir_context.data_dir.join("terminals").join("session.txt");
    std::fs::create_dir_all(scrollback.parent().unwrap()).unwrap();
    std::fs::write(&scrollback, "line one\nline two\n").unwrap();

    // Working dir is a sibling project root, distinct from the data dir.
    let project = temp_dir.path().join("project");
    std::fs::create_dir_all(&project).unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        100,
        24,
        Config::default(),
        project,
        dir_context,
    )
    .unwrap();
    harness.open_file(&scrollback).unwrap();
    harness.render().unwrap();

    assert!(
        harness.editor().active_window().is_editing_disabled(),
        "File under data dir should open read-only"
    );
}

/// A normal text file outside the data dir stays editable — the read-only
/// rule is scoped to data-dir artifacts, not all `.txt` files.
#[test]
fn test_file_outside_data_dir_is_editable() {
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    let project = temp_dir.path().join("project");
    std::fs::create_dir_all(&project).unwrap();
    let notes = project.join("notes.txt");
    std::fs::write(&notes, "editable content\n").unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        100,
        24,
        Config::default(),
        project,
        dir_context,
    )
    .unwrap();
    harness.open_file(&notes).unwrap();
    harness.render().unwrap();

    assert!(
        !harness.editor().active_window().is_editing_disabled(),
        "File outside data dir should remain editable"
    );
}

/// A session working tree (conductor / orchestrator) physically lives under
/// the data dir, but its files are real working files — opening one must stay
/// editable. The read-only rule applies only to artifacts outside the window's
/// own root. Drives real keystrokes and observes the typed text on screen.
#[test]
fn test_file_in_session_tree_under_data_dir_is_editable() {
    let temp_dir = TempDir::new().unwrap();
    let dir_context = DirectoryContext::for_testing(temp_dir.path());

    // Project root sits under the data dir, mirroring a conductor session.
    let project = dir_context
        .data_dir
        .join("conductor")
        .join("proj")
        .join("session-1");
    std::fs::create_dir_all(&project).unwrap();
    let changelog = project.join("CHANGELOG.md");
    std::fs::write(&changelog, "# Release Notes\n").unwrap();

    let mut harness = EditorTestHarness::with_shared_dir_context(
        100,
        24,
        Config::default(),
        project,
        dir_context,
    )
    .unwrap();
    harness.open_file(&changelog).unwrap();
    harness.render().unwrap();

    // Typing must land in the buffer: if the data-dir guard wrongly disabled
    // editing, the keystrokes are dropped and the marker never renders.
    harness.type_text("ZZEDITABLEZZ").unwrap();
    harness.render().unwrap();
    harness.assert_screen_contains("ZZEDITABLEZZ");
}

/// Test that PNG files are detected as binary and opened in read-only mode
#[test]
fn test_png_file_detected_as_binary() {
    let temp_dir = TempDir::new().unwrap();
    let png_path = temp_dir.path().join("test.png");

    // Write a minimal valid PNG file
    // PNG signature: 89 50 4E 47 0D 0A 1A 0A
    // The 0x1A byte (SUB control character) triggers binary detection
    let png_data: &[u8] = &[
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, // PNG signature
        0x00, 0x00, 0x00, 0x0D, // IHDR chunk length
        0x49, 0x48, 0x44, 0x52, // "IHDR"
        0x00, 0x00, 0x00, 0x01, // width = 1
        0x00, 0x00, 0x00, 0x01, // height = 1
        0x08, 0x02, // bit depth = 8, color type = 2 (RGB)
        0x00, 0x00, 0x00, // compression, filter, interlace
        0x90, 0x77, 0x53, 0xDE, // CRC
    ];
    std::fs::write(&png_path, png_data).unwrap();

    // Use wider terminal to see full status message
    let mut harness = EditorTestHarness::new(120, 24).unwrap();
    harness.open_file(&png_path).unwrap();
    harness.render().unwrap();

    // Verify the file is detected as binary by checking editing is disabled
    assert!(
        harness.editor().active_window().is_editing_disabled(),
        "Binary file should have editing disabled"
    );

    // Verify tab shows [BIN] indicator
    harness.assert_screen_contains("[BIN]");

    // Verify status bar shows binary file indicator
    harness.assert_screen_contains("[BIN]");
}

/// Test that JPEG files are detected as binary
#[test]
fn test_jpeg_file_detected_as_binary() {
    let temp_dir = TempDir::new().unwrap();
    let jpeg_path = temp_dir.path().join("test.jpg");

    // JPEG signature with null bytes that trigger binary detection
    let jpeg_data: &[u8] = &[
        0xFF, 0xD8, 0xFF, 0xE0, // JPEG SOI + APP0 marker
        0x00, 0x10, // APP0 length (16 bytes) - null byte triggers binary
        0x4A, 0x46, 0x49, 0x46, 0x00, // "JFIF\0"
        0x01, 0x01, // version
        0x00, // aspect ratio units
        0x00, 0x01, // X density
        0x00, 0x01, // Y density
        0x00, 0x00, // thumbnail dimensions
    ];
    std::fs::write(&jpeg_path, jpeg_data).unwrap();

    let mut harness = EditorTestHarness::new(120, 24).unwrap();
    harness.open_file(&jpeg_path).unwrap();
    harness.render().unwrap();

    assert!(
        harness.editor().active_window().is_editing_disabled(),
        "JPEG file should have editing disabled"
    );
    harness.assert_screen_contains("[BIN]");
}

/// Test that ELF executables are detected as binary
#[test]
fn test_elf_executable_detected_as_binary() {
    let temp_dir = TempDir::new().unwrap();
    let elf_path = temp_dir.path().join("test_binary");

    // ELF header with null bytes
    let elf_data: &[u8] = &[
        0x7F, 0x45, 0x4C, 0x46, // ELF magic
        0x02, // 64-bit
        0x01, // little endian
        0x01, // ELF version
        0x00, // OS/ABI - null byte triggers binary detection
        0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, // padding
    ];
    std::fs::write(&elf_path, elf_data).unwrap();

    let mut harness = EditorTestHarness::new(120, 24).unwrap();
    harness.open_file(&elf_path).unwrap();
    harness.render().unwrap();

    assert!(
        harness.editor().active_window().is_editing_disabled(),
        "ELF binary should have editing disabled"
    );
    harness.assert_screen_contains("[BIN]");
}

/// Test that regular text files are NOT detected as binary
#[test]
fn test_text_file_not_detected_as_binary() {
    let temp_dir = TempDir::new().unwrap();
    let text_path = temp_dir.path().join("test.txt");

    std::fs::write(&text_path, "Hello, world!\nThis is a text file.\n").unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&text_path).unwrap();
    harness.render().unwrap();

    // Text files should allow editing
    assert!(
        !harness.editor().active_window().is_editing_disabled(),
        "Text file should allow editing"
    );

    // Status bar should NOT show binary indicator
    harness.assert_screen_not_contains("binary");
}

/// Test that files with ANSI escape sequences are NOT detected as binary
#[test]
fn test_ansi_escape_sequences_not_binary() {
    let temp_dir = TempDir::new().unwrap();
    let ansi_path = temp_dir.path().join("colored.txt");

    // File with ANSI color codes (CSI sequences)
    let ansi_content = "\x1b[31mRed text\x1b[0m\n\x1b[32mGreen text\x1b[0m\n";
    std::fs::write(&ansi_path, ansi_content).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&ansi_path).unwrap();
    harness.render().unwrap();

    // ANSI files should allow editing (not binary)
    assert!(
        !harness.editor().active_window().is_editing_disabled(),
        "File with ANSI escape sequences should allow editing"
    );
}

/// Test that typing is blocked in binary files
#[test]
fn test_typing_blocked_in_binary_file() {
    use crossterm::event::{KeyCode, KeyModifiers};

    let temp_dir = TempDir::new().unwrap();
    let png_path = temp_dir.path().join("test.png");

    // Minimal PNG data
    let png_data: &[u8] = &[
        0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A, 0x00, 0x00, 0x00, 0x00,
    ];
    std::fs::write(&png_path, png_data).unwrap();

    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&png_path).unwrap();

    let initial_len = harness.buffer_len();

    // Try to type - should be blocked
    harness
        .send_key(KeyCode::Char('a'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('b'), KeyModifiers::NONE)
        .unwrap();
    harness
        .send_key(KeyCode::Char('c'), KeyModifiers::NONE)
        .unwrap();

    // Buffer length should not change
    assert_eq!(
        harness.buffer_len(),
        initial_len,
        "Typing should be blocked in binary files"
    );
}

/// Test that binary bytes are rendered as <XX> format
#[test]
fn test_binary_bytes_rendered_as_hex() {
    let temp_dir = TempDir::new().unwrap();
    let bin_path = temp_dir.path().join("test.bin");

    // Create a file with specific bytes that we can verify in the rendering:
    // 0x89 (high byte), 0x50 ('P'), 0x4E ('N'), 0x47 ('G'), 0x0D (CR), 0x0A (LF), 0x1A (SUB), 0x0A (LF)
    // This is the PNG signature - we should see <89>PNG<0D><0A><1A><0A>
    // Note: 0x0D (CR) and 0x0A (newline) are allowed whitespace, so they won't be rendered as hex
    let bin_data: &[u8] = &[0x89, 0x50, 0x4E, 0x47, 0x00, 0x01, 0x7F];
    std::fs::write(&bin_path, bin_data).unwrap();

    let mut harness = EditorTestHarness::new(120, 24).unwrap();
    harness.open_file(&bin_path).unwrap();
    harness.render().unwrap();

    // The screen should contain <89> for the first byte (high byte, not valid UTF-8)
    harness.assert_screen_contains("<89>");

    // The screen should contain PNG (printable ASCII is shown as-is)
    harness.assert_screen_contains("PNG");

    // The screen should contain <00> for the null byte
    harness.assert_screen_contains("<00>");

    // The screen should contain <01> for the SOH control character
    harness.assert_screen_contains("<01>");

    // The screen should contain <7F> for the DEL character
    harness.assert_screen_contains("<7F>");
}

/// Test that scrolling through binary files doesn't cause rendering artifacts
/// This validates:
/// 1. Gutter line numbers remain consistent (format: "    N │")
/// 2. Content doesn't overflow into the gutter
/// 3. Screen is identical after scrolling down and back up
/// 4. VT100 parser sees correct output (catches ANSI escape sequence bugs)
#[test]
fn test_binary_file_scrolling_no_artifacts() {
    use crossterm::event::{KeyCode, KeyModifiers};

    let temp_dir = TempDir::new().unwrap();
    let png_path = temp_dir.path().join("test.png");

    // Create a realistic PNG-like file with multiple lines of binary data
    // This simulates a real binary file with multiple newlines creating many "lines"
    let mut png_data = Vec::new();

    // PNG signature
    png_data.extend_from_slice(&[0x89, 0x50, 0x4E, 0x47, 0x0D, 0x0A, 0x1A, 0x0A]);

    // Generate enough binary data to require scrolling (multiple "lines")
    // Add newlines periodically to create multiple lines of binary content
    for i in 0..100 {
        // Add some binary bytes
        for j in 0..20 {
            png_data.push(((i * 20 + j) % 256) as u8);
        }
        // Add a newline to create a new "line"
        png_data.push(0x0A);
    }

    std::fs::write(&png_path, &png_data).unwrap();

    // Use a standard terminal size
    let mut harness = EditorTestHarness::new(80, 24).unwrap();
    harness.open_file(&png_path).unwrap();

    // Use render_real() which processes through VT100 parser for accurate terminal simulation
    harness.render_real().unwrap();

    // Capture initial screen using VT100 parser (more accurate than test backend)
    let initial_screen = harness.vt100_screen_to_string();

    // Validate initial gutter format
    validate_gutter_format(&initial_screen, "initial");

    // Verify test backend matches VT100 output
    harness.assert_test_matches_real();

    // Scroll down several times
    for i in 0..5 {
        harness
            .send_key(KeyCode::PageDown, KeyModifiers::NONE)
            .unwrap();
        harness.render_real().unwrap();
        let screen = harness.vt100_screen_to_string();
        validate_gutter_format(&screen, &format!("after PageDown #{}", i + 1));
        harness.assert_test_matches_real();
    }

    // Scroll back up to the beginning
    for i in 0..5 {
        harness
            .send_key(KeyCode::PageUp, KeyModifiers::NONE)
            .unwrap();
        harness.render_real().unwrap();
        let screen = harness.vt100_screen_to_string();
        validate_gutter_format(&screen, &format!("after PageUp #{}", i + 1));
        harness.assert_test_matches_real();
    }

    // Go to beginning of file using Home key
    harness
        .send_key(KeyCode::Home, KeyModifiers::CONTROL)
        .unwrap();
    harness.render_real().unwrap();

    // Capture final screen after scrolling back
    let final_screen = harness.vt100_screen_to_string();

    // Validate final gutter format
    validate_gutter_format(&final_screen, "final");
    harness.assert_test_matches_real();

    // Compare screens cell by cell for exact match
    compare_screens_cell_by_cell(&initial_screen, &final_screen, 80, 24);
}

/// Compare two screens cell by cell to catch any rendering differences
fn compare_screens_cell_by_cell(initial: &str, final_screen: &str, width: usize, height: usize) {
    let initial_lines: Vec<&str> = initial.lines().collect();
    let final_lines: Vec<&str> = final_screen.lines().collect();

    assert_eq!(
        initial_lines.len(),
        final_lines.len(),
        "Screen height mismatch: initial has {} lines, final has {} lines",
        initial_lines.len(),
        final_lines.len()
    );

    let mut differences = Vec::new();

    for row in 0..height.min(initial_lines.len()) {
        let initial_line = initial_lines.get(row).unwrap_or(&"");
        let final_line = final_lines.get(row).unwrap_or(&"");

        if initial_line != final_line {
            let initial_chars: Vec<char> = initial_line.chars().collect();
            let final_chars: Vec<char> = final_line.chars().collect();

            for col in 0..width.max(initial_chars.len()).max(final_chars.len()) {
                let ic = initial_chars.get(col).copied().unwrap_or(' ');
                let fc = final_chars.get(col).copied().unwrap_or(' ');
                if ic != fc {
                    differences.push(format!(
                        "  Row {}, Col {}: initial '{}' (U+{:04X}) vs final '{}' (U+{:04X})",
                        row, col, ic, ic as u32, fc, fc as u32
                    ));
                }
            }
        }
    }

    if !differences.is_empty() {
        panic!(
            "Screen differs after scrolling!\n\nDifferences:\n{}\n\nInitial screen:\n{}\n\nFinal screen:\n{}",
            differences.join("\n"),
            initial,
            final_screen
        );
    }
}

/// Helper to validate gutter format in screen output
fn validate_gutter_format(screen: &str, context: &str) {
    let lines: Vec<&str> = screen.lines().collect();

    // Skip menu bar (line 0), tab bar (line 1), and check content lines
    // Also skip status bar and prompt line at the bottom
    let content_start = 2;
    let content_end = lines.len().saturating_sub(2);

    for (i, line) in lines.iter().enumerate() {
        if i < content_start || i >= content_end {
            continue;
        }

        // Skip empty lines and tilde lines (EOF markers)
        if line.trim().is_empty() || line.trim().starts_with('~') {
            continue;
        }

        // Each content line should have a gutter separator "│"
        let bar_pos = line.find('');
        assert!(
            bar_pos.is_some(),
            "{}: Line {} is missing gutter separator │.\nLine: '{}'\n\nFull screen:\n{}",
            context,
            i,
            line,
            screen
        );

        let bar_pos = bar_pos.unwrap();
        let before_bar = &line[..bar_pos];

        // Before the bar should only contain spaces, digits (line number),
        // and fold indicators (▾ uncollapsed / ▸ collapsed / ● diagnostic).
        let invalid_chars: Vec<char> = before_bar
            .chars()
            .filter(|c| {
                !c.is_ascii_whitespace() && !c.is_ascii_digit() && !matches!(*c, '' | '' | '')
            })
            .collect();
        assert!(
            invalid_chars.is_empty(),
            "{}: Line {} has content overflowing into gutter.\nGutter area: '{}'\nInvalid chars: {:?}\nLine: '{}'\n\nFull screen:\n{}",
            context, i, before_bar, invalid_chars, line, screen
        );
    }
}