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
|
//! The document model and the file format. Pure Zig, no AppKit: `zig build test` covers it.
const std = @import("std");
const ghost_io = @import("ghost_io.zig");
const markdown = @import("markdown.zig");
const mem = std.mem;
const Allocator = mem.Allocator;
pub const Scope = enum { word, sentence, paragraph };
/// The other ways to say one thing. `variants[active]` mirrors the text showing on the page;
/// there is always at least one variant.
pub const Group = struct {
scope: Scope,
active: usize = 0,
variants: std.ArrayList([]u8) = .empty,
/// Variants deleted this session, so that undoing a delete can put one back.
removed: std.ArrayList([]u8) = .empty,
/// What the AI suggested, by its text. A variant is the AI's while it still reads as
/// suggested; edited, it is the writer's.
ai: std.ArrayList([]u8) = .empty,
pub fn init(gpa: Allocator, scope: Scope, variants: []const []const u8, active: usize) !Group {
var g: Group = .{ .scope = scope, .active = active };
for (variants) |v| try g.variants.append(gpa, try gpa.dupe(u8, v));
return g;
}
pub fn deinit(g: *Group, gpa: Allocator) void {
for (g.variants.items) |v| gpa.free(v);
for (g.removed.items) |v| gpa.free(v);
for (g.ai.items) |v| gpa.free(v);
g.variants.deinit(gpa);
g.removed.deinit(gpa);
g.ai.deinit(gpa);
}
pub fn isAI(g: *const Group, text: []const u8) bool {
return indexOf(g.ai.items, text) != null;
}
pub fn markAI(g: *Group, gpa: Allocator, text: []const u8) !void {
if (g.isAI(text)) return;
try g.ai.ensureUnusedCapacity(gpa, 1);
g.ai.appendAssumeCapacity(try gpa.dupe(u8, text));
}
pub fn shown(g: *const Group) []const u8 {
return g.variants.items[g.active];
}
/// Bring the model in line with what the page shows. Typing rewrites the active variant.
/// Undo and redo can instead land on another variant, or on one that was deleted.
pub fn sync(g: *Group, gpa: Allocator, on_page: []const u8, undoing: bool) !void {
if (mem.eql(u8, g.shown(), on_page)) return;
if (undoing) {
for (g.variants.items, 0..) |v, i| if (mem.eql(u8, v, on_page)) {
g.active = i;
return;
};
for (g.removed.items, 0..) |v, i| if (mem.eql(u8, v, on_page)) {
try g.variants.insert(gpa, g.active, v);
_ = g.removed.orderedRemove(i);
return;
};
}
const copy = try gpa.dupe(u8, on_page);
gpa.free(g.variants.items[g.active]);
g.variants.items[g.active] = copy;
}
/// The alternatives panel shows a group as text, one variant to a line, and this takes
/// that text back as the variants. Blank lines are rows nothing has been typed in yet.
/// `on` is the variant the panel's caret is on, counting only the lines that hold one,
/// and it shows. From a blank line, what showed before still shows, or else `fallback`.
/// False, and nothing changes, if no line holds anything.
pub fn setRows(g: *Group, gpa: Allocator, text: []const u8, on: ?usize, fallback: []const u8) !bool {
var rows: std.ArrayList([]u8) = .empty;
errdefer {
for (rows.items) |v| gpa.free(v);
rows.deinit(gpa);
}
var lines = mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
if (blank(line)) continue;
try rows.ensureUnusedCapacity(gpa, 1);
rows.appendAssumeCapacity(try gpa.dupe(u8, line));
}
if (rows.items.len == 0) return false;
const last = rows.items.len - 1;
const active = if (on) |i| @min(i, last) else indexOf(rows.items, g.shown()) orelse indexOf(rows.items, fallback) orelse @min(g.active, last);
for (g.variants.items) |v| gpa.free(v);
g.variants.deinit(gpa);
g.variants = rows;
g.active = active;
return true;
}
/// Whether the panel's text already says what the group holds.
pub fn sameRows(g: *const Group, text: []const u8) bool {
var n: usize = 0;
var lines = mem.splitScalar(u8, text, '\n');
while (lines.next()) |line| {
if (blank(line)) continue;
if (n == g.variants.items.len or !mem.eql(u8, line, g.variants.items[n])) return false;
n += 1;
}
return n == g.variants.items.len;
}
/// Move to a neighbouring variant, wrapping at the ends.
pub fn step(g: *Group, delta: isize) void {
const n: isize = @intCast(g.variants.items.len);
g.active = @intCast(@mod(@as(isize, @intCast(g.active)) + delta, n));
}
/// Delete the showing variant; the next one shows. Needs two or more.
pub fn remove(g: *Group, gpa: Allocator) !void {
std.debug.assert(g.variants.items.len > 1);
try g.removed.ensureUnusedCapacity(gpa, 1);
g.removed.appendAssumeCapacity(g.variants.orderedRemove(g.active));
if (g.active == g.variants.items.len) g.active = 0;
}
};
fn indexOf(list: []const []const u8, text: []const u8) ?usize {
for (list, 0..) |v, i| if (mem.eql(u8, v, text)) return i;
return null;
}
/// A row of the alternatives panel that holds no variant: nothing is typed in it, or it
/// is the "??" that asks the AI for some, or the "?" on the way there.
pub fn blank(line: []const u8) bool {
const typed = mem.trim(u8, line, " \t\r");
return typed.len == 0 or mem.eql(u8, typed, "?") or asks(line);
}
pub fn asks(line: []const u8) bool {
return mem.eql(u8, mem.trim(u8, line, " \t\r"), "??");
}
/// One line of the AI's answer as an alternative: without the numbering, bullets or
/// quotes a model may add though asked not to. Null if nothing is left.
pub fn suggestion(line: []const u8) ?[]const u8 {
var s = mem.trim(u8, line, " \t\r");
var digits: usize = 0;
while (digits < s.len and std.ascii.isDigit(s[digits])) digits += 1;
if (digits > 0 and digits + 1 < s.len and (s[digits] == '.' or s[digits] == ')') and s[digits + 1] == ' ') s = s[digits + 2 ..];
for ([_][]const u8{ "- ", "* ", "• " }) |bullet| {
if (mem.startsWith(u8, s, bullet)) s = s[bullet.len..];
}
for ([_][2][]const u8{ .{ "\"", "\"" }, .{ "“", "”" } }) |q| {
if (s.len <= q[0].len + q[1].len or !mem.startsWith(u8, s, q[0]) or !mem.endsWith(u8, s, q[1])) continue;
const inner = s[q[0].len .. s.len - q[1].len];
// One quoted answer, not a sentence that happens to open and close on quotes.
if (mem.find(u8, inner, q[0]) == null and mem.find(u8, inner, q[1]) == null) s = inner;
}
s = mem.trim(u8, s, " \t");
return if (blank(s)) null else s;
}
// --- The file -------------------------------------------------------------------------------
//
// v3 puts optional Overflow and write_away comments before the visible Markdown. One LF
// separates the comments when both are present; two LFs separate the last comment from
// the exact visible bytes. YAML frontmatter is those bytes' one exception: it stays on the
// file's first line and the comments follow it. Legacy comments were trailers. Offsets
// always address the full editor body, so ghosts must be restored before the alternatives
// are reanchored.
//
// The file may have been edited elsewhere. A ghost's text is not among the visible bytes, so
// it is found by the text that was on either side of it: see `Near`. One with no clear
// place goes to Overflow and is a ghost no more. v2 had only the offsets, and a digest of the
// visible bytes to say whether they still held. A group's showing
// version is there to be found, but may be there twice, so its surroundings tell it apart in
// the same way. One with no clear place is dropped.
const overflow_mark = "<!-- overflow -->"; // legacy
const overflow_open = "<!-- overflow\n(";
const overflow_close = ")-->";
const meta_open = "<!-- write_away ";
const meta_close = " -->";
const framing = "\n\n";
const Sha256 = std.crypto.hash.sha2.Sha256;
pub const GroupRec = struct { scope: Scope = .word, at: usize, active: usize = 0, variants: []const []const u8, ai: ?[]const []const u8 = null };
pub const GhostRec = struct { at: usize, text: []const u8 };
const around = 32; // how many bytes of the text on either side of a ghost or a group are kept with it
const enough = 12; // and the fewest, blanks aside, that can place a ghost without the other side's
/// What is around something, to find it by when the file has been edited elsewhere. If some of
/// that was in the text twice, an edit to the right copy would leave the wrong one the only
/// match. So with it goes the least of each side that made this the only one, or null if all
/// of it did not, and whether the two together did.
const Near = struct {
before: []const u8 = "",
after: []const u8 = "",
alone: [2]?usize = .{ null, null },
together: bool = false,
/// Around the `len` bytes at `at`. A ghost's text is not in `bytes`, so it has none.
fn of(bytes: []const u8, at: usize, len: usize) Near {
const stop = at + len;
var lo = at -| around;
while (lo < at and bytes[lo] & 0xc0 == 0x80) lo += 1;
var hi = @min(bytes.len, stop + around);
while (hi > stop and hi < bytes.len and bytes[hi] & 0xc0 == 0x80) hi -= 1;
var near: Near = .{ .before = bytes[lo..at], .after = bytes[stop..hi] };
const whole = bytes[lo..hi];
near.together = whole.len != 0 and only(bytes, whole) != null;
for (&near.alone, [_]usize{ near.before.len, near.after.len }, 0..) |*least, most, side| {
least.* = for (0..most + 1) |n| {
const part = near.piece(whole, side, n);
if (len == 0 and mem.trim(u8, part, " \t\r\n").len < enough) continue;
if (only(bytes, part) != null) break n;
} else null;
}
return near;
}
fn from(saved: anytype) Near {
return .{ .before = saved.before, .after = saved.after, .alone = saved.alone, .together = saved.together };
}
/// Saved before this was.
fn unknown(near: Near) bool {
return near.before.len + near.after.len == 0 and !near.together;
}
/// Of `whole`, which is everything around with what it is around in the middle: the middle,
/// and the `n` bytes nearest it on one side.
fn piece(near: Near, whole: []const u8, side: usize, n: usize) []const u8 {
const stop = whole.len - near.after.len;
return if (side == 0) whole[near.before.len - n .. stop] else whole[near.before.len .. stop + n];
}
/// Where `text` (a ghost's is "") belongs in `bytes`: where it was, if both sides are still
/// there, or else the one place that has both. Failing that, where one side leads.
fn find(near: Near, arena: Allocator, bytes: []const u8, was: ?usize, text: []const u8) !?usize {
const whole = try mem.concat(arena, u8, &.{ near.before, text, near.after });
if (whole.len == 0) return if (bytes.len == 0) 0 else null;
if (was) |at| if (at >= near.before.len and at <= bytes.len and mem.startsWith(u8, bytes[at - near.before.len ..], whole)) return at;
if (near.together) if (only(bytes, whole)) |at| return at + near.before.len;
// As much of a side as is still somewhere, down to what was the only one.
var spots: [2]?usize = .{ null, null };
var found: [2]usize = .{ 0, 0 };
for (near.alone, [_]usize{ near.before.len, near.after.len }, 0..) |alone, most, side| {
const least = alone orelse continue;
if (least == 0 and text.len == 0) continue;
for (0..(most + 1) -| least) |cut| {
const part = near.piece(whole, side, most - cut);
if (mem.find(u8, bytes, part) == null) continue;
found[side] = most - cut;
if (only(bytes, part)) |at| spots[side] = if (side == 0) at + found[0] else at;
break;
}
}
const left = spots[0] orelse return spots[1];
const right = spots[1] orelse return left;
if (left == right) return left;
if (text.len == 0) {
// New text may have come between the two, but not if they have changed order.
return if (left > right) null else if (found[1] > found[0]) right else left;
}
return if (found[0] == found[1]) null else if (found[1] > found[0]) right else left;
}
};
const SavedGhost = struct { at: usize, text: []const u8, before: []const u8 = "", after: []const u8 = "", alone: [2]?usize = .{ null, null }, together: bool = false };
const SavedGroup = struct {
scope: Scope = .word,
at: usize,
active: usize = 0,
variants: []const []const u8,
ai: ?[]const []const u8 = null,
before: []const u8 = "",
after: []const u8 = "",
alone: [2]?usize = .{ null, null },
together: bool = false,
};
const Meta = struct {
v: u32 = 1,
groups: []const SavedGroup = &.{},
ghosts: []const SavedGhost = &.{},
visible_sha256: ?[Sha256.digest_length * 2]u8 = null,
};
pub const File = struct {
body: []const u8 = "",
overflow: []const u8 = "",
groups: []const GroupRec = &.{},
ghosts: []const GhostRec = &.{},
displaced: bool = false, // a ghost had no clear place, and is in Overflow: the file does not say so yet
};
pub fn serialize(gpa: Allocator, f: File) ![]u8 {
const has_meta = f.groups.len != 0 or f.ghosts.len != 0;
if (!has_meta and f.overflow.len == 0) return gpa.dupe(u8, f.body);
for (f.groups) |g| if (!validGroup(g)) return error.InvalidGroup;
const visible = if (f.ghosts.len != 0) try ghost_io.visible(gpa, f.body, f.ghosts) else f.body;
defer if (f.ghosts.len != 0) gpa.free(visible);
// Frontmatter cut off by the end of the file has no line break to put a comment after.
var front = frontmatter(visible);
if (front != 0 and visible[front - 1] != '\n') front = 0;
var out: std.ArrayList(u8) = .empty;
errdefer out.deinit(gpa);
try out.appendSlice(gpa, visible[0..front]);
if (f.overflow.len > 0) {
try out.appendSlice(gpa, overflow_open);
// Escape ampersands first conceptually: each input byte is emitted only once.
for (f.overflow) |c| switch (c) {
'&' => try out.appendSlice(gpa, "&"),
'-' => try out.appendSlice(gpa, "-"),
else => try out.append(gpa, c),
};
try out.appendSlice(gpa, overflow_close);
if (has_meta) try out.append(gpa, '\n');
}
if (has_meta) {
const ghosts = try gpa.alloc(SavedGhost, f.ghosts.len);
defer gpa.free(ghosts);
var removed: usize = 0;
for (f.ghosts, ghosts) |g, *saved| {
const near: Near = .of(visible, g.at - removed, 0);
removed += g.text.len;
saved.* = .{ .at = g.at, .text = g.text, .before = near.before, .after = near.after, .alone = near.alone, .together = near.together };
}
// A group's surroundings are the whole body's: a ghost it is in or beside is found first.
const groups = try gpa.alloc(SavedGroup, f.groups.len);
defer gpa.free(groups);
for (f.groups, groups) |g, *saved| {
const text = g.variants[g.active];
const there = g.at <= f.body.len and mem.startsWith(u8, f.body[g.at..], text);
const near: Near = if (there) .of(f.body, g.at, text.len) else .{};
saved.* = .{ .scope = g.scope, .at = g.at, .active = g.active, .variants = g.variants, .ai = g.ai, .before = near.before, .after = near.after, .alone = near.alone, .together = near.together };
}
const json = try std.json.Stringify.valueAlloc(gpa, Meta{
.v = 3,
.groups = groups,
.ghosts = ghosts,
}, .{ .emit_null_optional_fields = false });
defer gpa.free(json);
try out.appendSlice(gpa, meta_open);
for (json) |c| switch (c) {
'>' => try out.appendSlice(gpa, "\\u003e"),
'-' => try out.appendSlice(gpa, "\\u002d"),
else => try out.append(gpa, c),
};
try out.appendSlice(gpa, meta_close);
}
try out.appendSlice(gpa, framing);
try out.appendSlice(gpa, visible[front..]);
return out.toOwnedSlice(gpa);
}
/// The length of the YAML frontmatter `bytes` opens with, through the line that closes it,
/// or 0. Without that line there is none: a first line of "---" is then only a rule.
pub fn frontmatter(bytes: []const u8) usize {
var at: usize = 0;
while (at < bytes.len) {
const stop = if (mem.findScalarPos(u8, bytes, at, '\n')) |nl| nl + 1 else bytes.len;
const delimiter = markdown.frontDelimiter(u8, bytes[at..stop], at == 0);
if (at != 0 and delimiter) return stop;
if (at == 0 and !delimiter) return 0;
at = stop;
}
return 0;
}
/// `body` with blanks for its comments: every other byte, and every line, where it was.
pub fn withoutComments(gpa: Allocator, body: []const u8) ![]u8 {
const prose = try gpa.dupe(u8, body);
var it: markdown.Comments(u8) = .{ .text = body, .front = frontmatter(body) != 0 };
while (it.next()) |c| for (prose[c.lo..c.hi]) |*b| {
if (b.* != '\n' and b.* != '\r') b.* = ' ';
};
return prose;
}
fn digest(bytes: []const u8) [Sha256.digest_length * 2]u8 {
var hash: [Sha256.digest_length]u8 = undefined;
Sha256.hash(bytes, &hash, .{});
return std.fmt.bytesToHex(hash, .lower);
}
/// Everything returned lives in `arena` or in `bytes`. If metadata is unsafe to
/// interpret, keep the entire source in the editor, including the recovery metadata.
pub fn parse(arena: Allocator, bytes: []const u8) !File {
const unchanged: File = .{ .body = bytes };
// The comments lead the file, or follow the frontmatter that does.
var rest = bytes[frontmatter(bytes)..];
if (!mem.startsWith(u8, rest, overflow_open) and !mem.startsWith(u8, rest, meta_open)) rest = bytes;
const head = bytes[0 .. bytes.len - rest.len];
var overflow: ?[]const u8 = null;
if (mem.startsWith(u8, rest, overflow_open)) {
const block = splitComment(rest, overflow_open, overflow_close) orelse return unchanged;
if (mem.startsWith(u8, block.rest, framing)) return .{
.body = try mem.concat(arena, u8, &.{ head, block.rest[framing.len..] }),
.overflow = try decodeOverflow(arena, block.payload),
};
if (!mem.startsWith(u8, block.rest, "\n" ++ meta_open)) return parseLegacy(arena, bytes);
overflow = block.payload;
rest = block.rest[1..];
}
if (!mem.startsWith(u8, rest, meta_open)) return parseLegacy(arena, bytes);
const block = splitComment(rest, meta_open, meta_close) orelse return unchanged;
const meta = (try readMeta(arena, block.payload, false)) orelse return unchanged;
if (meta.v == 1 and overflow == null) return parseLegacy(arena, bytes);
if ((meta.v != 2 and meta.v != 3) or !mem.startsWith(u8, block.rest, framing)) return unchanged;
if ((meta.v == 2 and meta.ghosts.len != 0) != (meta.visible_sha256 != null)) return unchanged;
const visible = try mem.concat(arena, u8, &.{ head, block.rest[framing.len..] });
const moves = try arena.alloc(Move, meta.ghosts.len);
const ghosts = try placeGhosts(arena, visible, meta, moves);
const body = ghost_io.restore(arena, visible, ghosts) catch |err| switch (err) {
error.OutOfMemory => return err,
else => return unchanged,
};
var stowed: std.ArrayList(u8) = .empty;
if (overflow) |encoded| try stowed.appendSlice(arena, try decodeOverflow(arena, encoded));
for (moves) |m| if (m.to == null) try stow(arena, &stowed, m.was.text);
const groups = (try placeGroups(arena, body, meta.groups, moves)) orelse return unchanged;
return .{
.body = body,
.groups = groups,
.ghosts = ghosts,
.displaced = ghosts.len != moves.len,
.overflow = stowed.items,
};
}
/// Where a ghost was in the body, and where it is now, if it has a place there.
const Move = struct { was: GhostRec, to: ?usize = null };
/// The ghosts that have a place, as `ghost_io.restore` wants them. Fills in `moves`.
fn placeGhosts(arena: Allocator, visible: []const u8, meta: Meta, moves: []Move) ![]const GhostRec {
const trusted = if (meta.visible_sha256) |sum| mem.eql(u8, &sum, &digest(visible)) else false;
const Spot = struct {
at: usize, // among the visible bytes
move: *Move,
fn lessThan(_: void, a: @This(), b: @This()) bool {
return a.at < b.at;
}
};
var spots: std.ArrayList(Spot) = .empty;
var removed: usize = 0;
for (meta.ghosts, moves) |g, *m| {
m.* = .{ .was = .{ .at = g.at, .text = g.text } };
const was = if (g.at >= removed) g.at - removed else null;
removed +|= g.text.len;
const at = (if (trusted) was else try Near.from(g).find(arena, visible, was, "")) orelse continue;
const inside = at < visible.len and visible[at] & 0xc0 == 0x80; // a character
if (g.text.len == 0 or at > visible.len or inside) continue;
try spots.append(arena, .{ .at = at, .move = m });
}
mem.sort(Spot, spots.items, {}, Spot.lessThan); // stable: ghosts side by side stay in order
const ghosts = try arena.alloc(GhostRec, spots.items.len);
removed = 0;
for (spots.items, ghosts) |spot, *g| {
g.* = .{ .at = spot.at + removed, .text = spot.move.was.text };
spot.move.to = g.at;
removed += g.text.len;
}
return ghosts;
}
/// Where `text` is, if it is in one place.
fn only(bytes: []const u8, text: []const u8) ?usize {
if (text.len == 0) return null;
const first = mem.find(u8, bytes, text) orelse return null;
return if (mem.find(u8, bytes[first + 1 ..], text) == null) first else null;
}
fn stow(arena: Allocator, overflow: *std.ArrayList(u8), text: []const u8) !void {
const entry = mem.trim(u8, text, "\r\n");
if (blank(entry)) return;
try overflow.appendSlice(arena, overflowGap(overflow.items));
try overflow.appendSlice(arena, entry);
}
/// What goes between what Overflow has and the next thing put in it.
pub fn overflowGap(have: []const u8) []const u8 {
if (have.len == 0 or mem.endsWith(u8, have, "\n\n")) return "";
return if (have[have.len - 1] == '\n') "\n" else "\n\n";
}
const Comment = struct { payload: []const u8, rest: []const u8 };
// Only unescaped comment delimiters may frame a block, never interrupt its payload.
fn splitComment(bytes: []const u8, open: []const u8, close: []const u8) ?Comment {
const tail = bytes[open.len..];
const end = mem.find(u8, tail, close) orelse return null;
const payload = tail[0..end];
if (mem.find(u8, payload, "--") != null) return null;
return .{ .payload = payload, .rest = tail[end + close.len ..] };
}
fn readMeta(arena: Allocator, json: []const u8, legacy: bool) !?Meta {
return std.json.parseFromSliceLeaky(Meta, arena, json, .{ .ignore_unknown_fields = legacy }) catch |err| switch (err) {
error.OutOfMemory => return err,
else => return null,
};
}
fn decodeOverflow(arena: Allocator, encoded: []const u8) ![]const u8 {
var decoded: std.ArrayList(u8) = .empty;
var i: usize = 0;
while (i < encoded.len) {
if (mem.startsWith(u8, encoded[i..], "&")) {
try decoded.append(arena, '&');
i += 5;
} else if (mem.startsWith(u8, encoded[i..], "-")) {
try decoded.append(arena, '-');
i += 5;
} else {
try decoded.append(arena, encoded[i]);
i += 1;
}
}
return decoded.items;
}
// Legacy markers are column-zero lines, but those lines can also be fenced Markdown.
fn lineMarker(bytes: []const u8, comptime marker: []const u8, comptime last: bool) ?usize {
var rest = bytes;
var fence: []const u8 = "";
var found: ?usize = null;
while (rest.len != 0) {
if (fence.len == 0) {
if (mem.startsWith(u8, rest, marker)) {
found = bytes.len - rest.len;
if (!last) return found;
}
// A wrapped Overflow trailer can contain its own unfinished code examples.
if (mem.startsWith(u8, rest, overflow_open)) {
if (splitComment(rest, overflow_open, overflow_close)) |block| {
const end = mem.findScalar(u8, block.rest, '\n') orelse break;
rest = block.rest[end + 1 ..];
continue;
}
}
}
const end = mem.findScalar(u8, rest, '\n') orelse break;
const line = mem.trimStart(u8, rest[0..end], " ");
if (line.len >= 3 and end - line.len <= 3 and (line[0] == '`' or line[0] == '~')) {
var width: usize = 1;
while (width < line.len and line[width] == line[0]) width += 1;
if (fence.len == 0) {
if (width >= 3 and (line[0] != '`' or mem.findScalar(u8, line[width..], '`') == null)) fence = line[0..width];
} else if (line[0] == fence[0] and width >= fence.len and mem.trim(u8, line[width..], " \t\r").len == 0) {
fence = "";
}
}
rest = rest[end + 1 ..];
}
return found;
}
fn parseLegacy(arena: Allocator, bytes: []const u8) !File {
const unchanged: File = .{ .body = bytes };
var meta: Meta = .{};
var rest = bytes;
if (lineMarker(rest, meta_open, true)) |open| {
const block = splitComment(rest[open..], meta_open, meta_close) orelse return unchanged;
// Only a final comment is a legacy trailer. Otherwise it is body text.
if (mem.trim(u8, block.rest, " \r\n").len == 0) {
meta = (try readMeta(arena, block.payload, true)) orelse return unchanged;
if (meta.v != 1) return unchanged;
rest = rest[0..open];
}
}
var f: File = .{ .body = rest };
if (lineMarker(rest, overflow_open, true)) |open| {
const block = splitComment(rest[open..], overflow_open, overflow_close) orelse return unchanged;
if (mem.trim(u8, block.rest, " \r\n").len == 0) {
f.body = rest[0..open];
f.overflow = try decodeOverflow(arena, block.payload);
}
} else if (lineMarker(rest, overflow_mark, false)) |open| {
f.body = rest[0..open];
f.overflow = mem.trim(u8, rest[open + overflow_mark.len ..], "\r\n");
}
if (f.body.len == bytes.len) return unchanged;
// Legacy trailers did not distinguish body line endings from their separators.
f.body = mem.trimEnd(u8, f.body, "\r\n");
f.groups = (try placeGroups(arena, f.body, meta.groups, &.{})) orelse return unchanged;
var ghosts: std.ArrayList(GhostRec) = .empty;
for (meta.ghosts) |g| {
const at = anchor(f.body, g.at, g.text) orelse return unchanged;
try ghosts.append(arena, .{ .at = at, .text = g.text });
}
// Reanchoring an externally edited v1 file can change the order of its spans.
mem.sort(GhostRec, ghosts.items, {}, struct {
fn lessThan(_: void, a: GhostRec, b: GhostRec) bool {
return a.at < b.at;
}
}.lessThan);
var end: usize = 0;
for (ghosts.items) |g| {
if (g.at < end) return unchanged;
end = g.at + g.text.len;
}
f.ghosts = ghosts.items;
return f;
}
fn validGroup(g: GroupRec) bool {
return g.variants.len >= 2 and g.active < g.variants.len;
}
/// The groups that have a place in the body. Any other is let go: what it was about has been
/// settled elsewhere. Null if one makes no sense.
fn placeGroups(arena: Allocator, body: []const u8, records: []const SavedGroup, moves: []const Move) !?[]const GroupRec {
var groups: std.ArrayList(GroupRec) = .empty;
var origins: std.ArrayList(usize) = .empty; // where each of those was
for (records) |g| {
var rec: GroupRec = .{ .scope = g.scope, .at = g.at, .active = g.active, .variants = g.variants, .ai = g.ai };
if (!validGroup(rec)) return null;
const text = g.variants[g.active];
var spot = try groupSpot(arena, body, g, moves);
// Two that stood apart must not end up on the same text.
if (spot) |at| for (groups.items, origins.items) |other, origin| {
const n = other.variants[other.active].len;
if (overlaps(at, text.len, other.at, n) and !overlaps(g.at, text.len, origin, n)) spot = null;
};
rec.at = spot orelse continue;
try groups.append(arena, rec);
try origins.append(arena, g.at);
}
return groups.items;
}
fn groupSpot(arena: Allocator, body: []const u8, g: SavedGroup, moves: []const Move) !?usize {
const text = g.variants[g.active];
if (text.len == 0) return null;
var was = g.at;
for (moves) |m| {
const shared = overlaps(g.at, text.len, m.was.at, m.was.text.len);
if (m.to) |to| {
if (!shared or g.at < m.was.at) continue;
const at = to + (g.at - m.was.at); // it goes where the ghost it starts in goes
if (mem.startsWith(u8, body[at..], text)) return at;
} else if (shared) {
return null; // some of its text is in Overflow
} else if (m.was.at < g.at) was -|= m.was.text.len;
}
const near: Near = .from(g);
return if (near.unknown()) anchor(body, was, text) else near.find(arena, body, was, text);
}
fn overlaps(a: usize, a_len: usize, b: usize, b_len: usize) bool {
return a < b +| b_len and b < a +| a_len;
}
/// Trust a matching offset even when repeated; a stale offset needs one unique match.
fn anchor(body: []const u8, at: usize, text: []const u8) ?usize {
if (text.len == 0) return null;
if (at <= body.len and mem.startsWith(u8, body[at..], text)) return at;
return only(body, text);
}
// --- Text helpers ---------------------------------------------------------------------------
/// What a selection inside one paragraph covers: all of a several-sentence paragraph, whole
/// sentences, or something smaller. `start` and `end` are byte offsets into `para`.
pub fn classify(para: []const u8, start: usize, end: usize) Scope {
const space = " \t\r\n";
const before = mem.trimEnd(u8, para[0..start], space);
const sel = mem.trim(u8, para[start..end], space);
const after = mem.trim(u8, para[end..], space);
if (sel.len == 0) return .word;
const at_head = mem.trimStart(u8, before, "#> ").len == 0; // heading and quote marks do not count
const starts = at_head or isStop(before[before.len - 1]);
const ends = after.len == 0 or isStop(sel[sel.len - 1]);
if (!starts or !ends) return .word;
if (at_head and after.len == 0) {
for (sel[0 .. sel.len - 1], sel[1..]) |c, next| if (isStop(c) and next == ' ') return .paragraph;
}
return .sentence;
}
fn isStop(c: u8) bool {
return c == '.' or c == '!' or c == '?';
}
/// Whether `word` takes "an" rather than "a". It goes by the sound the word starts with,
/// as far as a few spellings give that away. Null when it does not start with a letter.
pub fn takesAn(word: []const u8) ?bool {
if (word.len == 0 or !std.ascii.isAlphabetic(word[0])) return null;
var buf: [6]u8 = undefined;
const head = std.ascii.lowerString(&buf, word[0..@min(word.len, buf.len)]);
const starts = struct {
fn any(s: []const u8, prefixes: []const []const u8) bool {
for (prefixes) |p| if (mem.startsWith(u8, s, p)) return true;
return false;
}
}.any;
if (starts(head, &.{ "hour", "honest", "honor", "honour", "heir" })) return true; // a silent h
if (starts(head, &.{ "unin", "unim", "unid" })) return true; // "an uninvited", not "a unit"
if (starts(head, &.{ "uni", "use", "usu", "uti", "eu", "one", "once" })) return false; // "you" and "won"
return mem.findScalar(u8, "aeiou", head[0]) != null;
}
pub fn countWords(s: []const u8) usize {
var n: usize = 0;
var it = mem.tokenizeAny(u8, s, " \t\r\n");
while (it.next()) |_| n += 1;
return n;
}
/// Length in UTF-16 units. NSString indexes by UTF-16 unit, the file by byte.
pub fn utf16Len(s: []const u8) usize {
var n: usize = 0;
for (s) |b| {
if (b & 0xC0 != 0x80) n += 1; // start of a codepoint
if (b >= 0xF0) n += 1; // four bytes: a surrogate pair
}
return n;
}
/// Byte offset of UTF-16 index `index`.
pub fn utf8Index(s: []const u8, index: usize) usize {
var n: usize = 0;
for (s, 0..) |b, at| {
if (b & 0xC0 == 0x80) continue;
if (n >= index) return at;
n += if (b >= 0xF0) 2 else 1;
}
return s.len;
}
// --- The check ------------------------------------------------------------------------------
test "hidden overflow preserves bytes and malformed blocks" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const text = "\n \r\n<!-- nested --> --!> -- & - \\ )-->\x00\xff\n\n";
const body = "\r\n```zig\r\nconst x = 1;\r\n\n"; // Deliberately unclosed fence.
const bytes = try serialize(a, .{ .body = body, .overflow = text });
try t.expect(mem.startsWith(u8, bytes, overflow_open));
const block = splitComment(bytes, overflow_open, overflow_close).?;
try t.expectEqualStrings(framing ++ body, block.rest);
const back = try parse(a, bytes);
try t.expectEqualStrings(body, back.body);
try t.expectEqualStrings(text, back.overflow);
const legacy = try parse(a, "Body\n\n<!-- overflow -->\n\nOld text.\n");
try t.expectEqualStrings("Body", legacy.body);
try t.expectEqualStrings("Old text.", legacy.overflow);
const wrapped = try parse(a, "Body\n\n<!-- overflow\n(\n&-\r\n)-->\n");
try t.expectEqualStrings("Body", wrapped.body);
try t.expectEqualStrings("\n&-\r\n", wrapped.overflow);
for ([_][]const u8{
"Body\n\n<!-- overflow\n(unclosed -->\nmore\n",
"<!-- overflow\n(a --> leaked)-->\n\nBody\n",
"<!-- overflow\n(a --!> leaked)-->\n\nBody\n",
"<!-- overflow\n(stash)-->\n<!-- write_away {nope -->\n\nBody\n",
"<!-- overflow\n(stash)-->\n<!-- write_away {\"v\":2,\"ghsts\":[]} -->\n\nBody\n",
"<!-- overflow\n(stash)-->\n<!-- write_away {\"v\":4} -->\n\nBody\n",
"Body\n\n<!-- overflow\n(stash)-->\n\n<!-- write_away {\"v\":3} -->\n",
"Text.\n\n<!-- write_away {nope -->\n",
}) |bad| {
const f = try parse(a, bad);
try t.expectEqualStrings(bad, f.body);
try t.expectEqualStrings("", f.overflow);
}
}
fn expectRaw(arena: Allocator, bytes: []const u8) !void {
const t = std.testing;
const f = try parse(arena, bytes);
try t.expectEqualStrings(bytes, f.body);
try t.expectEqualStrings("", f.overflow);
try t.expectEqual(0, f.groups.len);
try t.expectEqual(0, f.ghosts.len);
try t.expectEqualStrings(bytes, try serialize(arena, f));
}
test "legacy trailers are not taken from fenced Markdown" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const bare = "<!-- overflow -->\nSome example text.\n";
const wrapped = "<!-- overflow\n(Example.)-->\n";
const meta = "<!-- write_away {\"v\":1} -->\n";
for ([_][]const u8{ bare, wrapped, meta }) |example| {
try expectRaw(a, try mem.concat(a, u8, &.{ "Body\n\n```md\n", example }));
try expectRaw(a, try mem.concat(a, u8, &.{ "Body\n\n ~~~md\r\n", example, " ~~~~ \r\n" }));
}
try expectRaw(a, "````md\n```\n<!-- overflow -->\n````\n");
const closed = "```md\n" ++ bare ++ "```";
const real = try parse(a, closed ++ "\n\n<!-- overflow -->\nReal overflow.\n");
try t.expectEqualStrings(closed, real.body);
try t.expectEqualStrings("Real overflow.", real.overflow);
const wrapped_then_meta = try parse(a, "Body\n\n<!-- overflow\n(\n```md\nUnclosed example.)-->\n" ++ meta);
try t.expectEqualStrings("Body", wrapped_then_meta.body);
try t.expectEqualStrings("\n```md\nUnclosed example.", wrapped_then_meta.overflow);
}
test "v1 ghosts require an exact or unique anchor" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const trailer = "\n\n<!-- write_away {\"v\":1,\"ghosts\":[{\"at\":4,\"text\":\"ghost\"}]} -->\n";
try expectRaw(a, "ghost and ghost" ++ trailer);
try expectRaw(a, "no match" ++ trailer);
try expectRaw(a, "ghost\n\n<!-- write_away {\"v\":1,\"ghosts\":[{\"at\":0,\"text\":\"ghost\"},{\"at\":9,\"text\":\"ghost\"}]} -->\n");
const exact = try parse(a, "one ghost and ghost" ++ trailer);
try t.expectEqualStrings("one ghost and ghost", exact.body);
try t.expectEqual(1, exact.ghosts.len);
try t.expectEqual(4, exact.ghosts[0].at);
}
test "groups without surroundings need an exact or unique anchor, or are dropped" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const body = "one banana";
const first_group = "\"groups\":[{\"at\":0,\"variants\":[\"one\",\"first\"]},";
for ([_][]const u8{
"{\"at\":0,\"variants\":[\"ana\",\"missing\"],\"active\":1}", // The inactive variant must not anchor.
"{\"at\":0,\"variants\":[\"ana\",\"other\"]}", // Two overlapping matches.
"{\"at\":5,\"variants\":[\"ana\"]}", // Not a persistent group.
"{\"at\":5,\"variants\":[\"ana\",\"other\"],\"active\":2}",
}, [_]bool{ true, true, false, false }) |bad, sensible| {
for ([_][]const u8{
try mem.concat(a, u8, &.{ body, "\n\n<!-- overflow -->\nNotes\n", meta_open, "{\"v\":1,", first_group, bad, "]}", meta_close }),
try mem.concat(a, u8, &.{ "<!-- overflow\n(Notes)-->\n", meta_open, "{\"v\":2,", first_group, bad, "]}", meta_close, framing, body }),
}) |bytes| {
if (!sensible) { // not something an edit elsewhere could do
try expectRaw(a, bytes);
continue;
}
const f = try parse(a, bytes);
try t.expectEqualStrings(body, f.body);
try t.expectEqualStrings("Notes", f.overflow);
try t.expect(f.groups.len == 1 and !f.displaced);
}
}
const record = "{\"at\":5,\"variants\":[\"ana\",\"other\"]}]";
const legacy = try mem.concat(a, u8, &.{ body, "\n\n", meta_open, "{\"v\":1,", first_group, record, "}", meta_close });
const prefixed = try mem.concat(a, u8, &.{ meta_open, "{\"v\":2,", first_group, record, "}", meta_close, framing, body });
for ([_][]const u8{ legacy, prefixed }) |bytes| {
const exact = try parse(a, bytes);
try t.expectEqual(2, exact.groups.len);
try t.expectEqual(5, exact.groups[1].at);
}
}
test "ghosts are hidden, and found again after edits elsewhere or left in Overflow" {
const t = std.testing;
var arena_state: std.heap.ArenaAllocator = .init(t.allocator);
defer arena_state.deinit();
const arena = arena_state.allocator();
// Round trip. The '>' in a variant must not close the comment.
const body = "# Title\n\nThe tension is real. Maybe cut this.";
const file: File = .{
.body = body,
.overflow = "Kept for later.",
.groups = &.{.{ .scope = .word, .at = 13, .active = 1, .variants = &.{ "pressure", "tension", "a --> b" } }},
.ghosts = &.{.{ .at = 30, .text = "Maybe cut this." }},
};
const bytes = try serialize(arena, file);
const overflow = splitComment(bytes, overflow_open, overflow_close).?;
try t.expect(mem.startsWith(u8, overflow.rest, "\n" ++ meta_open ++ "{\"v\":3,"));
const block = splitComment(overflow.rest[1..], meta_open, meta_close).?;
try t.expectEqualStrings("\n\n# Title\n\nThe tension is real. ", block.rest);
try t.expect(mem.find(u8, bytes, "a -->") == null);
const back = try parse(arena, bytes);
try t.expectEqualStrings(body, back.body);
try t.expectEqualStrings("Kept for later.", back.overflow);
try t.expectEqual(13, back.groups[0].at);
try t.expectEqualStrings("a --> b", back.groups[0].variants[2]);
try t.expectEqual(30, back.ghosts[0].at);
try t.expect(!back.displaced);
try t.expectEqualStrings(bytes, try serialize(arena, back));
// A ghost with no text around it on record, and nothing to vouch for its offset.
try expectRaw(arena, "<!-- write_away {\"v\":2,\"ghosts\":[{\"at\":0,\"text\":\"ghost\"}]} -->\n\nBody");
// [was] is a ghost, and <word> a group. What the visible text became, and how that opens.
const cases = [_][3][]const u8{
// Edits before it, after it, and on one side right up against it.
.{ "# Title\n\nThe tension is real.[ Maybe cut this.]", "# A longer title\n\nThe tension is real.", "# A longer title\n\nThe tension is real.[ Maybe cut this.]" },
.{ "# Title\n\nThe tension is real.[ Maybe cut this.]", "# Title\n\nThe tension is real. And more.", "# Title\n\nThe tension is real.[ Maybe cut this.] And more." },
.{ "One thing. [Cut. ]The rest of it goes on from there.", "Changed! The rest of it goes on from there.", "Changed! [Cut. ]The rest of it goes on from there." },
// New text at the very spot stands after it.
.{ "The tension is real.[ Cut.] The rest goes on.", "The tension is real. New. The rest goes on.", "The tension is real.[ Cut.] New. The rest goes on." },
// The same text twice: only an offset that still holds can tell which.
.{ "Same line here.\nSame line here.[ Cut.]\nSame line here.\n", "Same line here.\nSame line here.\nSame line here.\n", "Same line here.\nSame line here.[ Cut.]\nSame line here.\n" },
.{ "echo echo echo [Cut]echo echo echo echo", "echo echo echo echo echo echo echo echo", "echo echo echo [Cut]echo echo echo echo echo" },
.{ "a\nA line.\nA line.[ Cut.]\nA line.\nA line.\nA line.\nA line.\nA line.\n", "abc\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\n", "abc\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\nA line.\n| Cut." },
// Both sides rewritten, or changed about.
.{ "The tension is real.[ Cut.] And so on.", "Nothing like it.", "Nothing like it.| Cut." },
.{ "First this came.[ Cut.]Then that went.", "Then that went. First this came.", "Then that went. First this came.| Cut." },
.{ "[All of it.]", "New.", "New.|All of it." },
// Each goes its own way, and those side by side stay in order. UTF-8 is kept whole.
.{ "終終終終終終終終終終終終é[👻][ a]é終終終終終終終終終終終終. Then [gone]. The end is near now.", "New 終終終終終終終終終終終終éé終終終終終終終終終終終終.", "New 終終終終終終終終終終終終é[👻][ a]é終終終終終終終終終終終終.|gone" },
// They follow their text past one another.
.{ "First paragraph is here.[ One.]\n\nSecond paragraph follows.[ Two.]\n\nThird.", "Second paragraph follows.\n\nFirst paragraph is here.\n\nThird.", "Second paragraph follows.[ Two.]\n\nFirst paragraph is here.[ One.]\n\nThird." },
};
for (cases) |c| {
const saved = try serialize(arena, try bracketed(arena, c[0]));
const visible = splitComment(saved, meta_open, meta_close).?.rest;
const f = try parse(arena, try mem.concat(arena, u8, &.{ saved[0 .. saved.len - visible.len], framing, c[1] }));
var want = mem.splitScalar(u8, c[2], '|');
const opened = try bracketed(arena, want.first());
try t.expectEqualStrings(opened.body, f.body);
try t.expectEqualStrings(want.next() orelse "", f.overflow);
try t.expectEqual(f.overflow.len != 0, f.displaced);
try t.expectEqual(opened.ghosts.len, f.ghosts.len);
for (opened.ghosts, f.ghosts) |a, b| {
try t.expectEqual(a.at, b.at);
try t.expectEqualStrings(a.text, b.text);
}
// What is saved next opens the same, with nothing left to place.
const again = try parse(arena, try serialize(arena, f));
try t.expectEqualStrings(f.body, again.body);
try t.expectEqualStrings(f.overflow, again.overflow);
try t.expectEqual(f.ghosts.len, again.ghosts.len);
try t.expect(!again.displaced);
}
// Text already in Overflow stays first. Once there, a ghost does not come back with its place.
const gone = try parse(arena, try mem.replaceOwned(u8, arena, bytes, "\n\nThe tension is real. ", "\n\nNo tension at all."));
try t.expectEqualStrings("Kept for later.\n\nMaybe cut this.", gone.overflow);
try t.expectEqual(1, gone.groups.len);
const stowed = try mem.replaceOwned(u8, arena, try serialize(arena, gone), "\n\nNo tension at all.", "\n\nThe tension is real. ");
const back_again = try parse(arena, stowed);
try t.expectEqualStrings("Kept for later.\n\nMaybe cut this.", back_again.overflow);
try t.expectEqual(0, back_again.ghosts.len);
}
/// A file whose ghosts are the bracketed parts of `text`.
fn bracketed(arena: Allocator, text: []const u8) !File {
var body: std.ArrayList(u8) = .empty;
var ghosts: std.ArrayList(GhostRec) = .empty;
var parts = mem.splitScalar(u8, text, '[');
try body.appendSlice(arena, parts.first());
while (parts.next()) |part| {
const close = mem.findScalar(u8, part, ']').?;
try ghosts.append(arena, .{ .at = body.items.len, .text = part[0..close] });
try body.appendSlice(arena, part[0..close]);
try body.appendSlice(arena, part[close + 1 ..]);
}
return .{ .body = body.items, .ghosts = ghosts.items };
}
test "alternatives go where their ghost goes" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const group: GroupRec = .{ .at = 5, .variants = &.{ "echo", "other" }, .ai = &.{"other"} };
const saved = try serialize(a, .{ .body = "echo echo and then the end.", .groups = &.{group}, .ghosts = &.{.{ .at = 5, .text = "echo" }} });
// The first "echo" reads the same, but it is not the one.
const moved = try parse(a, try mem.replaceOwned(u8, a, saved, "\n\necho and", "\n\nAn echo and"));
try t.expectEqualStrings("An echo echo and then the end.", moved.body);
try t.expectEqual(8, moved.groups[0].at);
const lost = try parse(a, try mem.replaceOwned(u8, a, saved, "\n\necho and then the end.", "\n\necho only"));
try t.expectEqualStrings("echo only", lost.body);
try t.expectEqual(0, lost.groups.len);
try t.expectEqualStrings("echo", lost.overflow);
}
test "v2 offsets hold while the visible bytes do; after that its ghosts are in Overflow" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const visible = "# A draft\n\nThe tension is real.\n";
for ([_]usize{ 31, 3000 }, [_][]const u8{ "# A draft\n\nThe tension is real. Cut this.\n", visible }, [_][]const u8{ "", " Cut this." }) |at, body, over| {
const old = try mem.concat(a, u8, &.{ try std.fmt.allocPrint(a, "{s}{{\"v\":2,\"groups\":[{{\"at\":15,\"variants\":[\"tension\",\"strain\"]}}],\"ghosts\":[{{\"at\":{d},\"text\":\" Cut this.\"}}],\"visible_sha256\":\"{s}\"}}{s}", .{ meta_open, at, &digest(visible), meta_close }), framing, visible });
const f = try parse(a, old);
try t.expectEqualStrings(body, f.body);
try t.expectEqualStrings(over, f.overflow);
try t.expectEqual(1, f.groups.len);
const edited = try parse(a, try mem.replaceOwned(u8, a, old, "# A draft", "# My draft"));
try t.expectEqualStrings("# My draft\n\nThe tension is real.\n", edited.body);
try t.expectEqualStrings(" Cut this.", edited.overflow);
try t.expectEqual(16, edited.groups[0].at);
try t.expect(edited.displaced);
}
}
test "restores adjacent UTF-8 ghosts and overlapping groups after an editor edit" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
const before = "\n\r\n```zig\r\ncafé";
const first = "👻";
const second = "<!-- --!> -->";
const keep = "\r\n終 ";
const last = "\n💤\n";
const body = before ++ first ++ second ++ keep ++ last;
const file: File = .{
.body = body,
.groups = &.{
.{ .at = before.len - "café".len, .variants = &.{ "café" ++ first ++ second, "coffee" } },
.{ .at = before.len, .variants = &.{ first, "spirit" }, .ai = &.{"spirit"} },
.{ .at = (before ++ first ++ second).len, .variants = &.{ keep, "end" } },
},
.ghosts = &.{
.{ .at = before.len, .text = first },
.{ .at = (before ++ first).len, .text = second },
.{ .at = (before ++ first ++ second ++ keep).len, .text = last },
},
};
const bytes = try serialize(a, file);
try t.expectEqualStrings(framing ++ before ++ keep, splitComment(bytes, meta_open, meta_close).?.rest);
const restored = try parse(a, bytes);
try t.expectEqualStrings(body, restored.body);
try t.expectEqual(file.ghosts.len, restored.ghosts.len);
for (file.ghosts, restored.ghosts) |expected, actual| {
try t.expectEqual(expected.at, actual.at);
try t.expectEqualStrings(expected.text, actual.text);
}
try t.expectEqual(file.groups.len, restored.groups.len);
for (file.groups, restored.groups) |expected, actual| try t.expectEqual(expected.at, actual.at);
try t.expectEqualStrings("spirit", restored.groups[1].ai.?[0]);
var edited = restored;
edited.body = try mem.concat(a, u8, &.{ restored.body, "new ending\n" });
const saved = try serialize(a, edited);
try t.expectEqualStrings(framing ++ before ++ keep ++ "new ending\n", splitComment(saved, meta_open, meta_close).?.rest);
try t.expectEqualStrings(edited.body, (try parse(a, saved)).body);
const all_hidden = try serialize(a, .{ .body = first ++ last, .ghosts = &.{
.{ .at = 0, .text = first },
.{ .at = first.len, .text = last },
} });
try t.expectEqualStrings(framing, splitComment(all_hidden, meta_open, meta_close).?.rest);
try t.expectEqualStrings(first ++ last, (try parse(a, all_hidden)).body);
try t.expectError(error.InvalidGhost, serialize(a, .{ .body = body, .ghosts = &.{.{ .at = 0, .text = last }} }));
}
test "comments follow YAML frontmatter, which keeps the first line" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
try t.expectEqual(7, frontmatter("---\n---"));
try t.expectEqual(17, frontmatter("--- \r\nk: v\n... \r\n---\n"));
for ([_][]const u8{ "", "---", "---\nk: v\n", "---\nk: v\n ---\n", "\n---\n---\n", "...\n---\n", "----\n---\n" }) |none| try t.expectEqual(0, frontmatter(none));
const front = "---\ntitle: café\n---\n";
const rest = "\n# Title\n\n---\n";
const file: File = .{
.body = front ++ rest,
.overflow = "Kept.",
.groups = &.{.{ .at = front.len + 3, .variants = &.{ "Title", "Name" } }},
.ghosts = &.{.{ .at = 4, .text = "title" }},
};
const bytes = try serialize(a, file);
try t.expect(mem.startsWith(u8, bytes, "---\n: café\n---\n" ++ overflow_open));
try t.expect(mem.endsWith(u8, bytes, meta_close ++ framing ++ rest));
const back = try parse(a, bytes);
try t.expectEqualStrings(file.body, back.body);
try t.expectEqualStrings("Kept.", back.overflow);
try t.expectEqual(front.len + 3, back.groups[0].at);
try t.expectEqual(4, back.ghosts[0].at);
const stashed = try serialize(a, .{ .body = front ++ rest, .overflow = "Kept." });
try t.expectEqualStrings(front ++ overflow_open ++ "Kept." ++ overflow_close ++ framing ++ rest, stashed);
try t.expectEqualStrings(front ++ rest, (try parse(a, stashed)).body);
// A file saved with its comments first still opens, and saves the new way.
const old = try parse(a, overflow_open ++ "Kept." ++ overflow_close ++ framing ++ front ++ rest);
try t.expectEqualStrings(front ++ rest, old.body);
try t.expectEqualStrings(stashed, try serialize(a, old));
// With no line of its own to close on, or a ghost for a delimiter, the comments lead.
const cut_off = try serialize(a, .{ .body = "---\nk: v\n---", .overflow = "Kept." });
try t.expect(mem.startsWith(u8, cut_off, overflow_open));
try t.expectEqualStrings("---\nk: v\n---", (try parse(a, cut_off)).body);
const hidden: File = .{ .body = front ++ rest, .ghosts = &.{.{ .at = 0, .text = "---" }} };
const leading = try serialize(a, hidden);
try t.expect(mem.startsWith(u8, leading, meta_open));
try t.expectEqualStrings(hidden.body, (try parse(a, leading)).body);
// Frontmatter before a comment that cannot be read is left exactly as it is.
try expectRaw(a, front ++ meta_open ++ "{nope" ++ meta_close ++ framing ++ rest);
}
test "plain Markdown is byte-exact; v1 ghosts and ghost-free v2 groups still follow their text" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
for ([_][]const u8{ "", "Just text.", "\n\r\n# Title\r\n", "\n```\n ", "---\nkey: café\n---\n\n" }) |body| {
const bytes = try serialize(a, .{ .body = body });
try t.expectEqualStrings(body, bytes);
try t.expectEqualStrings(body, (try parse(a, bytes)).body);
}
const legacy = "# A longer title\n\nThe tension is real. Maybe cut this.\n\n" ++
"<!-- overflow\n(Old text.)-->\n\n" ++
"<!-- write_away {\"v\":1,\"groups\":[{\"at\":13,\"variants\":[\"tension\",\"pressure\"]}]," ++
"\"ghosts\":[{\"at\":30,\"text\":\"Maybe cut this.\"}]} -->\n";
const old = try parse(a, legacy);
try t.expectEqualStrings("# A longer title\n\nThe tension is real. Maybe cut this.", old.body);
try t.expectEqualStrings("Old text.", old.overflow);
try t.expectEqual(22, old.groups[0].at);
try t.expectEqual(39, old.ghosts[0].at);
const migrated = try serialize(a, old);
try t.expectEqualStrings(old.body, (try parse(a, migrated)).body);
try t.expect(!mem.endsWith(u8, migrated, "Maybe cut this."));
const no_ghosts = try serialize(a, .{
.body = "The tension is real.\r\n\n",
.groups = &.{.{ .at = 4, .variants = &.{ "tension", "strain" } }},
});
const edited = try mem.replaceOwned(u8, a, no_ghosts, "The tension is", "Some tension is");
const moved = try parse(a, edited);
try t.expectEqualStrings("Some tension is real.\r\n\n", moved.body);
try t.expectEqual(5, moved.groups[0].at);
const gone = try parse(a, try mem.replaceOwned(u8, a, no_ghosts, "\n\nThe tension is", "\n\nThe strain is"));
try t.expectEqualStrings("The strain is real.\r\n\n", gone.body);
try t.expect(gone.groups.len == 0 and gone.overflow.len == 0 and !gone.displaced);
try t.expectEqualStrings(gone.body, try serialize(a, gone));
}
test "a group on a word that is there twice keeps its own, or is dropped" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const a = state.allocator();
// <word> is a group with "other". What the text became, and how that opens.
const cases = [_][3][]const u8{
.{ "The end of the story is the <end>.", "So, the end of the story is the end.", "So, the end of the story is the <end>." },
.{ "The <end> of the story is the end.", "So, the end of the tale is the end.", "So, the <end> of the tale is the end." },
.{ "The <end> of the story is the end.", "At the end of a story comes the end.", "At the <end> of a story comes the end." },
// Its own was rewritten, and the other is not it.
.{ "The <end> of the story is the end.", "The close of the story is the end.", "The close of the story is the end." },
.{ "One <tension> here.", "One more tension there, and a tension here.", "One more tension there, and a <tension> here." },
.{ "<All of it.>", "More. All of it.", "More. <All of it.>" },
.{ "<All of it.>", "None.", "None." },
};
for (cases) |c| {
const saved = try serialize(a, try angled(a, c[0]));
const was = splitComment(saved, meta_open, meta_close).?.rest;
const f = try parse(a, try mem.concat(a, u8, &.{ saved[0 .. saved.len - was.len], framing, c[1] }));
const want = try angled(a, c[2]);
try t.expectEqualStrings(want.body, f.body);
try t.expectEqual(want.groups.len, f.groups.len);
for (want.groups, f.groups) |x, y| try t.expectEqual(x.at, y.at);
try t.expect(f.overflow.len == 0 and !f.displaced);
}
// Two on the same word, one of which is gone, do not share the other.
const two = try serialize(a, .{ .body = "echo echo", .groups = &.{
.{ .at = 0, .variants = &.{ "echo", "first" } },
.{ .at = 5, .variants = &.{ "echo", "second" } },
} });
const f = try parse(a, try mem.replaceOwned(u8, a, two, "\n\necho echo", "\n\necho"));
try t.expect(f.groups.len < 2);
}
/// A file in which the part of `text` in angle brackets is a group.
fn angled(arena: Allocator, text: []const u8) !File {
const lo = mem.findScalar(u8, text, '<') orelse return .{ .body = text };
const hi = mem.findScalar(u8, text, '>').?;
const groups = try arena.alloc(GroupRec, 1);
const variants = try arena.dupe([]const u8, &.{ text[lo + 1 .. hi], "other" });
groups[0] = .{ .at = lo, .variants = variants };
return .{ .body = try mem.concat(arena, u8, &.{ text[0..lo], variants[0], text[hi + 1 ..] }), .groups = groups };
}
test "variants and text helpers" {
const t = std.testing;
var state: std.heap.ArenaAllocator = .init(t.allocator);
defer state.deinit();
const arena = state.allocator();
// Variants.
var g = try Group.init(arena, .word, &.{ "tension", "pressure" }, 0);
g.step(-1);
try t.expectEqualStrings("pressure", g.shown());
try g.sync(arena, "strain", false); // typing rewrites the active variant
try t.expectEqualStrings("strain", g.variants.items[1]);
try g.sync(arena, "tension", true); // undo lands on the other variant
try t.expectEqual(0, g.active);
try g.remove(arena);
try t.expectEqualStrings("strain", g.shown());
try g.sync(arena, "tension", true); // undoing the delete brings it back
try t.expectEqual(2, g.variants.items.len);
try t.expectEqualStrings("tension", g.shown());
// The panel's rows. A blank row is not a variant, and a caret on one changes nothing.
try t.expect(g.sameRows("tension\nstrain\n"));
try t.expect(!g.sameRows("tension\n"));
try t.expect(try g.setRows(arena, "tension\nstrain\n\nc", 2, ""));
try t.expectEqualStrings("c", g.shown()); // typed on the new row, and showing
try t.expect(try g.setRows(arena, "tension\nstrain\n\n", null, "strain"));
try t.expectEqualStrings("strain", g.shown()); // the row was emptied: back to where the visit began
try t.expect(try g.setRows(arena, "tension\nstrain\n", null, ""));
try t.expectEqualStrings("strain", g.shown());
// Asking the AI. The "??" row is not a variant, and neither is the "?" before it.
try t.expect(g.sameRows("tension\nstrain\n?"));
try t.expect(g.sameRows("tension\nstrain\n ??"));
try t.expect(asks("??") and !asks("?") and !asks("what??"));
try t.expectEqualStrings("pull", suggestion("3. pull").?);
try t.expectEqualStrings("pull", suggestion(" - “pull” ").?);
try t.expectEqualStrings("\"no\" and \"yes\"", suggestion("\"no\" and \"yes\"").?);
try t.expectEqual(null, suggestion(" "));
try g.markAI(arena, "strain");
try t.expect(g.isAI("strain") and !g.isAI("strains"));
try t.expect(!try g.setRows(arena, " \n", null, ""));
try t.expectEqual(2, g.variants.items.len);
// a or an.
try t.expectEqual(true, takesAn("eraser"));
try t.expectEqual(false, takesAn("thumbtack"));
try t.expectEqual(true, takesAn("Hour"));
try t.expectEqual(false, takesAn("user"));
try t.expectEqual(true, takesAn("uninvited"));
try t.expectEqual(null, takesAn("“quoted”"));
// Text helpers.
const para = "# One two. Three four. Five";
try t.expectEqual(Scope.word, classify(para, 6, 9));
try t.expectEqual(Scope.sentence, classify(para, 11, 22));
try t.expectEqual(Scope.sentence, classify(para, 2, 10));
try t.expectEqual(Scope.paragraph, classify(para, 2, para.len));
try t.expectEqual(3, countWords(" a b\nc "));
try t.expectEqual(4, utf16Len("é😀a")); // 1 + 2 + 1
try t.expectEqual(6, utf8Index("é😀a", 3));
}
|