summaryrefslogtreecommitdiff
path: root/src/doc.zig
blob: 2320a6a8f5accda313fe0c719d8f5e477cd2cb34 (plain)
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
//! 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 -------------------------------------------------------------------------------
//
// v2 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 v2 ghosts must be restored before the
// alternatives are reanchored.

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 Meta = struct {
    v: u32 = 1,
    groups: []const GroupRec = &.{},
    ghosts: []const GhostRec = &.{},
    visible_sha256: ?[Sha256.digest_length * 2]u8 = null,
};

pub const File = struct {
    body: []const u8 = "",
    overflow: []const u8 = "",
    groups: []const GroupRec = &.{},
    ghosts: []const GhostRec = &.{},
};

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, "&#38;"),
            '-' => try out.appendSlice(gpa, "&#45;"),
            else => try out.append(gpa, c),
        };
        try out.appendSlice(gpa, overflow_close);
        if (has_meta) try out.append(gpa, '\n');
    }
    if (has_meta) {
        const json = try std.json.Stringify.valueAlloc(gpa, Meta{
            .v = 2,
            .groups = f.groups,
            .ghosts = f.ghosts,
            .visible_sha256 = if (f.ghosts.len != 0) digest(visible) else null,
        }, .{ .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;
}

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 or !mem.startsWith(u8, block.rest, framing)) return unchanged;
    if ((meta.ghosts.len != 0) != (meta.visible_sha256 != null)) return unchanged;

    const visible = try mem.concat(arena, u8, &.{ head, block.rest[framing.len..] });
    const body = if (meta.ghosts.len == 0) visible else body: {
        const expected = meta.visible_sha256 orelse return unchanged;
        if (!mem.eql(u8, &expected, &digest(visible))) return unchanged;
        break :body ghost_io.restore(arena, visible, meta.ghosts) catch |err| switch (err) {
            error.OutOfMemory => return err,
            else => return unchanged,
        };
    };
    const groups = (try reanchorGroups(arena, body, meta.groups)) orelse return unchanged;
    return .{
        .body = body,
        .overflow = if (overflow) |encoded| try decodeOverflow(arena, encoded) else "",
        .groups = groups,
        .ghosts = meta.ghosts,
    };
}

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..], "&#38;")) {
            try decoded.append(arena, '&');
            i += 5;
        } else if (mem.startsWith(u8, encoded[i..], "&#45;")) {
            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 reanchorGroups(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;
}

fn reanchorGroups(arena: Allocator, body: []const u8, records: []const GroupRec) !?[]const GroupRec {
    const groups = try arena.alloc(GroupRec, records.len);
    for (records, groups) |g, *kept| {
        if (!validGroup(g)) return null;
        kept.* = g;
        kept.at = anchor(body, g.at, g.variants[g.active]) orelse return null;
    }
    return groups;
}

/// 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;
    const first = mem.find(u8, body, text) orelse return null;
    return if (mem.find(u8, body[first + 1 ..], text) == null) first else null;
}

// --- 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 --> --!> -- & &#45; \\ )-->\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&#38;&#45;\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\":3} -->\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 "v1 and v2 groups preserve all raw metadata if any record cannot be anchored" {
    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}",
    }) |bad| {
        try expectRaw(a, try mem.concat(a, u8, &.{ body, "\n\n<!-- overflow -->\nNotes\n", meta_open, "{\"v\":1,", first_group, bad, "]}", meta_close }));
        try expectRaw(a, try mem.concat(a, u8, &.{ "<!-- overflow\n(Notes)-->\n", meta_open, "{\"v\":2,", first_group, bad, "]}", meta_close, framing, body }));
    }

    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 "v2 hides ghosts and rejects edits or invalid ghost positions without losing the source" {
    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\":2,"));
    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);

    // Even a same-length edit with all offsets still valid cannot relocate a ghost.
    for ([_][]const u8{
        try mem.replaceOwned(u8, arena, bytes, "# Title", "# A Longer Title"),
        try mem.replaceOwned(u8, arena, bytes, "# Title", "# Other"),
        try mem.concat(arena, u8, &.{ bytes, "\n" }),
        try mem.replaceOwned(u8, arena, bytes, "\"at\":30", "\"at\":3000"),
        "<!-- write_away {\"v\":2,\"ghosts\":[{\"at\":0,\"text\":\"ghost\"}]} -->\n\nBody",
    }) |edited| {
        const f = try parse(arena, edited);
        try t.expectEqualStrings(edited, f.body);
        try t.expectEqual(0, f.ghosts.len);
        try t.expectEqual(0, f.groups.len);
        try t.expectEqualStrings("", f.overflow);
        try t.expectEqualStrings(edited, try serialize(arena, f));
    }
}

test "v2 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 mem.replaceOwned(u8, a, no_ghosts, "The tension is", "The strain is");
    try expectRaw(a, gone);
}

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));
}