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
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
//! Link-following and back/forward navigation: the [`NavEntry`] stack record,
//! the [`App`] methods over `nav_back` / `nav_forward`, the buffer-replacement
//! helper [`App::load_file_into_editor`], and the [`App::follow_link`]
//! dispatcher.
use std::path::{Path, PathBuf};
use anyhow::Result;
use crate::app::flash::MessageKind;
use crate::app::modal;
use crate::config::cursor_key;
use crate::docs::DocId;
use crate::document::Buffer;
use crate::editor::link::LinkTarget;
use crate::editor::{mouse_ops, EditorState, Mode};
use crate::ui::EditorViewState;
use super::App;
/// Where a [`NavEntry`] restores to.
#[derive(Debug, Clone)]
pub(super) enum NavDest {
/// A file to load before restoring scroll/cursor/mode. A cross-file
/// restore passes through the dirty guard.
File(PathBuf),
/// A position within the *currently loaded* document (footnote follow,
/// `#heading` jump, footnote back-link): no reload, no dirty guard, and no
/// path — so history is recorded even for an unsaved `[No file]` buffer.
///
/// `footnote` names the footnote whose reference was followed to leave this
/// position (`None` for a heading jump), so a definition's back-link can
/// distinguish "I arrived by following *this* footnote" from an unrelated
/// jump sitting on the stack.
InDocument { footnote: Option<String> },
/// A page of the embedded manual, named by id because it has no path — the
/// text lives in the binary.
EmbeddedDoc(DocId),
}
/// A destination held across the dirty guard, which has to name it in its prose
/// and resume it on Save / Discard. Not a `PathBuf`: a manual page would need a
/// fake one, which every point treating a path as a real file (the watcher,
/// `Save`, the own-write hash) would then have to recognize and strip.
#[derive(Debug, Clone)]
pub(crate) enum NavPending {
File(PathBuf),
Doc(DocId),
}
impl NavPending {
/// How the destination is named in the dirty guard's prose.
pub(crate) fn display_name(&self) -> String {
match self {
NavPending::File(p) => p.display().to_string(),
NavPending::Doc(id) => format!("the {} documentation", id.title()),
}
}
}
/// One entry on [`App::nav_back`] / [`App::nav_forward`]: enough state to
/// restore the exact scroll / cursor / mode a position was left in.
#[derive(Debug, Clone)]
pub(super) struct NavEntry {
pub(super) dest: NavDest,
pub(super) scroll: usize,
pub(super) cursor_offset: usize,
pub(super) mode: Mode,
}
/// True when `path` ends in `.md` / `.markdown` (case-insensitive) — "is this a
/// file edamame handles?".
///
/// Shared by `App::follow_link` (open in-editor or hand to the OS?) and
/// [`super::difftool::is_markdown_pair`] (is a `--diff` pair reviewable?) rather
/// than copied: the two disagreeing is how a `git difftool` walk would open a
/// full-screen review of a shell script.
pub(super) fn is_markdown_path(path: &Path) -> bool {
path.extension()
.and_then(|e| e.to_str())
.map(|e| {
let lower = e.to_ascii_lowercase();
lower == "md" || lower == "markdown"
})
.unwrap_or(false)
}
impl App {
/// Resolve the link under the keyboard cursor. Shares
/// `mouse_ops::link_at_offset` with the mouse path, so `FollowLink` behaves
/// identically whichever device fired it.
pub(super) fn resolve_link_at_cursor(&self) -> Option<LinkTarget> {
let cursor_byte = self
.editor
.buffer
.rope()
.char_to_byte(self.editor.cursor.offset);
let source = self.editor.buffer.contents();
// Unambiguous (`[^…]` with no `(url)`), so checked first.
if let Some(target) = mouse_ops::footnote_at_offset(&source, cursor_byte) {
return Some(target);
}
let url = mouse_ops::link_at_offset(&source, cursor_byte)?;
let base_dir = self.file_path.as_deref().and_then(|p| p.parent());
Some(LinkTarget::parse(&url, base_dir))
}
/// Follow `target` by its classified kind. A no-op for an empty anchor or
/// an unknown heading slug, and when the dirty guard intercepts.
pub(super) fn follow_link(&mut self, target: LinkTarget, doc_height: usize, doc_width: usize) {
match target {
LinkTarget::Url(url) => {
self.spawn_open_worker(url);
}
LinkTarget::Anchor(slug) => {
self.scroll_to_heading(&slug, doc_height, doc_width);
}
LinkTarget::Footnote(label) => {
self.follow_footnote_reference(&label, doc_height, doc_width);
}
LinkTarget::FootnoteBack(label) => {
self.follow_footnote_back_link(&label, doc_height, doc_width);
}
LinkTarget::LocalFile { path, fragment } => {
// A link inside a manual page resolves against the *embedded*
// set: the page is pathless, so `LinkTarget::parse` had no
// `base_dir` and returned a bare relative path, which the branch
// below would resolve against the process's working directory —
// opening whatever `security.md` sits next to the user's shell.
//
// Gated here rather than in `LinkTarget::parse`, which is pure
// and must keep answering the same way for an ordinary document
// that links to a file of its own by one of these names.
if self.open_doc.is_some() {
match crate::docs::resolve_doc_reference(&path, fragment) {
crate::docs::DocLinkResolution::Doc(id, frag) => {
// No dirty guard: a manual page is read-only, so
// `dirty` cannot be set while one is open.
self.open_doc_page(id, frag, doc_height, doc_width);
}
// Ships in the repository but not in the binary (the
// contributor docs, the root `SECURITY.md`).
crate::docs::DocLinkResolution::External(url) => {
self.spawn_open_worker(url);
}
}
return;
}
if is_markdown_path(&path) {
if self.editor.dirty {
self.open_dirty_guard(NavPending::File(path), fragment);
} else {
let _ = self.navigate_to_file_at(path, fragment, doc_height, doc_width);
}
} else {
// Non-Markdown: defer to the OS handler, via the same
// worker path as remote URLs.
let url = path.to_string_lossy().into_owned();
self.spawn_open_worker(url);
}
}
}
}
/// Rendered-line index of the heading `fragment` names in the currently
/// loaded document, if any. Both the in-document `#anchor` path and the
/// cross-file deep link resolve through here, so they can't drift.
///
/// Matched exactly against `ParsedDoc::heading_anchors`, keyed by GFM slug.
/// Deliberately no leniency — no slugifying `#Getting Started`, no case
/// folding: a fragment that resolved only here would be a link the author
/// ships broken everywhere else without ever seeing it fail.
pub(super) fn heading_line_for_fragment(&self, fragment: &str) -> Option<usize> {
self.editor.parsed.heading_anchors.get(fragment).copied()
}
/// Scroll so `slug`'s heading sits at the viewport top, moving the cursor
/// onto it in editing modes. No-op for a slug not in the anchor table.
pub(super) fn scroll_to_heading(&mut self, slug: &str, doc_height: usize, doc_width: usize) {
let Some(line_idx) = self.heading_line_for_fragment(slug) else {
return;
};
// So `NavigateBack` returns to the link. Tagged `None`: a heading
// jump isn't a footnote follow.
self.record_in_doc_jump(None);
self.scroll_to_rendered_line(line_idx, doc_height, doc_width);
}
/// Scroll so rendered line `line_idx` sits at the viewport top, moving the
/// cursor to its first source byte in editing modes. Records no nav
/// history — callers push the origin first.
pub(super) fn scroll_to_rendered_line(
&mut self,
line_idx: usize,
doc_height: usize,
doc_width: usize,
) {
self.editor.scroll = self.editor.parsed.visual_rows_before(line_idx, doc_width);
if self.editor.mode != Mode::Preview {
if let Some(byte) = self
.editor
.parsed
.source_map
.original_byte_for_rendered_line(line_idx)
{
let char_offset = self.editor.buffer.rope().byte_to_char(byte);
self.editor.cursor.offset = char_offset.min(self.editor.buffer.len_chars());
self.editor.update_cursor_block();
self.editor.ensure_cursor_visible(doc_height, doc_width);
}
}
self.mark_scrolling();
}
/// Follow a footnote reference to its definition, recording the origin so
/// the back-link returns here. No-op for an undefined label.
pub(super) fn follow_footnote_reference(
&mut self,
label: &str,
doc_height: usize,
doc_width: usize,
) {
let Some(&line_idx) = self.editor.parsed.footnote_anchors.get(label) else {
return;
};
// Tagged so the definition's back-link recognizes *this* follow.
self.record_in_doc_jump(Some(label.to_string()));
self.scroll_to_rendered_line(line_idx, doc_height, doc_width);
}
/// Follow a footnote definition's back-link: to the exact spot the reader
/// came from, or — if they scrolled here directly — to the footnote's first
/// reference.
pub(super) fn follow_footnote_back_link(
&mut self,
label: &str,
doc_height: usize,
doc_width: usize,
) {
// Only when the top entry records following *this* footnote; an
// unrelated jump on the stack would warp the reader elsewhere.
let top_is_this_footnote = matches!(
self.nav_back.last().map(|e| &e.dest),
Some(NavDest::InDocument { footnote: Some(l) }) if l == label
);
if top_is_this_footnote {
self.navigate_back(doc_height, doc_width);
return;
}
if let Some(line_idx) = self.first_reference_line(label) {
self.record_in_doc_jump(None);
self.scroll_to_rendered_line(line_idx, doc_height, doc_width);
}
}
/// Rendered-line index of the first `[^label]` reference — not the
/// `[^label]:` definition — in the current buffer.
fn first_reference_line(&self, label: &str) -> Option<usize> {
let source = self.editor.buffer.contents();
let needle = format!("[^{label}]");
let mut from = 0;
while let Some(rel) = source[from..].find(&needle) {
let at = from + rel;
let after = at + needle.len();
if source.as_bytes().get(after) != Some(&b':') {
return Some(
self.editor
.parsed
.source_map
.rendered_lines_for_byte(at)
.start,
);
}
from = after;
}
None
}
/// Restore the cursor parked by [`App::new`] and park the viewport's vertical middle on it,
/// re-centring for the first few frames while image decodes land and the row space settles.
///
/// Runs from `prepare_viewport`, like [`Self::apply_startup_anchor`], and clears itself: a
/// later frame must not yank a reader who has scrolled away. Centering (rather than an
/// `ensure_cursor_visible` nudge) is what keeps the cursor clear of both edges, so the
/// `ensure_cursor_visible` calls that follow this in the same frame are no-ops and the restored
/// scroll survives them. A position within `height / 2` rows of the top clamps to the top,
/// which is as close to centered as the document allows.
///
/// The settle loop exists because a one-shot centre is computed in the wrong row space:
/// [`crate::image::ImageCache::reserved_rows`] answers `None` — the `image_max_height` fallback
/// — until a decode lands, and every figure then collapses to its real height. Centred on
/// frame 0 and never revisited, the viewport ended up past the *end* of the settled document,
/// which paints nothing at all.
///
/// An explicit `#section` on the command line outranks the remembered cursor: when a
/// [`Self::startup_anchor`] is still pending — it is consumed just after this in the same frame
/// — the restore is dropped entirely, so the anchor is not re-centred away on a later settle
/// frame.
pub(super) fn apply_pending_cursor_restore(&mut self, doc_height: usize, doc_width: usize) {
let Some(mut pending) = self.pending_cursor_restore else {
return;
};
if self.startup_anchor.is_some() {
self.pending_cursor_restore = None;
return;
}
// A file rewritten shorter can no longer hold the offset, so past end-of-file opens at the
// top instead. `==` is the valid end position, so the guard is `>`.
if pending.offset > self.editor.buffer.len_chars() {
self.pending_cursor_restore = None;
return;
}
// Placed once; only the scroll is re-derived, so the loop doesn't re-run the cursor-block
// bookkeeping (which re-arms the raw-reveal dwell) on every frame it stays armed.
if self.editor.cursor.offset != pending.offset {
self.editor.place_cursor(pending.offset);
}
self.editor
.set_scroll_for_cursor_screen_row(doc_height / 2, doc_width);
pending.frames_left = pending.frames_left.saturating_sub(1);
self.pending_cursor_restore = if pending.frames_left > 0 && self.row_space_still_settling()
{
Some(pending)
} else {
None
};
self.needs_draw = true;
}
/// Whether any image or figure block is still reserving the `image_max_height` fallback instead
/// of its real height, i.e. whether the row space the viewport is centred in can still change
/// under it.
///
/// A block with no cache entry counts: on the first frame the decodes have not been *requested*
/// yet — `prepare_viewport` dispatches them after this — so "no entry" is the normal state of a
/// document whose figures are about to land, not a settled one. A block that is never requested
/// at all (it is outside the near-viewport decode window) keeps the loop armed, which is why
/// the loop has a frame budget.
fn row_space_still_settling(&self) -> bool {
self.editor.parsed.image_blocks.iter().any(|b| {
matches!(
self.editor.images.status(&b.url),
None | Some(crate::image::DecodeStatus::Pending)
)
})
}
/// Apply the `#section` the command line named (`edamame notes.md#setup`),
/// then clear it so it happens once.
///
/// Runs from the first frame's `prepare_viewport`, not `App::new`: the jump
/// needs live document dimensions, which nothing knows until a frame is
/// measured. Records no nav entry — there is no earlier position to return
/// to. A section resolving to nothing is reported on the hint line.
pub(super) fn apply_startup_anchor(&mut self, doc_height: usize, doc_width: usize) {
let Some(fragment) = self.startup_anchor.take() else {
return;
};
match self.heading_line_for_fragment(&fragment) {
Some(line_idx) => self.scroll_to_rendered_line(line_idx, doc_height, doc_width),
None => self.flash(
format!("No section '#{fragment}' in this document"),
MessageKind::Info,
),
}
self.needs_draw = true;
}
/// Push the current position onto `nav_back` and load `path`, clearing
/// `nav_forward` (browser semantics). Returns whether the load succeeded.
pub(super) fn navigate_to_file(&mut self, path: PathBuf) -> bool {
let entry = self.current_file_entry();
if let Err(err) = self.load_file_into_editor(path.clone()) {
tracing::warn!(target: "link", path = %path.display(), error = %err, "failed to load linked file");
return false;
}
if let Some(e) = entry {
self.nav_back.push(e);
}
self.nav_forward.clear();
true
}
/// [`App::navigate_to_file`] plus the deep-link half: scroll to the heading
/// `fragment` names once the file is loaded.
///
/// Records *no* in-document history entry, unlike
/// [`App::scroll_to_heading`]: `navigate_to_file` already pushed the origin
/// as a file entry, so one `NavigateBack` returns to the link rather than to
/// the top of a document the reader never saw. A fragment naming no heading
/// says so on the hint line rather than silently dropping half the link.
///
/// The returned bool also says whether this call has taken ownership of the
/// viewport: a caller that would otherwise re-assert cursor visibility (the
/// dirty guard) must skip it on `true`, since a freshly loaded editor starts
/// in `Mode::Preview`, where the jump moves `scroll` without the cursor and
/// an `ensure_cursor_visible` drags the reader back to line 0.
pub(super) fn navigate_to_file_at(
&mut self,
path: PathBuf,
fragment: Option<String>,
doc_height: usize,
doc_width: usize,
) -> bool {
if !self.navigate_to_file(path) {
return false;
}
let Some(fragment) = fragment else {
return true;
};
// The new editor was built at a default width; the anchor table and the
// scroll arithmetic want the live one.
self.editor.set_viewport_width(doc_width);
match self.heading_line_for_fragment(&fragment) {
Some(line_idx) => self.scroll_to_rendered_line(line_idx, doc_height, doc_width),
None => self.flash(
format!("No section '#{fragment}' in this document"),
MessageKind::Info,
),
}
true
}
/// Build the `EditorState` for a document replacing the current one, wired
/// to everything an editor needs from `App` and `Config`.
///
/// Shared because the wiring has drifted twice — the encoder worker's
/// `ResizeRequest` sender, and `cursor_blink` — each time invisibly until a
/// *second* document was opened. The two callers, a file off disk and an
/// embedded manual page, differ only in where the `Buffer` came from.
pub(super) fn editor_for_buffer(&self, buffer: Buffer) -> EditorState {
let mut new_editor = EditorState::new_with_image_config(
buffer,
self.theme,
self.config.editor.preserve_blank_lines,
self.config.editor.visual_line_nav,
self.config.images.max_height,
self.config.images.max_width,
self.capabilities
.image_picker
.as_ref()
.map(|p| {
// ratatui-image 11 returns a `FontSize`; we carry a tuple.
let fs = p.font_size();
(fs.width, fs.height)
})
.unwrap_or((10, 20)),
);
// The sender lives on the App because the cache needing it is rebuilt
// per document. Without it `get_protocol_pair` returns `None` and
// images decode fine but paint as placeholders forever.
if let Some(tx) = self.resize_tx.clone() {
new_editor.images.attach_resize_sender(tx);
}
// Everything else from `Config`, shared with `App::new` — including a
// session `No` or persisted `Never`, which stays in effect here.
super::configure_new_editor(
&mut new_editor,
&self.config,
self.images_layout_enabled(),
self.diagrams_layout_enabled(),
);
new_editor
}
/// Remember where the cursor sits in the file about to be replaced, so reopening it resumes
/// there. Called from [`Self::load_file_into_editor`] — the only place a switch can observe
/// the outgoing cursor, since the swap replaces the editor wholesale — and from the tail of
/// [`App::run`], where every quit path funnels.
///
/// Three deliberate no-ops: the switch off, no file to reopen (a `--diff` review, an embedded
/// manual page), and an unchanged position, which must not rewrite the machine file.
///
/// Offset `0` *is* recorded, but only to *update* a file that already has an entry — a reader
/// who scrolls back to the top wants to resume there next time. A file with no entry left at
/// the top earns none: an offset-`0` restore and no restore land in the same place, so a fresh
/// entry would only spend a slot (and a `state.toml` write) on every file merely looked at.
///
/// The write goes through `save_state_bookkeeping`, so a `--no-config` session records nothing
/// — the same gate that suppresses `state.toml` everywhere else.
pub(super) fn record_cursor_position(&mut self) {
if !self.config.editor.remember_cursor {
return;
}
let Some(path) = self.file_path.clone() else {
return;
};
let offset = self.editor.cursor.offset;
let key = cursor_key(&path);
match self.state.cursor_for(&key) {
Some(existing) if existing == offset => return,
None if offset == 0 => return,
_ => {}
}
self.state.remember_cursor(key, offset);
self.save_state_bookkeeping("remembered cursor position");
}
pub(super) fn load_file_into_editor(&mut self, path: PathBuf) -> Result<()> {
let buffer = Buffer::load_file(&path)?;
// The document being left keeps its position; this is the last moment it is knowable.
self.record_cursor_position();
// Stamp the own-write filter from the bytes just read, so the inotify
// event some backends synthesize on `open(2)` is suppressed.
self.set_disk_hash(buffer.contents().as_bytes());
self.editor = self.editor_for_buffer(buffer);
self.file_path = Some(path.clone());
// `open_doc` and `file_path` are mutually exclusive, and this is the
// transition back to a real file. Leaving it set would keep the status
// bar naming a page the reader has left and — worse — keep `follow_link`
// resolving relative links against the embedded manual.
self.open_doc = None;
self.view_state = EditorViewState::new();
// The counterpart of `load_doc_into_editor`'s park: a vim session
// suspended for a read-only document comes back with the next editable
// one.
self.sync_vim_suspension();
// Marks the image cache dirty and re-evaluates the per-document media
// prompts; a session answer already given is not re-asked.
self.on_document_contents_swapped();
// Best-effort: a failure leaves the user without external-edit prompts
// on this file.
if let Some(w) = self.watcher.as_mut() {
if let Err(e) = w.watch(&path) {
tracing::warn!(target: "watcher", path = %path.display(), error = %e, "watch swap failed");
}
}
Ok(())
}
/// Snapshot the current position as a *file* nav entry, or `None` with no
/// associated path — an entry we can't name can't be reloaded.
pub(super) fn current_file_entry(&self) -> Option<NavEntry> {
self.file_path.clone().map(|path| NavEntry {
dest: NavDest::File(path),
scroll: self.editor.scroll,
cursor_offset: self.editor.cursor.offset,
mode: self.editor.mode,
})
}
/// Snapshot wherever we are now as the entry to return *to*. Every site
/// recording an origin before replacing the document goes through here
/// rather than `current_file_entry`, which returns `None` for a pathless
/// manual page and so loses the way back.
pub(super) fn current_origin_entry(&self) -> Option<NavEntry> {
if let Some(id) = self.open_doc {
return Some(NavEntry {
dest: NavDest::EmbeddedDoc(id),
scroll: self.editor.scroll,
cursor_offset: self.editor.cursor.offset,
mode: self.editor.mode,
});
}
self.current_file_entry()
}
/// Snapshot the current position as an *in-document* nav entry. Needs no
/// path, so jumps record history even in an unsaved `[No file]` buffer.
/// `footnote` tags which footnote, if any, is being followed away from.
pub(super) fn current_in_doc_entry(&self, footnote: Option<String>) -> NavEntry {
NavEntry {
dest: NavDest::InDocument { footnote },
scroll: self.editor.scroll,
cursor_offset: self.editor.cursor.offset,
mode: self.editor.mode,
}
}
/// The shared prelude for every in-document jump: push the current position
/// onto `nav_back` and clear `nav_forward`.
pub(super) fn record_in_doc_jump(&mut self, footnote: Option<String>) {
self.nav_back.push(self.current_in_doc_entry(footnote));
self.nav_forward.clear();
}
/// Pop `nav_back`, push the current state onto `nav_forward`, and load the
/// popped destination. Respects the dirty guard, as forward does.
pub(super) fn navigate_back(&mut self, doc_height: usize, doc_width: usize) {
let Some(dest) = self.nav_back.pop() else {
return;
};
if let Some(target) = self.cross_file_dirty_target(&dest) {
// Restored so Cancel is a true no-op.
self.nav_back.push(dest);
self.open_dirty_guard(target, None);
return;
}
self.navigate_to_entry(dest, doc_height, doc_width, /*forward=*/ false);
}
pub(super) fn navigate_forward(&mut self, doc_height: usize, doc_width: usize) {
let Some(dest) = self.nav_forward.pop() else {
return;
};
if let Some(target) = self.cross_file_dirty_target(&dest) {
self.nav_forward.push(dest);
self.open_dirty_guard(target, None);
return;
}
self.navigate_to_entry(dest, doc_height, doc_width, /*forward=*/ true);
}
/// The destination to guard on when restoring `dest` would leave a dirty
/// buffer for a *different* document. In-document and same-file restores
/// lose no unsaved edits, so they bypass the guard.
fn cross_file_dirty_target(&self, dest: &NavEntry) -> Option<NavPending> {
if !self.editor.dirty {
return None;
}
match &dest.dest {
NavDest::File(path) if self.file_path.as_deref() != Some(path.as_path()) => {
Some(NavPending::File(path.clone()))
}
NavDest::EmbeddedDoc(id) if self.open_doc != Some(*id) => Some(NavPending::Doc(*id)),
_ => None,
}
}
/// Shared back/forward dispatch: push the current state onto the opposite
/// stack, then load `dest` and restore its scroll / cursor / mode.
fn navigate_to_entry(
&mut self,
dest: NavEntry,
doc_height: usize,
doc_width: usize,
forward: bool,
) {
// Only a `File` naming a *different* file reloads; same-file and
// `InDocument` entries restore in place.
let reload_path = match &dest.dest {
NavDest::File(path) if self.file_path.as_deref() != Some(path.as_path()) => {
Some(path.clone())
}
_ => None,
};
// The same question for a manual page.
let reload_doc = match &dest.dest {
NavDest::EmbeddedDoc(id) if self.open_doc != Some(*id) => Some(*id),
_ => None,
};
// A restore that reloads needs a file entry so the reverse navigation
// reloads too; otherwise an in-document entry suffices and also works
// for `[No file]`.
let current = if reload_path.is_some() || reload_doc.is_some() {
self.current_origin_entry()
} else {
Some(self.current_in_doc_entry(None))
};
if let Some(path) = reload_path {
if let Err(err) = self.load_file_into_editor(path.clone()) {
tracing::warn!(target: "link", path = %path.display(), error = %err, "nav load failed");
return;
}
}
if let Some(id) = reload_doc {
self.load_doc_into_editor(id);
}
if let Some(e) = current {
if forward {
self.nav_back.push(e);
} else {
self.nav_forward.push(e);
}
}
self.editor.scroll = dest.scroll.min(
self.editor
.total_visual_rows_for_mode(doc_width)
.saturating_sub(1),
);
self.editor.cursor.offset = dest.cursor_offset.min(self.editor.buffer.len_chars());
self.editor.mode = dest.mode;
// An entry pushed before a mid-session vim toggle carries `Preview`,
// which vim has no way back out of.
super::leave_preview_under_vim(&self.config, &mut self.editor);
self.editor.update_cursor_block();
// Preview decouples scroll from the cursor, so the restored scroll is
// authoritative there; elsewhere the cursor drives.
if self.editor.mode != Mode::Preview {
self.editor.ensure_cursor_visible(doc_height, doc_width);
}
}
/// Show the `Save / Discard / Cancel` modal for a pending link-follow. The
/// deep link's `#fragment` has to be carried across the modal's lifetime, or
/// answering it drops the reader at the top of the target document.
pub(super) fn open_dirty_guard(&mut self, pending: NavPending, fragment: Option<String>) {
let display = self
.file_path
.as_deref()
.and_then(|p| p.file_name())
.map(|n| n.to_string_lossy().into_owned())
.unwrap_or_else(|| "current file".to_owned());
self.modal_stack.push(Box::new(modal::DirtyGuardModal::new(
&display, pending, fragment,
)));
}
}
#[cfg(test)]
mod tests {
use std::io::Write;
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use super::*;
use crate::app::modal::{
FiguresEnabledPromptModal, ImagesEnabledPromptModal, RemoteImagePromptModal,
};
use crate::app::test_utils::app_with_buffer;
const H: usize = 20;
const W: usize = 80;
/// Write `contents` to a temp `.md` file; the handle is returned so the
/// file outlives the navigation under test.
fn md_file(contents: &str) -> (tempfile::NamedTempFile, PathBuf) {
let mut f = tempfile::Builder::new()
.suffix(".md")
.tempfile()
.expect("temp file");
f.write_all(contents.as_bytes()).expect("write");
f.flush().expect("flush");
let path = f.path().to_path_buf();
(f, path)
}
#[test]
fn heading_anchor_jump_records_history_and_back_returns() {
// The heading sits near the bottom, so the jump moves the scroll.
let src =
"Intro paragraph.\n\n".to_string() + &"filler\n\n".repeat(30) + "## Target\n\nEnd.\n";
let mut app = app_with_buffer(&src, 0);
assert_eq!(app.editor.scroll, 0);
assert!(app.nav_back.is_empty());
app.scroll_to_heading("target", H, W);
let jumped = app.editor.scroll;
assert!(jumped > 0, "jump should move the viewport");
assert_eq!(app.nav_back.len(), 1, "jump should record one back entry");
assert!(matches!(app.nav_back[0].dest, NavDest::InDocument { .. }));
app.navigate_back(H, W);
assert_eq!(
app.editor.scroll, 0,
"back should restore the origin scroll"
);
assert!(app.nav_back.is_empty());
assert_eq!(app.nav_forward.len(), 1);
app.navigate_forward(H, W);
assert_eq!(
app.editor.scroll, jumped,
"forward should re-apply the jump"
);
}
#[test]
fn footnote_reference_follow_jumps_to_definition_and_back_returns() {
let src = "Intro[^1] text.\n\n".to_string()
+ &"filler\n\n".repeat(30)
+ "[^1]: The definition.\n";
let mut app = app_with_buffer(&src, 0);
assert_eq!(app.editor.scroll, 0);
app.follow_footnote_reference("1", H, W);
let jumped = app.editor.scroll;
assert!(jumped > 0, "follow should scroll to the definition");
assert_eq!(app.nav_back.len(), 1);
assert!(matches!(app.nav_back[0].dest, NavDest::InDocument { .. }));
app.follow_footnote_back_link("1", H, W);
assert_eq!(
app.editor.scroll, 0,
"back-link should return to the reference"
);
}
#[test]
fn footnote_back_link_falls_back_to_first_reference_when_no_origin() {
// Reached by scrolling, not by following, so there is no in-document
// origin and the back-link falls back to the first reference.
let src = "Intro[^1] text.\n\n".to_string()
+ &"filler\n\n".repeat(30)
+ "[^1]: The definition.\n";
let mut app = app_with_buffer(&src, 0);
app.editor.scroll = app.editor.total_visual_rows_for_mode(W).saturating_sub(1);
assert!(app.nav_back.is_empty());
app.follow_footnote_back_link("1", H, W);
assert_eq!(
app.editor.scroll, 0,
"fallback should jump to the first reference near the top"
);
assert_eq!(app.nav_back.len(), 1, "fallback records its own origin");
}
#[test]
fn back_link_ignores_unrelated_heading_jump_on_stack() {
// The heading jump on the stack top must not be consumed: the back-link
// falls back to the footnote's first reference instead.
let src = "Ref[^1] here.\n\n## Section\n\n".to_string()
+ &"filler\n\n".repeat(30)
+ "[^1]: The definition.\n";
let mut app = app_with_buffer(&src, 0);
app.scroll_to_heading("section", H, W);
let heading_scroll = app.editor.scroll;
assert_eq!(app.nav_back.len(), 1);
app.follow_footnote_back_link("1", H, W);
// The bug — consuming the heading entry via `navigate_back` — would pop
// to len 1 and push forward instead.
assert_eq!(
app.nav_back.len(),
2,
"heading entry retained; back-link recorded its own origin"
);
assert!(
app.nav_forward.is_empty(),
"fallback must not consume the heading entry into nav_forward"
);
let _ = heading_scroll;
}
#[test]
fn resolve_link_at_cursor_classifies_footnote_reference() {
let src = "Body[^1] more.\n\n[^1]: def.\n";
let mut app = app_with_buffer(src, 0);
let at = src.find("[^1]").unwrap() + 1;
app.editor.cursor.offset = app.editor.buffer.rope().byte_to_char(at);
assert_eq!(
app.resolve_link_at_cursor(),
Some(LinkTarget::Footnote("1".into()))
);
}
#[test]
fn in_document_back_skips_dirty_guard() {
// No file switch means no data loss, so no guard.
let src = "Top.\n\n".to_string() + &"filler\n\n".repeat(30) + "## Here\n\nEnd.\n";
let mut app = app_with_buffer(&src, 0);
app.scroll_to_heading("here", H, W);
assert_eq!(app.nav_back.len(), 1);
assert!(matches!(app.nav_back[0].dest, NavDest::InDocument { .. }));
app.editor.dirty = true;
// `App::new` may have seeded a startup modal, so compare counts.
let modals_before = app.modal_stack.len();
app.navigate_back(H, W);
assert_eq!(
app.modal_stack.len(),
modals_before,
"in-document back must not raise the dirty guard"
);
assert_eq!(app.editor.scroll, 0);
}
// ── Per-document media prompts (issue #30) ────────────────────────────
/// Issue #38: the link classified as a non-Markdown local file — its
/// "extension" was `md#section` — and went to the OS opener, which failed.
#[test]
fn a_deep_link_opens_the_file_in_editor_and_lands_on_the_section() {
let target_src =
"# Top\n\n".to_string() + &"filler\n\n".repeat(30) + "## Deep Section\n\nEnd.\n";
let (_f, path) = md_file(&target_src);
let mut app = app_with_buffer("Link here.\n", 0);
let url = format!("{}#deep-section", path.display());
app.follow_link(LinkTarget::parse(&url, None), H, W);
assert_eq!(
app.file_path.as_deref(),
Some(path.as_path()),
"the link must load in-editor, not hand off to the OS opener"
);
assert!(
app.editor.scroll > 0,
"the fragment must scroll to its heading, not stay at the top"
);
}
/// The fragment has to survive the guard's close callback, which used to
/// re-assert cursor visibility on the new document — and, a fresh editor
/// starting in `Mode::Preview` at byte 0, scrolled straight off the section.
/// Driven through `dispatch_modal_key` so the button routing is covered.
#[test]
fn a_deep_link_answered_through_the_dirty_guard_still_lands_on_the_section() {
for (button, keys) in [
("Discard", vec![KeyCode::Right, KeyCode::Enter]),
("Save", vec![KeyCode::Enter]),
] {
let target_src =
"# Top\n\n".to_string() + &"filler\n\n".repeat(30) + "## Deep Section\n\nEnd.\n";
let (_f, path) = md_file(&target_src);
let (_origin_f, origin) = md_file("Link here.\n");
// The Save arm branches on the buffer having a path; without one
// it detours through the Save-as modal.
let mut app = app_with_buffer("Link here.\n", 0);
app.load_file_into_editor(origin.clone())
.expect("load origin");
app.editor.dirty = true;
app.last_doc_height = H;
app.last_doc_width = W;
let url = format!("{}#deep-section", path.display());
app.follow_link(LinkTarget::parse(&url, None), H, W);
assert!(
app.modal_stack.contains::<modal::DirtyGuardModal>(),
"{button}: a dirty buffer must route the deep link through the guard"
);
assert_eq!(
app.file_path.as_deref(),
Some(origin.as_path()),
"{button}: the guard must not navigate before it is answered"
);
for code in keys {
app.dispatch_modal_key(KeyEvent::new(code, KeyModifiers::NONE), H, W);
}
assert!(
!app.modal_stack.contains::<modal::DirtyGuardModal>(),
"{button}: answering the guard closes it"
);
assert_eq!(
app.file_path.as_deref(),
Some(path.as_path()),
"{button}: the pending destination must load"
);
assert!(
app.editor.scroll > 0,
"{button}: the fragment must survive the guard — landed at the top instead"
);
assert_eq!(
app.heading_line_for_fragment("deep-section")
.map(|l| app.editor.parsed.visual_rows_before(l, W)),
Some(app.editor.scroll),
"{button}: the viewport must sit on the linked heading"
);
}
}
#[test]
fn a_deep_link_records_one_file_entry_so_back_returns_to_the_link() {
let target_src = "# Top\n\n".to_string() + &"filler\n\n".repeat(30) + "## Deep\n";
let (_f, path) = md_file(&target_src);
let (_origin_f, origin) = md_file("Link here.\n");
let mut app = app_with_buffer("Link here.\n", 0);
app.file_path = Some(origin.clone());
let url = format!("{}#deep", path.display());
app.follow_link(LinkTarget::parse(&url, None), H, W);
assert_eq!(
app.nav_back.len(),
1,
"the jump within the freshly-loaded document must not record a second entry"
);
app.navigate_back(H, W);
assert_eq!(app.file_path.as_deref(), Some(origin.as_path()));
}
#[test]
fn a_deep_link_whose_section_is_missing_opens_the_file_and_says_so() {
let (_f, path) = md_file("# Top\n\nProse.\n");
let mut app = app_with_buffer("Link here.\n", 0);
let url = format!("{}#no-such-section", path.display());
app.follow_link(LinkTarget::parse(&url, None), H, W);
assert_eq!(app.file_path.as_deref(), Some(path.as_path()));
assert_eq!(app.editor.scroll, 0);
assert!(
app.transient
.as_ref()
.is_some_and(|m| m.text.contains("no-such-section")),
"a fragment that resolves to nothing must be reported, not silently dropped"
);
}
/// Only the GFM slug resolves: accepting a hand-written `#Getting Started`
/// would bless a fragment every other renderer rejects, and the author would
/// ship the broken link without ever seeing it fail here.
#[test]
fn only_the_gfm_slug_resolves_a_fragment() {
let src = "Intro.\n\n".to_string() + &"filler\n\n".repeat(30) + "## Getting Started\n";
let mut app = app_with_buffer(&src, 0);
for near_miss in [
"Getting Started",
"Getting-Started",
"getting started",
"getting%20started",
] {
app.editor.scroll = 0;
app.scroll_to_heading(near_miss, H, W);
assert_eq!(
app.editor.scroll, 0,
"'{near_miss}' is not the slug and must not resolve"
);
}
app.scroll_to_heading("getting-started", H, W);
assert!(app.editor.scroll > 0, "the slug itself must resolve");
}
#[test]
fn a_startup_anchor_lands_on_its_section_once() {
let src = "Intro.\n\n".to_string() + &"filler\n\n".repeat(30) + "## Setup\n\nEnd.\n";
let mut app = app_with_buffer(&src, 0);
app.startup_anchor = Some("setup".to_owned());
app.apply_startup_anchor(H, W);
let landed = app.editor.scroll;
assert!(landed > 0, "the named section should be scrolled to");
assert!(
app.nav_back.is_empty(),
"there is no earlier position in the session to go back to"
);
assert_eq!(app.startup_anchor, None, "the jump happens once");
// A later frame must not re-apply it; the reader may have scrolled away.
app.editor.scroll = 0;
app.apply_startup_anchor(H, W);
assert_eq!(app.editor.scroll, 0);
}
#[test]
fn a_startup_anchor_naming_no_heading_says_so() {
let mut app = app_with_buffer("# Top\n\nProse.\n", 0);
app.startup_anchor = Some("nowhere".to_owned());
app.apply_startup_anchor(H, W);
assert_eq!(app.editor.scroll, 0);
assert!(app
.transient
.as_ref()
.is_some_and(|m| m.text.contains("nowhere")));
}
#[test]
fn navigating_to_a_document_with_images_queues_the_images_prompt() {
// The session starts with no images, so no prompt was queued.
let mut app = app_with_buffer("Just prose.\n", 0);
assert_eq!(app.config.images.enabled, crate::config::ImagesEnabled::Ask);
assert_eq!(app.session_images_enabled, None);
assert!(!app.modal_stack.contains::<ImagesEnabledPromptModal>());
assert!(
!app.effective_images_enabled(),
"no answer yet means no decoding"
);
let (_f, path) = md_file("\n");
app.navigate_to_file(path);
assert!(
app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"the linked document's images must raise the prompt that enables them"
);
}
#[test]
fn an_image_appearing_mid_session_queues_the_images_prompt() {
// A document opened *without* images leaves the ask gate unset; an
// image that appears afterwards — a pasted screenshot, or typed
// `` — must raise the prompt the on-load path would have,
// or `effective_images_enabled` stays false and it never decodes.
let mut app = app_with_buffer("Just prose.\n", 0);
crate::app::test_utils::close_startup_modals(&mut app);
assert_eq!(app.session_images_enabled, None);
assert!(!app.modal_stack.contains::<ImagesEnabledPromptModal>());
app.editor.buffer.insert(0, "\n\n");
app.editor.set_viewport_width(80);
app.editor.refresh_parsed();
app.dispatch_visible_image_decodes(0, 20);
assert!(
app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"an in-view image with the ask gate open must queue the prompt"
);
}
#[test]
fn the_mid_session_images_prompt_waits_for_typing_to_pause() {
// A prompt opening mid-burst would take the next keystrokes as its answers — bare `n`
// declines for the session — so it is held until typing pauses, with its due time
// parked for the run loop to wake on.
use crate::app::image_dispatch::IMAGES_PROMPT_TYPING_PAUSE;
let mut app = app_with_buffer("Just prose.\n", 0);
crate::app::test_utils::close_startup_modals(&mut app);
app.editor.buffer.insert(0, "\n\n");
app.editor.set_viewport_width(80);
app.editor.refresh_parsed();
let typed_at = std::time::Instant::now();
app.last_editor_key_at = Some(typed_at);
app.dispatch_visible_image_decodes(0, 20);
assert!(
!app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"no prompt while typing"
);
assert_eq!(
app.images_prompt_due,
Some(typed_at + IMAGES_PROMPT_TYPING_PAUSE)
);
app.last_editor_key_at = Some(typed_at - IMAGES_PROMPT_TYPING_PAUSE);
app.dispatch_visible_image_decodes(0, 20);
assert!(
app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"the prompt opens once typing has paused"
);
assert_eq!(app.images_prompt_due, None);
}
#[test]
fn the_mid_session_images_prompt_waits_for_an_open_modal_to_close() {
// Typing in a modal doesn't reset the editor's typing clock, so a prompt raised over,
// say, the command palette would take the query's `n` / `y` / Space as its answers.
let mut app = app_with_buffer("Just prose.\n", 0);
crate::app::test_utils::close_startup_modals(&mut app);
app.editor.buffer.insert(0, "\n\n");
app.editor.set_viewport_width(80);
app.editor.refresh_parsed();
app.dispatch_action(crate::config::Action::ShowCommandPalette, 20, 80);
assert_eq!(app.modal_stack.len(), 1, "the palette is open");
app.dispatch_visible_image_decodes(0, 20);
assert!(!app.modal_stack.contains::<ImagesEnabledPromptModal>());
assert_eq!(app.images_prompt_due, None, "closing the modal redraws");
app.dispatch_modal_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), 20, 80);
assert!(app.modal_stack.is_empty());
app.dispatch_visible_image_decodes(0, 20);
assert!(app.modal_stack.contains::<ImagesEnabledPromptModal>());
}
#[test]
fn an_answered_images_prompt_parks_no_wakeup() {
// Every edit would otherwise schedule a wake-up for a prompt the gate then refuses.
let mut app = app_with_buffer("\n", 0);
app.session_images_enabled = Some(true);
app.editor.set_viewport_width(80);
app.editor.refresh_parsed();
app.last_editor_key_at = Some(std::time::Instant::now());
app.dispatch_visible_image_decodes(0, 20);
assert_eq!(app.images_prompt_due, None);
}
#[test]
fn dismissing_the_images_prompt_does_not_invite_it_back() {
// The mid-session queue runs on every frame, so a dismissal that
// left the ask gate open would raise the prompt again on the very
// next one and the user could never get rid of it: Escape records
// the same session answer `No` does, which is what closes the gate.
let mut app = app_with_buffer("Just prose.\n", 0);
crate::app::test_utils::close_startup_modals(&mut app);
app.editor.buffer.insert(0, "\n\n");
app.editor.set_viewport_width(80);
app.editor.refresh_parsed();
app.dispatch_visible_image_decodes(0, 20);
assert!(app.modal_stack.contains::<ImagesEnabledPromptModal>());
app.dispatch_modal_key(KeyEvent::new(KeyCode::Esc, KeyModifiers::NONE), 20, 80);
assert!(
!app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"Escape dismisses the prompt"
);
app.dispatch_visible_image_decodes(0, 20);
assert!(
!app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"a dismissed prompt must not be re-queued by the next frame"
);
}
#[test]
fn navigating_to_a_document_with_a_diagram_queues_the_diagrams_prompt() {
let mut app = app_with_buffer("Just prose.\n", 0);
let (_f, path) = md_file("```mermaid\ngraph TD;\n```\n");
app.navigate_to_file(path);
assert!(app.modal_stack.contains::<FiguresEnabledPromptModal>());
assert!(
!app.modal_stack.contains::<ImagesEnabledPromptModal>(),
"a diagram-only document must not raise the images prompt"
);
}
#[test]
fn navigating_to_a_document_with_a_remote_image_queues_the_remote_prompt() {
let mut app = app_with_buffer("Just prose.\n", 0);
let (_f, path) = md_file("\n");
app.navigate_to_file(path);
assert!(app.modal_stack.contains::<RemoteImagePromptModal>());
// Images on top of remote, mirroring the startup push order.
assert!(app.modal_stack.contains::<ImagesEnabledPromptModal>());
}
#[test]
fn a_session_answer_is_not_re_asked_after_navigation() {
let mut app = app_with_buffer("\n", 0);
app.modal_stack.remove_first::<ImagesEnabledPromptModal>();
app.session_images_enabled = Some(true);
app.session_diagrams_enabled = Some(true);
let (_f, path) = md_file("\n\n```mermaid\ngraph TD;\n```\n");
app.navigate_to_file(path);
assert!(!app.modal_stack.contains::<ImagesEnabledPromptModal>());
assert!(!app.modal_stack.contains::<FiguresEnabledPromptModal>());
assert!(
app.effective_images_enabled(),
"the session answer carries into the new document"
);
}
#[test]
fn a_session_decline_is_not_re_asked_after_navigation() {
let mut app = app_with_buffer("\n", 0);
app.modal_stack.remove_first::<ImagesEnabledPromptModal>();
app.session_images_enabled = Some(false);
app.session_diagrams_enabled = Some(false);
app.session_remote_declined = true;
let (_f, path) = md_file("\n\n```mermaid\ngraph TD;\n```\n");
app.navigate_to_file(path);
assert!(!app.modal_stack.contains::<ImagesEnabledPromptModal>());
assert!(!app.modal_stack.contains::<FiguresEnabledPromptModal>());
assert!(!app.modal_stack.contains::<RemoteImagePromptModal>());
assert!(!app.effective_images_enabled());
assert!(
!app.editor.images_enabled,
"a declined session keeps the new document's image rows collapsed"
);
}
#[test]
fn an_indexed_terminal_is_not_prompted_by_navigation() {
// `App::new` suppresses all three prompts below truecolor, where
// `media_renderable` refuses to decode anyway; navigation owes the same
// suppression.
use crate::config::{Config, KeyBindingOverrides, State, Theme};
use crate::terminal::{Capabilities, ColorDepth};
let caps = Capabilities {
color_depth: ColorDepth::Ansi256,
..Capabilities::minimal()
};
let mut config = Config::default();
config.editor.show_welcome = false;
// With no version recorded, the post-upgrade notice would otherwise open
// over the document this test navigates.
let state = State {
last_version_seen: crate::app::update_check::INSTALLED_VERSION.to_owned(),
..State::default()
};
let mut app = App::new(
config,
state,
KeyBindingOverrides::default(),
(&Theme::default()).into(),
None,
caps,
Vec::new(),
)
.expect("build app");
assert!(!app.media_renderable());
let (_f, path) = md_file("\n\n```mermaid\ngraph TD;\n```\n");
app.navigate_to_file(path);
assert!(!app.modal_stack.contains::<ImagesEnabledPromptModal>());
assert!(!app.modal_stack.contains::<FiguresEnabledPromptModal>());
assert!(!app.modal_stack.contains::<RemoteImagePromptModal>());
}
#[test]
fn navigation_carries_the_cursor_blink_setting_to_the_new_document() {
// Drift regression: `App::new` applied `cursor_blink` and the navigation
// path didn't, so following a link resumed blinking.
let mut app = app_with_buffer("Just prose.\n", 0);
app.config.editor.cursor_blink = false;
let (_f, path) = md_file("More prose.\n");
app.navigate_to_file(path);
assert!(
!app.editor.cursor_blink.is_blinking(),
"the new document must honor the configured blink setting",
);
}
#[test]
fn reconfiguring_an_existing_editor_picks_up_every_config_field() {
// The post-`$EDITOR` config reload hands `configure_new_editor` an
// already-configured editor, so every field must be re-applied, not
// merely defaulted. The reload used to live-apply only the theme and
// keymap, so hand-editing `syntax_highlighting`, `big_h1`,
// `cursor_blink` or `row_striping` did nothing until the next launch
// while the flash still said "Configuration updated". Driving the real
// reload needs a live `$EDITOR`, so the invariant is pinned here.
let mut app = app_with_buffer(
"```rust
fn main() {}
```
",
0,
);
app.editor.set_syntax_highlighting(false);
app.editor.set_big_h1(false);
app.editor.set_row_striping(false);
assert!(app.editor.cursor_blink.is_blinking());
// Stands in for the user's hand-edit of `config.toml`.
app.config.editor.syntax_highlighting = true;
app.config.editor.big_h1 = true;
app.config.table.row_striping = true;
app.config.editor.cursor_blink = false;
let (images_on, diagrams_on) = (app.images_layout_enabled(), app.diagrams_layout_enabled());
crate::app::configure_new_editor(&mut app.editor, &app.config, images_on, diagrams_on);
assert!(app.editor.syntax_highlighting, "syntax_highlighting stale");
assert!(app.editor.big_h1, "big_h1 stale");
assert!(app.editor.row_striping, "row_striping stale");
assert!(!app.editor.cursor_blink.is_blinking(), "cursor_blink stale");
}
#[test]
fn navigation_carries_the_encoder_sender_to_the_new_document() {
// The paint half needs `ImageCache::resize_tx`, and the cache is rebuilt
// per document: attaching it only in `spawn_event_threads` left every
// later document painting placeholders over images that decoded fine.
let mut app = app_with_buffer("\n", 0);
let (tx, _rx) = std::sync::mpsc::channel();
app.editor.images.attach_resize_sender(tx.clone());
app.resize_tx = Some(tx);
assert!(app.editor.images.has_resize_sender());
let (_f, path) = md_file("\n");
app.navigate_to_file(path);
assert!(
app.editor.images.has_resize_sender(),
"a document opened mid-session must be able to encode its images",
);
}
#[test]
fn navigation_dispatches_decodes_for_the_new_documents_images() {
// An answer already given must also reach the new document's decode
// dispatch, which reads `session_*` off the App and the URLs off the
// freshly built `EditorState`. A local path keeps the worker offline.
let mut app = app_with_buffer("Just prose.\n", 0);
app.session_images_enabled = Some(true);
let (tx, _rx) = std::sync::mpsc::channel();
app.app_tx = Some(tx);
let (_f, path) = md_file("\n");
app.navigate_to_file(path);
app.editor.refresh_parsed();
app.dispatch_visible_image_decodes(0, 20);
let url = app.editor.parsed.image_blocks[0].url.clone();
assert!(
app.editor.images.status(&url).is_some(),
"the new document's image must be requested, not left untracked",
);
}
#[test]
fn images_below_the_dispatch_window_are_not_requested_yet() {
// Dispatch is viewport-limited. Pinned because from the outside this
// looks identical to a broken prompt: open a long document, see no
// image, conclude nothing works.
let mut app = app_with_buffer("Just prose.\n", 0);
app.session_images_enabled = Some(true);
let (tx, _rx) = std::sync::mpsc::channel();
app.app_tx = Some(tx);
let filler = "text\n\n".repeat(200);
let (_f, path) = md_file(&format!("{filler}\n"));
app.navigate_to_file(path);
app.editor.refresh_parsed();
let url = app.editor.parsed.image_blocks[0].url.clone();
app.dispatch_visible_image_decodes(0, 20);
assert!(
app.editor.images.status(&url).is_none(),
"an image 400 rows down must not be fetched from the top of the document",
);
let rows = app
.editor
.parsed
.source_map
.rendered_lines_for_block(app.editor.parsed.image_blocks[0].block_idx);
app.dispatch_visible_image_decodes(rows.start.saturating_sub(5), 20);
assert!(
app.editor.images.status(&url).is_some(),
"scrolling to it must request it",
);
}
#[test]
fn a_pending_prompt_is_not_stacked_twice_by_navigation() {
// Navigating before answering the startup prompt must not queue a
// second copy.
let mut app = app_with_buffer("\n", 0);
app.on_document_contents_swapped();
let (_f, path) = md_file("\n");
app.navigate_to_file(path);
assert_eq!(
app.modal_stack.count::<ImagesEnabledPromptModal>(),
1,
"one pending images prompt, not one per document"
);
}
// ── Remembered cursor ─────────────────────────────────────────────────
/// Build an app the way `main` does: a real file on disk, and the state `state.toml` holds.
fn app_on_file(
path: PathBuf,
config: crate::config::Config,
state: crate::config::State,
) -> App {
use crate::config::{KeyBindingOverrides, Theme};
use crate::terminal::{Capabilities, ColorDepth};
let caps = Capabilities {
color_depth: ColorDepth::TrueColor,
..Capabilities::default()
};
App::new(
config,
state,
KeyBindingOverrides::default(),
(&Theme::default()).into(),
Some(path),
caps,
Vec::new(),
)
.expect("build app")
}
/// Blank-line-separated paragraphs: one rendered line each, so rendered row == paragraph index
/// and the centering arithmetic in these tests needs no wrap model.
fn paragraphs(count: usize) -> String {
(0..count).map(|i| format!("para {i}\n\n")).collect()
}
#[test]
fn a_remembered_cursor_lands_at_the_vertical_middle_on_the_first_frame() {
let src = paragraphs(40);
let (_f, path) = md_file(&src);
let offset = src.find("para 20").expect("paragraph 20");
let mut state = crate::config::State::default();
state.remember_cursor(cursor_key(&path), offset);
let mut app = app_on_file(path, crate::config::Config::default(), state);
assert_eq!(
app.pending_cursor_restore.map(|p| p.offset),
Some(offset),
"opening the file parks the position it was left at"
);
app.apply_pending_cursor_restore(H, W);
assert_eq!(app.editor.cursor.offset, offset);
assert_eq!(
app.editor.cursor_screen_row(W),
H / 2,
"the remembered position is centered, not merely visible"
);
assert!(app.pending_cursor_restore.is_none(), "consumed once");
// A later frame must leave it alone: the reader owns the scroll from here.
let scroll = app.editor.scroll;
app.apply_pending_cursor_restore(H, W);
assert_eq!(app.editor.scroll, scroll);
}
#[test]
fn a_remembered_cursor_near_the_top_clamps_to_the_top() {
let src = paragraphs(40);
let (_f, path) = md_file(&src);
let offset = src.find("para 2").expect("paragraph 2");
let mut state = crate::config::State::default();
state.remember_cursor(cursor_key(&path), offset);
let mut app = app_on_file(path, crate::config::Config::default(), state);
app.apply_pending_cursor_restore(H, W);
assert_eq!(
app.editor.scroll, 0,
"a document cannot scroll above its own top"
);
assert_eq!(app.editor.cursor.offset, offset);
}
#[test]
fn the_restore_re_centres_while_a_decode_is_still_landing() {
// An image block reserves `image_max_height` rows until its decode lands and only then
// takes the image's real height, so a centre computed on the first frame is computed for a
// row space the reader never ends up in. Measured in the wild: a math-heavy document lost
// 100 of its 178 rows over the first five frames, and the one-shot centre left the viewport
// past the end of the settled document, painting an empty screen.
let src = format!(
"{}\n\n{}",
"para\n\n".repeat(20),
"para\n\n".repeat(20)
);
let (_f, path) = md_file(&src);
let offset = src.find("![a]").expect("image paragraph");
let mut state = crate::config::State::default();
state.remember_cursor(cursor_key(&path), offset);
let mut app = app_on_file(path, crate::config::Config::default(), state);
// No decode worker runs in a unit test, so ask the cache for the decode by hand — what the
// settle loop keys off is `DecodeStatus::Pending`.
let urls: Vec<String> = app
.editor
.parsed
.image_blocks
.iter()
.map(|b| b.url.clone())
.collect();
assert_eq!(urls.len(), 1, "the image paragraph promoted to a block");
for url in &urls {
app.editor.images.request(url);
}
app.apply_pending_cursor_restore(H, W);
let reserved = app.editor.total_visual_rows_for_mode(W);
assert!(
app.pending_cursor_restore.is_some(),
"a decode in flight keeps the restore armed, so it can re-centre on the settled space"
);
// The decode lands — as a failure, which collapses the block to one row — and the document
// gets much shorter under the reader.
app.editor.images.set_failed(&urls[0], "test".to_owned());
app.editor.refresh_parsed();
app.apply_pending_cursor_restore(H, W);
let settled = app.editor.total_visual_rows_for_mode(W);
assert!(settled < reserved, "the collapse shortened the document");
assert!(
app.editor.scroll < settled,
"the re-centred scroll stays inside the document ({settled} rows, was {reserved})"
);
assert!(
app.pending_cursor_restore.is_none(),
"nothing is pending, so the restore lets go"
);
assert_eq!(app.editor.cursor.offset, offset);
}
#[test]
fn remember_cursor_off_neither_parks_nor_records() {
let src = paragraphs(40);
let (_f, path) = md_file(&src);
let key = cursor_key(&path);
let mut config = crate::config::Config::default();
config.editor.remember_cursor = false;
let mut state = crate::config::State::default();
state.remember_cursor(key.clone(), 30);
let mut app = app_on_file(path, config, state);
assert_eq!(
app.pending_cursor_restore.map(|p| p.offset),
None,
"nothing is restored"
);
// ...and the recording half writes nothing either: off is a pause, not a purge, so the
// entry already on disk is left exactly as it was rather than following the cursor.
app.editor.cursor.offset = 999;
app.record_cursor_position();
assert_eq!(app.state.cursor_for(&key), Some(30));
assert_eq!(app.state.cursors.len(), 1);
}
#[test]
fn leaving_a_file_records_its_cursor_once() {
// The switch writes to `state.toml`; isolation keeps that off the real data dir.
let _iso = crate::test_env::config_isolation();
let src = paragraphs(40);
let (_a, first) = md_file(&src);
let (_b, second) = md_file(&src);
let offset = src.find("para 30").expect("paragraph 30");
let mut app = app_on_file(
first.clone(),
crate::config::Config::default(),
crate::config::State::default(),
);
app.editor.cursor.offset = offset;
app.load_file_into_editor(second).expect("load second file");
assert_eq!(app.state.cursor_for(&cursor_key(&first)), Some(offset));
assert_eq!(app.state.cursors.len(), 1, "one entry for the file left");
// Leaving it again at the same place must not rewrite the machine file, which shows up as
// nothing changing — a second file would have joined the list otherwise.
app.record_cursor_position();
assert_eq!(app.state.cursors.len(), 1);
}
#[test]
fn opening_an_embedded_page_records_the_outgoing_file() {
// Switching to a manual page clears `file_path`, so it is the last moment the file's
// position is knowable — like a file switch, it must be recorded before the swap.
let _iso = crate::test_env::config_isolation();
let src = paragraphs(40);
let (_f, path) = md_file(&src);
let offset = src.find("para 30").expect("paragraph 30");
let mut app = app_on_file(
path.clone(),
crate::config::Config::default(),
crate::config::State::default(),
);
app.editor.cursor.offset = offset;
app.load_doc_into_editor(crate::docs::DocId::Index);
assert_eq!(app.state.cursor_for(&cursor_key(&path)), Some(offset));
}
#[test]
fn an_untouched_or_pathless_buffer_records_nothing() {
let src = paragraphs(40);
let (_f, path) = md_file(&src);
// Cursor at the top: the default the user already gets, so it earns no entry.
let mut app = app_on_file(
path,
crate::config::Config::default(),
crate::config::State::default(),
);
app.record_cursor_position();
assert!(app.state.cursors.is_empty());
// No file to reopen: a `--diff` review, or an embedded manual page.
let mut pathless = app_with_buffer(&src, 0);
pathless.editor.cursor.offset = 30;
pathless.record_cursor_position();
assert!(pathless.state.cursors.is_empty());
}
#[test]
fn a_startup_anchor_outranks_a_remembered_cursor() {
// A command-line `#section` is explicit intent and must win, on every settle frame — not
// just frame 0. The restore runs before the anchor each frame, so it drops itself when an
// anchor is pending rather than re-centring it away once the anchor has consumed itself.
let src = format!("{}## setup\n\n{}", "para\n\n".repeat(5), paragraphs(30));
let (_f, path) = md_file(&src);
let offset = src.rfind("para").expect("a paragraph near the end");
let mut state = crate::config::State::default();
state.remember_cursor(cursor_key(&path), offset);
let mut app = app_on_file(path, crate::config::Config::default(), state);
app.startup_anchor = Some("setup".to_owned());
// The event-loop order: restore first, then anchor.
app.apply_pending_cursor_restore(H, W);
assert!(
app.pending_cursor_restore.is_none(),
"a pending anchor drops the restore outright"
);
assert_eq!(
app.editor.scroll, 0,
"the restore left the viewport for the anchor"
);
app.apply_startup_anchor(H, W);
assert_eq!(
app.editor.scroll,
app.heading_line_for_fragment("setup")
.expect("setup heading"),
"the anchor lands on its section, unopposed on this and every later frame"
);
}
#[test]
fn an_offset_past_end_of_file_opens_at_the_top() {
// The file was rewritten shorter since the cursor was left, so the offset can no longer
// name a place: open at the top rather than clamping to a spot the reader never chose.
let src = paragraphs(3);
let (_f, path) = md_file(&src);
let mut state = crate::config::State::default();
state.remember_cursor(cursor_key(&path), 100_000);
let mut app = app_on_file(path, crate::config::Config::default(), state);
app.apply_pending_cursor_restore(H, W);
assert_eq!(app.editor.scroll, 0, "opened at the top");
assert_eq!(
app.editor.cursor.offset, 0,
"the stale offset was not applied"
);
assert!(
app.pending_cursor_restore.is_none(),
"and the restore let go"
);
}
#[test]
fn moving_to_the_top_updates_an_existing_entry_but_creates_none() {
// `record_cursor_position` writes to `state.toml`; isolation keeps that off the data dir.
let _iso = crate::test_env::config_isolation();
let src = paragraphs(40);
let (_f, path) = md_file(&src);
let key = cursor_key(&path);
// A file with an entry, left at the top, resumes at the top: offset 0 updates the entry.
let mut state = crate::config::State::default();
state.remember_cursor(key.clone(), 30);
let mut app = app_on_file(path.clone(), crate::config::Config::default(), state);
app.editor.cursor.offset = 0;
app.record_cursor_position();
assert_eq!(
app.state.cursor_for(&key),
Some(0),
"the entry followed to the top"
);
// A file with no entry, left at the top, earns none: an offset-0 restore is the same as no
// restore, so a fresh entry would only cost a cap slot.
let mut fresh = app_on_file(
path,
crate::config::Config::default(),
crate::config::State::default(),
);
fresh.record_cursor_position();
assert!(fresh.state.cursors.is_empty());
}
}