hjkl 0.33.2

Vim-modal terminal editor: standalone TUI built on the hjkl engine.
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
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
//! Quickfix list (#184) app-level tests: nav dispatch, popup toggle, and a
//! real jump-to-entry through a temp file.

use super::*;
use hjkl_ex::QfCommand;
use hjkl_quickfix::{QfEntry, QfKind};

fn entry(path: &std::path::Path, row: usize) -> QfEntry {
    QfEntry {
        path: path.to_path_buf(),
        row,
        col: 0,
        kind: QfKind::Grep,
        message: format!("hit at {row}"),
    }
}

#[test]
fn quickfix_popup_nav_and_toggle() {
    let mut app = App::new(None, false, None, None).unwrap();
    let p = std::path::PathBuf::from("x.rs");
    app.quickfix
        .set(vec![entry(&p, 0), entry(&p, 1), entry(&p, 2)]);

    // `:copen` shows the popup; popup j/k move the highlight without jumping.
    app.handle_quickfix_command(QfCommand::Open);
    assert!(app.quickfix_open);
    app.quickfix_popup_down();
    assert_eq!(app.quickfix.cursor(), 1);
    app.quickfix_popup_down();
    assert_eq!(app.quickfix.cursor(), 2);
    app.quickfix_popup_up();
    assert_eq!(app.quickfix.cursor(), 1);

    // `:cclose` hides it.
    app.handle_quickfix_command(QfCommand::Close);
    assert!(!app.quickfix_open);
}

#[cfg(unix)]
#[test]
fn quickfix_make_parses_output_into_list() {
    // A fake `makeprg` script that emits a gcc-style diagnostic to stderr.
    use std::os::unix::fs::PermissionsExt;
    let dir = std::env::temp_dir().join(format!("hjkl_make_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let script = dir.join("fakemake.sh");
    std::fs::write(
        &script,
        "#!/bin/sh\necho 'src/main.rs:3:5: error: boom' 1>&2\nexit 1\n",
    )
    .unwrap();
    std::fs::set_permissions(&script, std::fs::Permissions::from_mode(0o755)).unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    app.active_editor_mut().settings_mut().makeprg = script.to_string_lossy().into_owned();
    app.handle_quickfix_command(QfCommand::Make(String::new()));

    assert_eq!(app.quickfix.len(), 1, ":make should populate the list");
    assert!(app.quickfix_open, ":make with errors opens the popup");
    let e = app.quickfix.current().unwrap();
    assert_eq!((e.row, e.col), (2, 4)); // 0-based
    assert_eq!(e.kind, QfKind::Error);
    assert_eq!(e.message, "boom");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn quickfix_open_empty_does_not_show() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.handle_quickfix_command(QfCommand::Open);
    assert!(
        !app.quickfix_open,
        "empty quickfix list must not open the popup"
    );
}

#[test]
fn quickfix_next_jumps_to_entry() {
    // `:cnext` moves the list cursor AND jumps the editor to that file+row.
    let dir = std::env::temp_dir().join(format!("hjkl_qf_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("sample.txt");
    std::fs::write(&file, "line zero\nline one\nline two\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    app.quickfix.set(vec![entry(&file, 0), entry(&file, 2)]);

    // Cursor starts at entry 0; :cnext → entry 1 (row 2) and opens the file.
    app.handle_quickfix_command(QfCommand::Next);
    assert_eq!(app.quickfix.cursor(), 1);
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "cnext should jump the editor cursor to the entry's row"
    );

    // `]q` / `[q` route through the same path: [q → back to entry 0 (row 0).
    app.dispatch_action(crate::keymap_actions::AppAction::QuickfixPrev, 1);
    assert_eq!(app.quickfix.cursor(), 0);
    assert_eq!(app.active_editor().cursor().0, 0);

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn loclist_independent_from_quickfix() {
    // The location list is a separate list/popup from the quickfix list.
    let mut app = App::new(None, false, None, None).unwrap();
    let p = std::path::PathBuf::from("x.rs");
    app.loclist.set(vec![entry(&p, 0), entry(&p, 1)]);

    // `:lopen` opens the loclist popup, NOT the quickfix popup.
    app.handle_loclist_command(QfCommand::Open);
    assert!(app.loclist_open);
    assert!(!app.quickfix_open);

    app.loclist_popup_down();
    assert_eq!(app.loclist.cursor(), 1);
    assert_eq!(app.quickfix.cursor(), 0, "quickfix list untouched");

    app.handle_loclist_command(QfCommand::Close);
    assert!(!app.loclist_open);
}

#[test]
fn loclist_next_jumps_and_dispatch_routes() {
    let dir = std::env::temp_dir().join(format!("hjkl_ll_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let file = dir.join("sample.txt");
    std::fs::write(&file, "line zero\nline one\nline two\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    app.loclist.set(vec![entry(&file, 0), entry(&file, 2)]);

    app.handle_loclist_command(QfCommand::Next);
    assert_eq!(app.loclist.cursor(), 1);
    assert_eq!(app.active_editor().cursor().0, 2);

    // `[l` routes through the loclist via dispatch.
    app.dispatch_action(crate::keymap_actions::AppAction::LoclistPrev, 1);
    assert_eq!(app.loclist.cursor(), 0);
    assert_eq!(app.active_editor().cursor().0, 0);

    let _ = std::fs::remove_dir_all(&dir);
}

// ── :cexpr / :cgetexpr / :caddexpr in-process tests (#261) ─────────────────

/// Build an App with a 6-line in-memory buffer (no real file) and set
/// `errorformat` to `%l:%c:%m` so `:cexpr "3:2:three\n5:1:five"` produces
/// two empty-path entries.
fn make_app_with_buffer() -> App {
    let mut app = App::new(None, false, None, None).unwrap();
    // Populate the buffer with 6 lines.
    let content = "line1\nline2\nline3\nline4\nline5\nline6\n";
    app.active_editor_mut().set_content(content);
    // Set errorformat to no-file form.
    app.active_editor_mut().settings_mut().errorformat = "%l:%c:%m".to_string();
    app
}

#[test]
fn cexpr_populates_list_and_jumps_to_first() {
    let mut app = make_app_with_buffer();
    // `:cexpr "3:2:three\n5:1:five"` — two entries, jump=true
    app.handle_quickfix_command(QfCommand::Expr {
        text: r#""3:2:three\n5:1:five""#.to_string(),
        append: false,
        jump: true,
    });
    assert_eq!(app.quickfix.len(), 2, "should have 2 entries");
    // First entry: row=2 (0-based from line 3), col=1
    assert_eq!(app.quickfix.cursor(), 0);
    let e0 = app.quickfix.current().unwrap();
    assert_eq!(e0.row, 2, "entry 0 row should be 2 (0-based)");
    assert_eq!(e0.col, 1, "entry 0 col should be 1 (0-based)");
    // Editor cursor must have jumped to row 2
    assert_eq!(
        app.active_editor().cursor().0,
        2,
        "editor row should be at first entry (row 2)"
    );
    assert_eq!(
        app.active_editor().cursor().1,
        1,
        "editor col should be at first entry (col 1)"
    );
}

#[test]
fn cexpr_then_cnext_moves_to_second_entry() {
    let mut app = make_app_with_buffer();
    app.handle_quickfix_command(QfCommand::Expr {
        text: r#""3:2:three\n5:1:five""#.to_string(),
        append: false,
        jump: true,
    });
    // :cnext should move to the second entry (row 4, col 0)
    app.handle_quickfix_command(QfCommand::Next);
    assert_eq!(app.quickfix.cursor(), 1);
    let e1 = app.quickfix.current().unwrap();
    assert_eq!(e1.row, 4, "entry 1 row should be 4 (0-based from line 5)");
    assert_eq!(e1.col, 0, "entry 1 col should be 0 (0-based from col 1)");
    assert_eq!(
        app.active_editor().cursor().0,
        4,
        "editor row should be at second entry (row 4)"
    );
}

#[test]
fn cgetexpr_populates_but_does_not_jump() {
    let mut app = make_app_with_buffer();
    let initial_row = app.active_editor().cursor().0;
    // :cgetexpr → jump=false, cursor should not move
    app.handle_quickfix_command(QfCommand::Expr {
        text: r#""3:2:three""#.to_string(),
        append: false,
        jump: false,
    });
    assert_eq!(app.quickfix.len(), 1, "list should have 1 entry");
    assert_eq!(
        app.active_editor().cursor().0,
        initial_row,
        "cgetexpr must not move cursor"
    );
}

#[test]
fn caddexpr_appends_to_existing_list() {
    let mut app = make_app_with_buffer();
    // First populate with one entry
    app.handle_quickfix_command(QfCommand::Expr {
        text: r#""2:0:two""#.to_string(),
        append: false,
        jump: false,
    });
    assert_eq!(app.quickfix.len(), 1);
    // caddexpr appends
    app.handle_quickfix_command(QfCommand::Expr {
        text: r#""4:1:four""#.to_string(),
        append: true,
        jump: false,
    });
    assert_eq!(app.quickfix.len(), 2, "caddexpr should append to list");
    // Cursor stays at 0 (not jumped)
    assert_eq!(app.quickfix.cursor(), 0);
}

// ── :cbuffer / :cgetbuffer / :caddbuffer in-process tests (#261 Phase 5b) ───

/// Build an App with buffer content set to 3 error-format lines and errorformat
/// configured to `%l:%c:%m` (no file column) so `:cbuffer` produces empty-path
/// entries at lines 1/2/3 col 1 each (0-based: row 0/1/2 col 0).
fn make_app_with_cbuffer_content() -> App {
    let mut app = App::new(None, false, None, None).unwrap();
    // Three lines matching %l:%c:%m: "1:1:a", "2:1:b", "3:1:c"
    app.active_editor_mut().set_content("1:1:a\n2:1:b\n3:1:c\n");
    app.active_editor_mut().settings_mut().errorformat = "%l:%c:%m".to_string();
    app
}

#[test]
fn cbuffer_populates_list_and_jumps_to_first() {
    let mut app = make_app_with_cbuffer_content();
    app.handle_quickfix_command(QfCommand::FromBuffer {
        append: false,
        jump: true,
    });
    assert_eq!(app.quickfix.len(), 3, "cbuffer should produce 3 entries");
    assert_eq!(app.quickfix.cursor(), 0);
    // First entry: line 1 col 1 → row=0 col=0 (0-based)
    let e0 = app.quickfix.current().unwrap();
    assert_eq!(e0.row, 0, "first entry row should be 0");
    assert_eq!(e0.col, 0, "first entry col should be 0");
    // Editor jumped to first entry
    assert_eq!(
        app.active_editor().cursor().0,
        0,
        "editor row should be at first entry (row 0)"
    );
}

#[test]
fn cbuffer_then_cnext_moves_to_second_entry() {
    let mut app = make_app_with_cbuffer_content();
    app.handle_quickfix_command(QfCommand::FromBuffer {
        append: false,
        jump: true,
    });
    // :cnext → second entry (line 2 col 1 → row=1 col=0)
    app.handle_quickfix_command(QfCommand::Next);
    assert_eq!(app.quickfix.cursor(), 1);
    let e1 = app.quickfix.current().unwrap();
    assert_eq!(e1.row, 1, "second entry row should be 1");
    assert_eq!(
        app.active_editor().cursor().0,
        1,
        "editor row should be at second entry (row 1)"
    );
}

#[test]
fn cgetbuffer_populates_but_does_not_jump() {
    let mut app = make_app_with_cbuffer_content();
    let initial_row = app.active_editor().cursor().0;
    app.handle_quickfix_command(QfCommand::FromBuffer {
        append: false,
        jump: false,
    });
    assert_eq!(app.quickfix.len(), 3, "cgetbuffer should produce 3 entries");
    assert_eq!(
        app.active_editor().cursor().0,
        initial_row,
        "cgetbuffer must not move cursor"
    );
}

#[test]
fn caddbuffer_appends_to_existing_list() {
    let mut app = make_app_with_cbuffer_content();
    // Populate with one entry first
    app.handle_quickfix_command(QfCommand::FromBuffer {
        append: false,
        jump: false,
    });
    assert_eq!(app.quickfix.len(), 3);
    // Change buffer content and caddbuffer — should append
    app.active_editor_mut().set_content("4:1:d\n5:1:e\n");
    app.handle_quickfix_command(QfCommand::FromBuffer {
        append: true,
        jump: false,
    });
    assert_eq!(
        app.quickfix.len(),
        5,
        "caddbuffer should append to existing list"
    );
    // Cursor stays at 0 (not jumped)
    assert_eq!(app.quickfix.cursor(), 0);
}

// ── :cfile / :cgetfile / :caddfile in-process tests (#261 Phase 5b) ─────────

#[test]
fn cfile_populates_list_from_disk_and_jumps() {
    // Write a temp file containing errorformat lines.
    let dir = std::env::temp_dir().join(format!("hjkl_cfile_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();
    let errfile = dir.join("errors.txt");
    // Use %f:%l:%c:%m so entries reference themselves; for jump we need a
    // reachable file — use the errfile itself so no extra files are needed.
    // Actually, for a simpler test use %l:%c:%m (no %f) so path is empty and
    // the jump stays in-buffer (no do_edit).
    let errfile_path = errfile.to_str().unwrap().to_string();
    std::fs::write(&errfile, "1:1:alpha\n2:1:beta\n3:1:gamma\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    app.active_editor_mut().settings_mut().errorformat = "%l:%c:%m".to_string();

    app.handle_quickfix_command(QfCommand::FromFile {
        path: errfile_path,
        append: false,
        jump: true,
    });

    assert_eq!(app.quickfix.len(), 3, "cfile should produce 3 entries");
    let e0 = app.quickfix.current().unwrap();
    assert_eq!(e0.row, 0, "first entry row should be 0");

    let _ = std::fs::remove_dir_all(&dir);
}

#[test]
fn cfile_missing_path_reports_error() {
    let mut app = App::new(None, false, None, None).unwrap();
    app.active_editor_mut().settings_mut().errorformat = "%l:%c:%m".to_string();
    // Non-existent file should produce an error bus message and leave list empty.
    app.handle_quickfix_command(QfCommand::FromFile {
        path: "/nonexistent/path/errors.err".to_string(),
        append: false,
        jump: false,
    });
    assert_eq!(
        app.quickfix.len(),
        0,
        "cfile on missing file leaves list empty"
    );
}

// ── :cdo / :cfdo / :ldo / :lfdo in-process tests (#261 Phase 5b "A2") ───────

/// Read the rope line at 0-based `row` from the active editor.
fn buf_row(app: &App, row: usize) -> String {
    hjkl_buffer::rope_line_str(&app.active_editor().buffer().rope(), row)
}

#[test]
fn cdo_runs_command_per_entry() {
    // App with a 5-line buffer; errorformat=%l:%c:%m; :cexpr produces two
    // empty-path entries at rows 1 (line 2) and 3 (line 4); :cdo s/^/X/
    // prepends X to each of those rows.
    let mut app = App::new(None, false, None, None).unwrap();
    app.active_editor_mut()
        .set_content("alpha\nbeta\ngamma\ndelta\nepsilon\n");
    app.active_editor_mut().settings_mut().errorformat = "%l:%c:%m".to_string();

    // Populate the quickfix list with entries at lines 2 and 4 (0-based rows 1,3).
    app.handle_quickfix_command(QfCommand::Expr {
        text: r#""2:1:a\n4:1:b""#.to_string(),
        append: false,
        jump: false,
    });
    assert_eq!(app.quickfix.len(), 2, "should have 2 entries");

    // Run :cdo s/^/X/
    app.handle_quickfix_command(QfCommand::Do {
        cmd: "s/^/X/".to_string(),
        per_file: false,
    });

    // Rows 1 and 3 should now start with X; others unchanged.
    assert_eq!(buf_row(&app, 0), "alpha", "row 0 must be untouched");
    assert!(
        buf_row(&app, 1).starts_with('X'),
        "row 1 must start with X, got: {:?}",
        buf_row(&app, 1)
    );
    assert_eq!(buf_row(&app, 2), "gamma", "row 2 must be untouched");
    assert!(
        buf_row(&app, 3).starts_with('X'),
        "row 3 must start with X, got: {:?}",
        buf_row(&app, 3)
    );
    assert_eq!(buf_row(&app, 4), "epsilon", "row 4 must be untouched");
}

#[test]
fn cfdo_runs_once_per_file() {
    // Build two real temp files, populate the quickfix list with entries
    // referencing them (2 entries in fileA, 1 in fileB), run :cfdo s/^/Z/,
    // and assert that the substitution ran exactly once per file.
    let dir = std::env::temp_dir().join(format!("hjkl_cfdo_test_{}", std::process::id()));
    std::fs::create_dir_all(&dir).unwrap();

    let file_a = dir.join("a.txt");
    let file_b = dir.join("b.txt");
    // fileA: 4 lines; fileB: 3 lines
    std::fs::write(&file_a, "alpha\nbeta\ngamma\ndelta\n").unwrap();
    std::fs::write(&file_b, "uno\ndos\ntres\n").unwrap();

    let mut app = App::new(None, false, None, None).unwrap();
    // Populate quickfix: two entries in fileA (rows 0,1), one in fileB (row 0).
    app.quickfix.set(vec![
        QfEntry {
            path: file_a.clone(),
            row: 0,
            col: 0,
            kind: QfKind::Grep,
            message: "a0".into(),
        },
        QfEntry {
            path: file_a.clone(),
            row: 1,
            col: 0,
            kind: QfKind::Grep,
            message: "a1".into(),
        },
        QfEntry {
            path: file_b.clone(),
            row: 0,
            col: 0,
            kind: QfKind::Grep,
            message: "b0".into(),
        },
    ]);

    // :cfdo s/^/Z/ — runs once per distinct file.
    app.handle_quickfix_command(QfCommand::Do {
        cmd: "s/^/Z/".to_string(),
        per_file: true,
    });

    // After :cfdo the editor last opened fileB (last visited file).
    // fileA row 0 was the cursor position for fileA's visit → got Z prepended.
    // fileA row 1 (second entry, same file) was NOT visited.
    // Verify by opening files explicitly.
    app.dispatch_ex(&format!("e {}", file_a.display()));
    let row0_a = buf_row(&app, 0);
    let row1_a = buf_row(&app, 1);
    assert!(
        row0_a.starts_with('Z'),
        "fileA row 0 must start with Z (cfdo visited first entry), got: {row0_a:?}"
    );
    assert!(
        !row1_a.starts_with('Z'),
        "fileA row 1 must NOT start with Z (second entry skipped by cfdo), got: {row1_a:?}"
    );

    app.dispatch_ex(&format!("e {}", file_b.display()));
    let row0_b = buf_row(&app, 0);
    assert!(
        row0_b.starts_with('Z'),
        "fileB row 0 must start with Z (cfdo visited its single entry), got: {row0_b:?}"
    );

    let _ = std::fs::remove_dir_all(&dir);
}

// ── :colder / :cnewer list-stack tests (#261 Phase 5b) ──────────────────────

/// Helper: populate quickfix via Expr (non-append) with a given `%l:%c:%m` line.
fn populate_expr(app: &mut App, text: &str) {
    app.handle_quickfix_command(QfCommand::Expr {
        text: text.to_string(),
        append: false,
        jump: false,
    });
}

#[test]
fn colder_restores_previous_list() {
    let mut app = make_app_with_buffer();
    // List A: single entry at line 2 (row 1)
    populate_expr(&mut app, r#""2:1:a""#);
    let entries_a: Vec<_> = app.quickfix.entries().to_vec();
    // List B: single entry at line 4 (row 3)
    populate_expr(&mut app, r#""4:1:b""#);
    let entries_b: Vec<_> = app.quickfix.entries().to_vec();

    // Sanity: current is B.
    assert_eq!(app.quickfix.entries(), entries_b.as_slice());

    // :colder → current should be A.
    app.handle_quickfix_command(QfCommand::Older(1));
    assert_eq!(
        app.quickfix.entries(),
        entries_a.as_slice(),
        "colder should restore list A"
    );
    assert!(
        app.quickfix_older.is_empty(),
        "older should be empty after single colder"
    );
    assert_eq!(app.quickfix_newer.len(), 1, "newer should hold list B");

    // :cnewer → current should be B again.
    app.handle_quickfix_command(QfCommand::Newer(1));
    assert_eq!(
        app.quickfix.entries(),
        entries_b.as_slice(),
        "cnewer should restore list B"
    );
    assert!(
        app.quickfix_newer.is_empty(),
        "newer should be empty after cnewer"
    );
}

#[test]
fn populate_while_older_discards_newer_branch() {
    let mut app = make_app_with_buffer();
    // Populate A, then B, then go colder (back to A).
    populate_expr(&mut app, r#""2:1:a""#);
    let entries_a: Vec<_> = app.quickfix.entries().to_vec();
    populate_expr(&mut app, r#""4:1:b""#);
    app.handle_quickfix_command(QfCommand::Older(1));
    // Current = A, newer holds B.
    assert_eq!(app.quickfix.entries(), entries_a.as_slice());
    assert_eq!(app.quickfix_newer.len(), 1);

    // Populate C while at A (not at top of newer stack).
    populate_expr(&mut app, r#""6:1:c""#);

    // newer must be cleared — populating discards the redo branch.
    assert!(
        app.quickfix_newer.is_empty(),
        "newer branch must be cleared on fresh populate"
    );
    // :cnewer should now be a no-op (no newer entries).
    let entries_c: Vec<_> = app.quickfix.entries().to_vec();
    app.handle_quickfix_command(QfCommand::Newer(1));
    assert_eq!(
        app.quickfix.entries(),
        entries_c.as_slice(),
        "cnewer should be no-op when newer is empty"
    );
}

#[test]
fn colder_saturates_when_no_older() {
    let mut app = make_app_with_buffer();
    populate_expr(&mut app, r#""2:1:a""#);
    let entries_a: Vec<_> = app.quickfix.entries().to_vec();
    // No prior list — colder should leave current unchanged.
    app.handle_quickfix_command(QfCommand::Older(1));
    assert_eq!(
        app.quickfix.entries(),
        entries_a.as_slice(),
        "colder on oldest list should not change current"
    );
}

#[test]
fn cnewer_saturates_when_no_newer() {
    let mut app = make_app_with_buffer();
    populate_expr(&mut app, r#""2:1:a""#);
    let entries_a: Vec<_> = app.quickfix.entries().to_vec();
    // No newer list — cnewer should leave current unchanged.
    app.handle_quickfix_command(QfCommand::Newer(1));
    assert_eq!(
        app.quickfix.entries(),
        entries_a.as_slice(),
        "cnewer on newest list should not change current"
    );
}

#[test]
fn loclist_colder_cnewer_work_independently() {
    let mut app = make_app_with_buffer();
    app.active_editor_mut().settings_mut().errorformat = "%l:%c:%m".to_string();

    // Populate loclist A then B.
    app.handle_loclist_command(QfCommand::Expr {
        text: r#""2:1:la""#.to_string(),
        append: false,
        jump: false,
    });
    let loc_a: Vec<_> = app.loclist.entries().to_vec();
    app.handle_loclist_command(QfCommand::Expr {
        text: r#""4:1:lb""#.to_string(),
        append: false,
        jump: false,
    });
    let loc_b: Vec<_> = app.loclist.entries().to_vec();

    // quickfix must be untouched.
    assert!(app.quickfix.is_empty());

    // lolder → restore A.
    app.handle_loclist_command(QfCommand::Older(1));
    assert_eq!(app.loclist.entries(), loc_a.as_slice());

    // lnewer → restore B.
    app.handle_loclist_command(QfCommand::Newer(1));
    assert_eq!(app.loclist.entries(), loc_b.as_slice());
}

// ── :diagnostics / :ldiagnostics in-process tests (#261 Phase 5b A3) ────────

fn make_lsp_diag(
    start_row: usize,
    start_col: usize,
    severity: DiagSeverity,
    message: &str,
) -> LspDiag {
    LspDiag {
        start_row,
        start_col,
        end_row: start_row,
        end_col: start_col + message.len(),
        severity,
        message: message.to_string(),
        source: None,
        code: None,
    }
}

#[test]
fn diagnostics_populates_quickfix_from_all_buffers() {
    let mut app = App::new(None, false, None, None).unwrap();

    // Inject diagnostics onto the active (only) slot.
    app.active_mut().lsp_diags = vec![
        make_lsp_diag(5, 3, DiagSeverity::Error, "type mismatch"),
        make_lsp_diag(2, 0, DiagSeverity::Hint, "consider renaming"),
        make_lsp_diag(2, 10, DiagSeverity::Warning, "unused variable"),
    ];

    app.handle_quickfix_command(QfCommand::Diagnostics);

    // 3 diags, sorted by (path, row, col): row2/col0, row2/col10, row5/col3.
    assert_eq!(app.quickfix.len(), 3, "quickfix should have 3 entries");
    assert!(app.quickfix_open, "popup should be open when diags present");

    let entries = app.quickfix.entries();
    assert_eq!(entries[0].row, 2);
    assert_eq!(entries[0].col, 0);
    assert_eq!(entries[0].kind, QfKind::Note, "Hint → Note");

    assert_eq!(entries[1].row, 2);
    assert_eq!(entries[1].col, 10);
    assert_eq!(entries[1].kind, QfKind::Warning, "Warning → Warning");

    assert_eq!(entries[2].row, 5);
    assert_eq!(entries[2].col, 3);
    assert_eq!(entries[2].kind, QfKind::Error, "Error → Error");

    // Location list must be untouched.
    assert!(app.loclist.is_empty(), "loclist must not be touched");
}

#[test]
fn ldiagnostics_uses_current_buffer_only() {
    let mut app = App::new(None, false, None, None).unwrap();

    app.active_mut().lsp_diags = vec![
        make_lsp_diag(1, 0, DiagSeverity::Info, "info message"),
        make_lsp_diag(0, 5, DiagSeverity::Warning, "warn here"),
    ];

    app.handle_loclist_command(QfCommand::Diagnostics);

    // 2 diags, sorted: row0/col5, row1/col0.
    assert_eq!(app.loclist.len(), 2, "loclist should have 2 entries");
    assert!(app.loclist_open, "loclist popup should be open");

    let entries = app.loclist.entries();
    assert_eq!(entries[0].row, 0);
    assert_eq!(entries[0].col, 5);
    assert_eq!(entries[0].kind, QfKind::Warning);

    assert_eq!(entries[1].row, 1);
    assert_eq!(entries[1].col, 0);
    assert_eq!(entries[1].kind, QfKind::Info);

    // Quickfix must be untouched.
    assert!(app.quickfix.is_empty(), "quickfix must not be touched");
    assert!(!app.quickfix_open, "quickfix popup must not be open");
}

#[test]
fn diagnostics_empty_no_popup() {
    let mut app = App::new(None, false, None, None).unwrap();

    // No diags injected — lsp_diags is empty by default.
    app.handle_quickfix_command(QfCommand::Diagnostics);

    assert!(app.quickfix.is_empty(), "list must remain empty");
    assert!(!app.quickfix_open, "popup must stay closed when no diags");
}