twig-doc 1.0.0

Parse, query, edit, and losslessly round-trip Djot, Markdown, HTML, and XML documents.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
mod error;
mod ffi;

use std::ops::Range;
use std::os::raw::{c_char, c_int};
use std::ptr::NonNull;

pub use error::Error;
pub use ffi::TwigSpan as Span;

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Format {
    Djot,
    Markdown,
    Xml,
    Html,
}

impl From<Format> for ffi::TwigFormat {
    fn from(value: Format) -> Self {
        match value {
            Format::Djot => ffi::TwigFormat::Djot,
            Format::Markdown => ffi::TwigFormat::Markdown,
            Format::Xml => ffi::TwigFormat::Xml,
            Format::Html => ffi::TwigFormat::Html,
        }
    }
}

/// One node returned by [`Document::query`]: its AST id, byte spans, and kind.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct QueryMatch {
    /// The node's id in the shared AST.
    pub node_id: u32,
    /// The node's whole byte range in the source.
    pub span: Range<usize>,
    /// The node's interior byte range (between its delimiters), or `None` for
    /// a leaf / a container with no known interior.
    pub content_span: Option<Range<usize>>,
    /// The node-kind name (e.g. `"heading"`, `"code_block"`).
    pub kind: String,
}

/// The byte-level effect of an [`Editor`] edit: `old` is the range of the
/// pre-edit source that was replaced, `new` the range the replacement now
/// occupies in the post-edit source (they share a start). An insertion has an
/// empty `old`; a deletion an empty `new`. Everything a caret/selection needs
/// to re-anchor across an edit without re-diffing: shift any offset `>= old.end`
/// by `new.len() - old.len()`.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct Change {
    pub old: Range<usize>,
    pub new: Range<usize>,
}

impl Change {
    /// The net change in source length (`new.len() - old.len()`).
    pub fn delta(&self) -> isize {
        self.new.len() as isize - self.old.len() as isize
    }

    fn from_ffi(c: ffi::TwigChange) -> Self {
        Change {
            old: c.old_span.start..c.old_span.end,
            new: c.new_span.start..c.new_span.end,
        }
    }
}

/// One node of an [`Editor::nodes`] snapshot — the flat AST arena as owned Rust
/// data (the JSON-free read path). `id` indexes the snapshot; `parent`,
/// `first_child`, and `next_sibling` link the tree (`None` where absent).
/// `text` is the node's primary payload (a `str`'s bytes, a `code_block`'s
/// body, …) and `destination` a link/image target, each `None` when the kind
/// carries no such payload.
#[derive(Clone, Debug, Eq, PartialEq)]
pub struct FlatNode {
    pub id: NodeId,
    pub parent: Option<NodeId>,
    pub first_child: Option<NodeId>,
    pub next_sibling: Option<NodeId>,
    pub span: Range<usize>,
    pub content_span: Option<Range<usize>>,
    /// A heading's level; `None` for every other kind.
    pub level: Option<u32>,
    pub kind: String,
    pub text: Option<String>,
    pub destination: Option<String>,
}

/// An inline mark for [`Editor::wrap_range`] / [`Editor::toggle_inline`] — a
/// rich editor's Bold / Italic / Code / … buttons. Markdown spells only
/// [`InlineKind::Strong`], [`InlineKind::Emph`], and [`InlineKind::Verbatim`];
/// Djot spells all of them. An unsupported kind yields [`Error::UnsupportedFormat`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum InlineKind {
    Strong,
    Emph,
    Verbatim,
    Mark,
    Superscript,
    Subscript,
    Insert,
    Delete,
}

impl InlineKind {
    fn to_c(self) -> c_int {
        match self {
            InlineKind::Strong => 0,
            InlineKind::Emph => 1,
            InlineKind::Verbatim => 2,
            InlineKind::Mark => 3,
            InlineKind::Superscript => 4,
            InlineKind::Subscript => 5,
            InlineKind::Insert => 6,
            InlineKind::Delete => 7,
        }
    }
}

/// A block target for [`Editor::set_block`] — the toolbar's H1…H6 / Body switch.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BlockKind {
    Paragraph,
    /// A heading of the given level (1–6; out of range is [`Error::InvalidArgument`]).
    Heading(u32),
}

impl BlockKind {
    /// `(block_kind_code, level)` for the C ABI.
    fn to_c(self) -> (c_int, u32) {
        match self {
            BlockKind::Paragraph => (0, 0),
            BlockKind::Heading(level) => (1, level),
        }
    }
}

#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub struct Version {
    pub major: u8,
    pub minor: u8,
    pub patch: u8,
}

pub fn version() -> Version {
    let packed = unsafe { ffi::twig_version() };
    Version {
        major: (packed >> 16) as u8,
        minor: (packed >> 8) as u8,
        patch: packed as u8,
    }
}

/// The C ABI contract version this crate was **compiled** against — the
/// compile-time counterpart to [`abi_version`] (which reports the **linked
/// library's**). This crate builds and links its own vendored copy of the Zig
/// source, so the two always agree; the pair is exposed so a consumer embedding
/// a separately-built library can verify layout compatibility at load time.
pub const ABI_VERSION: u32 = ffi::TWIG_ABI_VERSION;

/// The C ABI contract version of the linked library. This crate is written
/// against [`ABI_VERSION`]; the two agreeing is what makes the `#[repr(C)]`
/// mirrors in `ffi` sound. It is bumped only on a breaking ABI change (a struct
/// layout change or a renumbered enum value), never on an additive one (a new
/// format code or a new function).
pub fn abi_version() -> u32 {
    unsafe { ffi::twig_abi_version() }
}

pub fn version_string() -> &'static str {
    let ptr = unsafe { ffi::twig_version_string() };
    unsafe { std::ffi::CStr::from_ptr(ptr) }
        .to_str()
        .unwrap_or("")
}

#[derive(Debug)]
pub struct Document {
    raw: NonNull<ffi::TwigDocument>,
}

impl Document {
    pub fn parse(input: &[u8], format: Format) -> Result<Self, Error> {
        let mut raw = std::ptr::null_mut();
        let ffi_format: ffi::TwigFormat = format.into();
        let status = unsafe { ffi::twig_parse(input.as_ptr(), input.len(), ffi_format as i32, &mut raw) };
        Error::from_status(status)?;
        let raw = NonNull::new(raw).ok_or(Error::Internal)?;
        Ok(Self { raw })
    }

    pub fn parse_str(input: &str, format: Format) -> Result<Self, Error> {
        Self::parse(input.as_bytes(), format)
    }

    /// Render the document to HTML. For Djot/Markdown this is the rich
    /// rendering path that resolves reference/footnote side tables.
    pub fn render_html(&mut self) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        collect_bytes(|ptr, len| unsafe { ffi::twig_document_render_html(raw, ptr, len) })
    }

    /// Serialize the document to `format`'s own source syntax: a round-trip
    /// when `format` matches the document's own format, cross-format
    /// conversion otherwise (e.g. parse Markdown, serialize as Djot). Returns
    /// [`Error::UnsupportedFormat`] when the requested direction has no
    /// serializer (today: converting into XML from another format).
    pub fn serialize(&mut self, format: Format) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        let ffi_format: ffi::TwigFormat = format.into();
        collect_bytes(|ptr, len| unsafe {
            ffi::twig_document_serialize(raw, ffi_format as i32, ptr, len)
        })
    }

    /// Encode the document's AST as pretty-printed JSON (the same encoding as
    /// `twig convert -o ast`).
    pub fn ast_json(&mut self) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        collect_bytes(|ptr, len| unsafe { ffi::twig_document_ast_json(raw, ptr, len) })
    }

    /// Resolve a CSS-lite selector (e.g. `heading[level=2]`,
    /// `link[dest^="http"]`, `code`, `list > item`) against the document,
    /// returning one [`QueryMatch`] per matching node in document order. A
    /// malformed selector yields [`Error::InvalidArgument`].
    ///
    /// This is the general replacement for scanning code spans by hand: a
    /// `verbatim` / `code_block` / `raw_inline` / `raw_block` selector recovers
    /// those, and every other node kind is reachable too.
    pub fn query(&mut self, selector: &str) -> Result<Vec<QueryMatch>, Error> {
        let raw = self.raw.as_ptr();
        collect_matches(|ptr, len| unsafe {
            ffi::twig_document_query(raw, selector.as_ptr(), selector.len(), ptr, len)
        })
    }
}

impl Drop for Document {
    fn drop(&mut self) {
        unsafe { ffi::twig_document_destroy(self.raw.as_ptr()) }
    }
}

/// Markdown extensions to enable for an [`Editor`] parse (see
/// [`Editor::new_ext`]). Ignored for non-Markdown formats. Both default off,
/// matching the library.
#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
pub struct MarkdownExtensions {
    /// Generic directives: `:name`, `::name`, `:::name`.
    pub directives: bool,
    /// `$...$` / `$$...$$` math.
    pub math: bool,
}

impl MarkdownExtensions {
    fn to_flags(self) -> u32 {
        let mut flags = 0;
        if self.directives {
            flags |= ffi::TWIG_MD_DIRECTIVES;
        }
        if self.math {
            flags |= ffi::TWIG_MD_MATH;
        }
        flags
    }
}

/// A span-splice editor over a document: applies lossless, in-place edits and
/// reparses after each one, so node addressing stays valid as the document
/// evolves. Every op is addressed by a `locator` — a dot-separated index path
/// (`"0.3.1"`) or a selector that must match exactly one node
/// (`heading("Status")`). A failed edit leaves the document unchanged.
#[derive(Debug)]
pub struct Editor {
    raw: NonNull<ffi::TwigEditor>,
}

impl Editor {
    /// Create an editor over a private copy of `input`, parsed as `format` with
    /// default options.
    pub fn new(input: &[u8], format: Format) -> Result<Self, Error> {
        let mut raw = std::ptr::null_mut();
        let ffi_format: ffi::TwigFormat = format.into();
        let status =
            unsafe { ffi::twig_editor_create(input.as_ptr(), input.len(), ffi_format as i32, &mut raw) };
        Error::from_status(status)?;
        let raw = NonNull::new(raw).ok_or(Error::Internal)?;
        Ok(Self { raw })
    }

    pub fn new_str(input: &str, format: Format) -> Result<Self, Error> {
        Self::new(input.as_bytes(), format)
    }

    /// Like [`Editor::new`], plus Markdown `extensions` to enable (ignored for
    /// other formats). The editor reparses with these after every edit, so a
    /// directive-bearing document stays parseable — needed before
    /// [`Editor::filter`] can match `directive[...]` selectors.
    pub fn new_ext(input: &[u8], format: Format, extensions: MarkdownExtensions) -> Result<Self, Error> {
        let mut raw = std::ptr::null_mut();
        let ffi_format: ffi::TwigFormat = format.into();
        let status = unsafe {
            ffi::twig_editor_create_ext(
                input.as_ptr(),
                input.len(),
                ffi_format as i32,
                extensions.to_flags(),
                &mut raw,
            )
        };
        Error::from_status(status)?;
        let raw = NonNull::new(raw).ok_or(Error::Internal)?;
        Ok(Self { raw })
    }

    /// Replace the whole source of the located node with `text`.
    pub fn replace(&mut self, locator: &str, text: &str) -> Result<(), Error> {
        self.apply(locator, text, |ed, loc, loc_len, txt, txt_len| unsafe {
            ffi::twig_editor_replace(ed, loc, loc_len, txt, txt_len)
        })
    }

    /// Replace the interior (between-delimiters content) of the located
    /// container.
    pub fn replace_content(&mut self, locator: &str, text: &str) -> Result<(), Error> {
        self.apply(locator, text, |ed, loc, loc_len, txt, txt_len| unsafe {
            ffi::twig_editor_replace_content(ed, loc, loc_len, txt, txt_len)
        })
    }

    /// Insert `text` immediately before the located node.
    pub fn insert_before(&mut self, locator: &str, text: &str) -> Result<(), Error> {
        self.apply(locator, text, |ed, loc, loc_len, txt, txt_len| unsafe {
            ffi::twig_editor_insert_before(ed, loc, loc_len, txt, txt_len)
        })
    }

    /// Insert `text` immediately after the located node.
    pub fn insert_after(&mut self, locator: &str, text: &str) -> Result<(), Error> {
        self.apply(locator, text, |ed, loc, loc_len, txt, txt_len| unsafe {
            ffi::twig_editor_insert_after(ed, loc, loc_len, txt, txt_len)
        })
    }

    /// Insert `text` as the `index`-th child of the located container (an index
    /// at or past the child count appends).
    pub fn insert_child(&mut self, locator: &str, index: usize, text: &str) -> Result<(), Error> {
        let status = unsafe {
            ffi::twig_editor_insert_child(
                self.raw.as_ptr(),
                locator.as_ptr(),
                locator.len(),
                index,
                text.as_ptr(),
                text.len(),
            )
        };
        Error::from_status(status)
    }

    /// Delete the located node (removes exactly its span; no whitespace
    /// cleanup).
    pub fn delete(&mut self, locator: &str) -> Result<(), Error> {
        let status = unsafe {
            ffi::twig_editor_delete(self.raw.as_ptr(), locator.as_ptr(), locator.len())
        };
        Error::from_status(status)
    }

    /// Delete the located node, tidying surrounding blank lines for a
    /// whole-line (block) node; an inline node degrades to the exact delete.
    pub fn delete_smart(&mut self, locator: &str) -> Result<(), Error> {
        let status = unsafe {
            ffi::twig_editor_delete_smart(self.raw.as_ptr(), locator.as_ptr(), locator.len())
        };
        Error::from_status(status)
    }

    /// Unwrap the located node: replace it with its interior (drop the wrapper,
    /// keep the children) — e.g. peel a `:::vis{...}` container. A node with no
    /// interior (a leaf, or an empty container) is removed.
    pub fn unwrap_node(&mut self, locator: &str) -> Result<(), Error> {
        let status = unsafe {
            ffi::twig_editor_unwrap(self.raw.as_ptr(), locator.as_ptr(), locator.len())
        };
        Error::from_status(status)
    }

    /// Prune the document in place: remove every node matching the `drop`
    /// selector except those also matching `keep` (`None` spares nothing),
    /// then — if `unwrap_kept` — unwrap the survivors. Read the result with
    /// [`Editor::source`].
    pub fn filter(&mut self, drop: &str, keep: Option<&str>, unwrap_kept: bool) -> Result<(), Error> {
        let (keep_ptr, keep_len) = match keep {
            Some(k) => (k.as_ptr(), k.len()),
            None => (std::ptr::null(), 0),
        };
        let status = unsafe {
            ffi::twig_editor_filter(
                self.raw.as_ptr(),
                drop.as_ptr(),
                drop.len(),
                keep_ptr,
                keep_len,
                unwrap_kept as i32,
            )
        };
        Error::from_status(status)
    }

    /// The editor's current (edited) source bytes.
    pub fn source(&mut self) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        collect_bytes(|ptr, len| unsafe { ffi::twig_editor_source(raw, ptr, len) })
    }

    /// The editor's current source bytes as a UTF-8 string.
    pub fn source_str(&mut self) -> Result<String, Error> {
        String::from_utf8(self.source()?).map_err(|_| Error::Internal)
    }

    /// Encode the editor's current tree as pretty-printed JSON — the live
    /// counterpart of [`Document::ast_json`], for inspecting between edits.
    pub fn ast_json(&mut self) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        collect_bytes(|ptr, len| unsafe { ffi::twig_editor_ast_json(raw, ptr, len) })
    }

    /// Resolve a selector against the editor's current tree — the live
    /// counterpart of [`Document::query`].
    pub fn query(&mut self, selector: &str) -> Result<Vec<QueryMatch>, Error> {
        let raw = self.raw.as_ptr();
        collect_matches(|ptr, len| unsafe {
            ffi::twig_editor_query(raw, selector.as_ptr(), selector.len(), ptr, len)
        })
    }

    // ── offset-addressed editing & read-back ────────────────────────────────

    /// Splice `[start, end)` of the current source with `text`, reparse, and
    /// return the [`Change`] the edit produced — the offset-addressed primitive
    /// a caret editor is built on: a keystroke is `edit_range(c, c, "x")`,
    /// backspace `edit_range(c - 1, c, "")`, a selection replace
    /// `edit_range(a, b, s)`. `start <= end <= ` source length, else
    /// [`Error::InvalidArgument`]. A reparse-breaking edit is rolled back and
    /// returns [`Error::EditConflict`], leaving the document untouched.
    pub fn edit_range(&mut self, start: usize, end: usize, text: &str) -> Result<Change, Error> {
        let mut change = ffi::TwigChange {
            old_span: ffi::TwigSpan { start: 0, end: 0 },
            new_span: ffi::TwigSpan { start: 0, end: 0 },
        };
        let status = unsafe {
            ffi::twig_editor_edit_range(
                self.raw.as_ptr(),
                start,
                end,
                text.as_ptr(),
                text.len(),
                &mut change,
            )
        };
        Error::from_status(status)?;
        Ok(Change::from_ffi(change))
    }

    /// The byte effect of the last successful edit — including the locator ops
    /// ([`Editor::replace`], [`Editor::delete_smart`], …), so any edit can
    /// re-anchor a caret without re-diffing. `None` before the first successful
    /// edit. (A multi-splice op such as [`Editor::filter`] reports only its
    /// final splice.)
    pub fn last_change(&mut self) -> Option<Change> {
        let mut change = ffi::TwigChange {
            old_span: ffi::TwigSpan { start: 0, end: 0 },
            new_span: ffi::TwigSpan { start: 0, end: 0 },
        };
        let status = unsafe { ffi::twig_editor_last_change(self.raw.as_ptr(), &mut change) };
        match status.0 {
            ffi::TwigStatus::OK => Some(Change::from_ffi(change)),
            _ => None,
        }
    }

    /// Undo the last edit step, restoring the previous source and reparsing.
    /// Returns the [`Change`] the undo produced (current → restored) so a caret
    /// can re-anchor, or `None` when there's nothing to undo. History accrues
    /// across every successful edit that funnels through the splice primitive.
    pub fn undo(&mut self) -> Result<Option<Change>, Error> {
        let mut change = ffi::TwigChange {
            old_span: ffi::TwigSpan { start: 0, end: 0 },
            new_span: ffi::TwigSpan { start: 0, end: 0 },
        };
        let status = unsafe { ffi::twig_editor_undo(self.raw.as_ptr(), &mut change) };
        if status.0 == ffi::TwigStatus::NOT_FOUND {
            return Ok(None);
        }
        Error::from_status(status)?;
        Ok(Some(Change::from_ffi(change)))
    }

    /// Redo the most recently undone edit step; the inverse of [`Editor::undo`].
    /// Returns `None` when the redo stack is empty (nothing undone, or a fresh
    /// edit has invalidated it).
    pub fn redo(&mut self) -> Result<Option<Change>, Error> {
        let mut change = ffi::TwigChange {
            old_span: ffi::TwigSpan { start: 0, end: 0 },
            new_span: ffi::TwigSpan { start: 0, end: 0 },
        };
        let status = unsafe { ffi::twig_editor_redo(self.raw.as_ptr(), &mut change) };
        if status.0 == ffi::TwigStatus::NOT_FOUND {
            return Ok(None);
        }
        Error::from_status(status)?;
        Ok(Some(Change::from_ffi(change)))
    }

    /// Fold the most recent edit into the undo step before it, so a caret editor
    /// can coalesce a run of keystrokes into a single undo. Call right after an
    /// `edit_range` that continues a run (same kind, no intervening caret move);
    /// a no-op unless there are at least two steps to merge.
    pub fn coalesce_last_undo(&mut self) -> Result<(), Error> {
        let status = unsafe { ffi::twig_editor_coalesce_last(self.raw.as_ptr()) };
        Error::from_status(status)
    }

    /// Snapshot the current tree as a flat [`FlatNode`] array (the JSON-free
    /// read path for a renderer), indexed so `nodes[i].id == NodeId(i)`. Walk it
    /// via the `parent`/`first_child`/`next_sibling` links; the root is the node
    /// whose `parent` is `None`.
    pub fn nodes(&mut self) -> Result<Vec<FlatNode>, Error> {
        let mut ptr: *const ffi::TwigFlatNode = std::ptr::null();
        let mut len = 0usize;
        let status = unsafe { ffi::twig_editor_nodes(self.raw.as_ptr(), &mut ptr, &mut len) };
        Error::from_status(status)?;
        if len == 0 {
            return Ok(Vec::new());
        }
        if ptr.is_null() {
            return Err(Error::Internal);
        }
        let raw = unsafe { std::slice::from_raw_parts(ptr, len) };
        raw.iter().map(flat_node_from_ffi).collect()
    }

    /// The deepest node whose span contains byte `offset` (with `offset` equal
    /// to the source length treated as inside the root) — mouse hit-testing and
    /// cursor context. `Ok(None)` if no node covers the offset;
    /// [`Error::InvalidArgument`] if `offset` exceeds the source length.
    pub fn node_at(&mut self, offset: usize) -> Result<Option<QueryMatch>, Error> {
        let mut m = ffi::TwigQueryMatch {
            node_id: 0,
            span: ffi::TwigSpan { start: 0, end: 0 },
            content_span: ffi::TwigSpan { start: 0, end: 0 },
            has_content_span: 0,
            kind: std::ptr::null(),
        };
        let status = unsafe { ffi::twig_editor_node_at(self.raw.as_ptr(), offset, &mut m) };
        match status.0 {
            ffi::TwigStatus::OK => Ok(Some(query_match_from_ffi(&m)?)),
            ffi::TwigStatus::NOT_FOUND => Ok(None),
            _ => Err(Error::from_status(status).unwrap_err()),
        }
    }

    /// The chain of nodes containing byte `offset`, root-first down to the
    /// deepest (the node [`Editor::node_at`] returns) — the ancestor path for a
    /// breadcrumb or context-scoped edit. Empty if no node covers the offset.
    pub fn ancestors_at(&mut self, offset: usize) -> Result<Vec<QueryMatch>, Error> {
        let mut ptr: *const ffi::TwigQueryMatch = std::ptr::null();
        let mut len = 0usize;
        let status =
            unsafe { ffi::twig_editor_nodes_at(self.raw.as_ptr(), offset, &mut ptr, &mut len) };
        match status.0 {
            ffi::TwigStatus::OK => {}
            ffi::TwigStatus::NOT_FOUND => return Ok(Vec::new()),
            _ => return Err(Error::from_status(status).unwrap_err()),
        }
        if len == 0 || ptr.is_null() {
            return Ok(Vec::new());
        }
        let raw = unsafe { std::slice::from_raw_parts(ptr, len) };
        raw.iter().map(query_match_from_ffi).collect()
    }

    // ── range-oriented rich-text ops (the toolbar) ──────────────────────────

    /// Wrap `[start, end)` with `kind`'s delimiters — the unconditional half of
    /// the inline toolbar (always adds a mark; `*word*` → `**word**` stacks).
    /// [`Error::UnsupportedFormat`] if the document's format can't spell `kind`
    /// (e.g. a Markdown [`InlineKind::Mark`]); [`Error::InvalidArgument`] for a
    /// bad range; [`Error::EditConflict`] if the result doesn't reparse.
    pub fn wrap_range(&mut self, start: usize, end: usize, kind: InlineKind) -> Result<Change, Error> {
        self.change_op(|ed, out| unsafe {
            ffi::twig_editor_wrap_range(ed, start, end, kind.to_c(), out)
        })
    }

    /// Toggle `kind` over `[start, end)`: remove the mark if the range already
    /// *is* a node of `kind` (its whole span or its rendered interior), else
    /// wrap it — a rich editor's Cmd-B. Same error rules as
    /// [`Editor::wrap_range`].
    pub fn toggle_inline(&mut self, start: usize, end: usize, kind: InlineKind) -> Result<Change, Error> {
        self.change_op(|ed, out| unsafe {
            ffi::twig_editor_toggle_inline(ed, start, end, kind.to_c(), out)
        })
    }

    /// Convert the innermost heading/paragraph covering byte `offset` to `kind`,
    /// rewriting its leading marker while keeping its inline content (the
    /// toolbar's H1…H6 / Body switch). Djot and Markdown only, else
    /// [`Error::UnsupportedFormat`]; [`Error::NotFound`] if no heading/paragraph
    /// covers `offset`; [`Error::InvalidArgument`] for a heading level outside
    /// 1–6.
    pub fn set_block(&mut self, offset: usize, kind: BlockKind) -> Result<Change, Error> {
        let (block_kind, level) = kind.to_c();
        self.change_op(|ed, out| unsafe {
            ffi::twig_editor_set_block(ed, offset, block_kind, level, out)
        })
    }

    /// Shared plumbing for the change-returning ops: run `op` (which fills a
    /// `TwigChange` out-param) and wrap the result.
    fn change_op(
        &mut self,
        op: impl FnOnce(*mut ffi::TwigEditor, *mut ffi::TwigChange) -> ffi::TwigStatus,
    ) -> Result<Change, Error> {
        let mut change = ffi::TwigChange {
            old_span: ffi::TwigSpan { start: 0, end: 0 },
            new_span: ffi::TwigSpan { start: 0, end: 0 },
        };
        let status = op(self.raw.as_ptr(), &mut change);
        Error::from_status(status)?;
        Ok(Change::from_ffi(change))
    }

    /// Shared plumbing for the `(locator, text)` edit ops.
    fn apply(
        &mut self,
        locator: &str,
        text: &str,
        op: impl FnOnce(*mut ffi::TwigEditor, *const u8, usize, *const u8, usize) -> ffi::TwigStatus,
    ) -> Result<(), Error> {
        let status = op(
            self.raw.as_ptr(),
            locator.as_ptr(),
            locator.len(),
            text.as_ptr(),
            text.len(),
        );
        Error::from_status(status)
    }
}

impl Drop for Editor {
    fn drop(&mut self) {
        unsafe { ffi::twig_editor_destroy(self.raw.as_ptr()) }
    }
}

/// Run `call` (which writes a borrowed `(ptr, len)` byte buffer) and copy the
/// result into an owned `Vec` — the buffer is only valid until the next
/// same-accessor call on the handle, so we copy before returning. Shared by
/// [`Document`] and [`Editor`].
fn collect_bytes(
    call: impl FnOnce(*mut *const u8, *mut usize) -> ffi::TwigStatus,
) -> Result<Vec<u8>, Error> {
    let mut ptr = std::ptr::null();
    let mut len = 0usize;
    let status = call(&mut ptr, &mut len);
    Error::from_status(status)?;
    if len == 0 {
        return Ok(Vec::new());
    }
    if ptr.is_null() {
        return Err(Error::Internal);
    }
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    Ok(bytes.to_vec())
}

/// Run `call` (which writes a borrowed `(ptr, len)` match array) and copy each
/// match into an owned [`QueryMatch`]. Shared by [`Document`] and [`Editor`].
fn collect_matches(
    call: impl FnOnce(*mut *const ffi::TwigQueryMatch, *mut usize) -> ffi::TwigStatus,
) -> Result<Vec<QueryMatch>, Error> {
    let mut ptr = std::ptr::null();
    let mut len = 0usize;
    let status = call(&mut ptr, &mut len);
    Error::from_status(status)?;
    if len == 0 {
        return Ok(Vec::new());
    }
    if ptr.is_null() {
        return Err(Error::Internal);
    }
    let matches = unsafe { std::slice::from_raw_parts(ptr, len) };
    matches.iter().map(query_match_from_ffi).collect()
}

/// Copy a borrowed C ABI [`ffi::TwigQueryMatch`] into an owned [`QueryMatch`].
/// Shared by `collect_matches`, [`Editor::node_at`], and [`Editor::ancestors_at`].
fn query_match_from_ffi(m: &ffi::TwigQueryMatch) -> Result<QueryMatch, Error> {
    Ok(QueryMatch {
        node_id: m.node_id,
        span: m.span.start..m.span.end,
        content_span: if m.has_content_span != 0 {
            Some(m.content_span.start..m.content_span.end)
        } else {
            None
        },
        kind: borrowed_cstr(m.kind)?,
    })
}

/// Copy a borrowed C ABI [`ffi::TwigFlatNode`] into an owned [`FlatNode`].
fn flat_node_from_ffi(n: &ffi::TwigFlatNode) -> Result<FlatNode, Error> {
    let node_id = |v: u32| if v == ffi::TWIG_NO_NODE { None } else { Some(NodeId(v)) };
    Ok(FlatNode {
        id: NodeId(n.id),
        parent: node_id(n.parent),
        first_child: node_id(n.first_child),
        next_sibling: node_id(n.next_sibling),
        span: n.span.start..n.span.end,
        content_span: if n.has_content_span != 0 {
            Some(n.content_span.start..n.content_span.end)
        } else {
            None
        },
        level: if n.level != 0 { Some(n.level) } else { None },
        kind: borrowed_cstr(n.kind)?,
        text: borrowed_bytes(n.text_ptr, n.text_len),
        destination: borrowed_bytes(n.destination_ptr, n.destination_len),
    })
}

/// Copy a NUL-terminated, library-owned C string into an owned `String`.
fn borrowed_cstr(ptr: *const c_char) -> Result<String, Error> {
    if ptr.is_null() {
        return Err(Error::Internal);
    }
    Ok(unsafe { std::ffi::CStr::from_ptr(ptr) }
        .to_str()
        .map_err(|_| Error::Internal)?
        .to_owned())
}

/// Copy a borrowed `(ptr, len)` payload slice into an owned `String`, or `None`
/// for a NULL pointer (the kind carries no such payload). The bytes are a slice
/// of a UTF-8 document, so a lossy decode never actually substitutes.
fn borrowed_bytes(ptr: *const u8, len: usize) -> Option<String> {
    if ptr.is_null() {
        return None;
    }
    let bytes = unsafe { std::slice::from_raw_parts(ptr, len) };
    Some(String::from_utf8_lossy(bytes).into_owned())
}

/// The id of a node added to a [`Builder`], returned by every `add*` method and
/// used to wire up the tree via [`Builder::set_children`] and to root a
/// render/serialize/query.
#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
pub struct NodeId(pub u32);

/// The void-payload node kinds, addable via [`Builder::add`]. Kinds with a
/// payload have their own dedicated `add_*` method instead.
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum VoidKind {
    Doc,
    Para,
    ThematicBreak,
    Section,
    Div,
    BlockQuote,
    DefinitionList,
    Table,
    ListItem,
    DefinitionListItem,
    Term,
    Definition,
    Caption,
    SoftBreak,
    HardBreak,
    NonBreakingSpace,
    Emph,
    Strong,
    Span,
    Mark,
    Superscript,
    Subscript,
    Insert,
    Delete,
    DoubleQuoted,
    SingleQuoted,
}

impl VoidKind {
    fn to_c(self) -> c_int {
        // Discriminants match `TwigNodeKind` in the C ABI.
        match self {
            VoidKind::Doc => 0,
            VoidKind::Para => 1,
            VoidKind::ThematicBreak => 3,
            VoidKind::Section => 4,
            VoidKind::Div => 5,
            VoidKind::BlockQuote => 9,
            VoidKind::DefinitionList => 13,
            VoidKind::Table => 14,
            VoidKind::ListItem => 15,
            VoidKind::DefinitionListItem => 17,
            VoidKind::Term => 18,
            VoidKind::Definition => 19,
            VoidKind::Caption => 22,
            VoidKind::SoftBreak => 26,
            VoidKind::HardBreak => 27,
            VoidKind::NonBreakingSpace => 28,
            VoidKind::Emph => 38,
            VoidKind::Strong => 39,
            VoidKind::Span => 42,
            VoidKind::Mark => 43,
            VoidKind::Superscript => 44,
            VoidKind::Subscript => 45,
            VoidKind::Insert => 46,
            VoidKind::Delete => 47,
            VoidKind::DoubleQuoted => 48,
            VoidKind::SingleQuoted => 49,
        }
    }
}

/// The single-string-payload node kinds, addable via [`Builder::add_text`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum TextKind {
    Str,
    Symb,
    Verbatim,
    InlineMath,
    DisplayMath,
    Url,
    Email,
    FootnoteReference,
    Comment,
    Doctype,
    Cdata,
}

impl TextKind {
    fn to_c(self) -> c_int {
        match self {
            TextKind::Str => 25,
            TextKind::Symb => 29,
            TextKind::Verbatim => 30,
            TextKind::InlineMath => 32,
            TextKind::DisplayMath => 33,
            TextKind::Url => 34,
            TextKind::Email => 35,
            TextKind::FootnoteReference => 36,
            TextKind::Comment => 52,
            TextKind::Doctype => 53,
            TextKind::Cdata => 55,
        }
    }
}

/// Bullet marker style for [`Builder::add_bullet_list`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum BulletStyle {
    Dash,
    Plus,
    Star,
}

impl BulletStyle {
    fn to_c(self) -> c_int {
        match self {
            BulletStyle::Dash => 0,
            BulletStyle::Plus => 1,
            BulletStyle::Star => 2,
        }
    }
}

/// Numbering scheme for [`Builder::add_ordered_list`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OrderedNumbering {
    Decimal,
    LowerAlpha,
    UpperAlpha,
    LowerRoman,
    UpperRoman,
}

impl OrderedNumbering {
    fn to_c(self) -> c_int {
        match self {
            OrderedNumbering::Decimal => 0,
            OrderedNumbering::LowerAlpha => 1,
            OrderedNumbering::UpperAlpha => 2,
            OrderedNumbering::LowerRoman => 3,
            OrderedNumbering::UpperRoman => 4,
        }
    }
}

/// Delimiter around an ordered-list number (`1.`, `1)`, `(1)`).
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum OrderedDelim {
    Period,
    ParenAfter,
    ParenBoth,
}

impl OrderedDelim {
    fn to_c(self) -> c_int {
        match self {
            OrderedDelim::Period => 0,
            OrderedDelim::ParenAfter => 1,
            OrderedDelim::ParenBoth => 2,
        }
    }
}

/// Table-cell alignment for [`Builder::add_cell`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum Alignment {
    Default,
    Left,
    Right,
    Center,
}

impl Alignment {
    fn to_c(self) -> c_int {
        match self {
            Alignment::Default => 0,
            Alignment::Left => 1,
            Alignment::Right => 2,
            Alignment::Center => 3,
        }
    }
}

/// The smart-punctuation kind for [`Builder::add_smart_punctuation`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum SmartPunctuation {
    LeftSingleQuote,
    RightSingleQuote,
    LeftDoubleQuote,
    RightDoubleQuote,
    Ellipses,
    EmDash,
    EnDash,
}

impl SmartPunctuation {
    fn to_c(self) -> c_int {
        match self {
            SmartPunctuation::LeftSingleQuote => 0,
            SmartPunctuation::RightSingleQuote => 1,
            SmartPunctuation::LeftDoubleQuote => 2,
            SmartPunctuation::RightDoubleQuote => 3,
            SmartPunctuation::Ellipses => 4,
            SmartPunctuation::EmDash => 5,
            SmartPunctuation::EnDash => 6,
        }
    }
}

/// The surface form of a generic directive for [`Builder::add_directive`].
#[derive(Clone, Copy, Debug, Eq, PartialEq)]
pub enum DirectiveForm {
    Text,
    Leaf,
    Container,
}

impl DirectiveForm {
    fn to_c(self) -> c_int {
        match self {
            DirectiveForm::Text => 0,
            DirectiveForm::Leaf => 1,
            DirectiveForm::Container => 2,
        }
    }
}

/// Decompose an optional string into `(ptr, len, has)` for the C ABI's
/// `(ptr, len, has_*)` optional-string triples. The pointer borrows `s` and is
/// only used within the same call.
fn opt_str(s: Option<&str>) -> (*const u8, usize, c_int) {
    match s {
        Some(x) => (x.as_ptr(), x.len(), 1),
        None => (std::ptr::null(), 0, 0),
    }
}

/// Programmatic construction of a document — the write-path mirror of
/// [`Document::parse`]. Build the tree bottom-up (add children, then the
/// container, wiring them with [`Builder::set_children`]); every `add*` method
/// returns the new node's [`NodeId`]. Then render, serialize, query, or dump the
/// subtree rooted at any id, on demand, without consuming the builder. All input
/// strings are copied, so caller buffers need not outlive a call.
#[derive(Debug)]
pub struct Builder {
    raw: NonNull<ffi::TwigBuilder>,
}

impl Builder {
    /// Create an empty builder.
    pub fn new() -> Result<Self, Error> {
        let mut raw = std::ptr::null_mut();
        let status = unsafe { ffi::twig_builder_create(&mut raw) };
        Error::from_status(status)?;
        let raw = NonNull::new(raw).ok_or(Error::Internal)?;
        Ok(Self { raw })
    }

    /// Add a void-payload node (attach children later with
    /// [`Builder::set_children`]).
    pub fn add(&mut self, kind: VoidKind) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add(b, kind.to_c(), out) })
    }

    /// Add a single-string-payload node (a `str`, code span, url, comment, …).
    pub fn add_text(&mut self, kind: TextKind, text: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_text(b, kind.to_c(), text.as_ptr(), text.len(), out) })
    }

    /// Add a heading of the given level (attach its inline children afterward).
    pub fn add_heading(&mut self, level: u32) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_heading(b, level, out) })
    }

    /// Add a code block, with an optional info-string language.
    pub fn add_code_block(&mut self, lang: Option<&str>, text: &str) -> Result<NodeId, Error> {
        let (lp, ll, has) = opt_str(lang);
        self.emit(|b, out| unsafe { ffi::twig_builder_add_code_block(b, lp, ll, has, text.as_ptr(), text.len(), out) })
    }

    /// Add a raw block targeting `format` (e.g. `"html"`).
    pub fn add_raw_block(&mut self, format: &str, text: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_raw_block(b, format.as_ptr(), format.len(), text.as_ptr(), text.len(), out)
        })
    }

    /// Add a document-metadata block written in config language `lang`.
    pub fn add_metadata(&mut self, lang: &str, text: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_metadata(b, lang.as_ptr(), lang.len(), text.as_ptr(), text.len(), out)
        })
    }

    /// Add a raw inline targeting `format`.
    pub fn add_raw_inline(&mut self, format: &str, text: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_raw_inline(b, format.as_ptr(), format.len(), text.as_ptr(), text.len(), out)
        })
    }

    /// Add a smart-punctuation node standing for `text` (its source spelling).
    pub fn add_smart_punctuation(&mut self, kind: SmartPunctuation, text: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_smart_punctuation(b, kind.to_c(), text.as_ptr(), text.len(), out)
        })
    }

    /// Add a link with an optional destination and/or reference label (attach
    /// the link text as children).
    pub fn add_link(&mut self, destination: Option<&str>, reference: Option<&str>) -> Result<NodeId, Error> {
        let (dp, dl, hd) = opt_str(destination);
        let (rp, rl, hr) = opt_str(reference);
        self.emit(|b, out| unsafe { ffi::twig_builder_add_link(b, dp, dl, hd, rp, rl, hr, out) })
    }

    /// Add an image — like [`Builder::add_link`], but children are the alt text.
    pub fn add_image(&mut self, destination: Option<&str>, reference: Option<&str>) -> Result<NodeId, Error> {
        let (dp, dl, hd) = opt_str(destination);
        let (rp, rl, hr) = opt_str(reference);
        self.emit(|b, out| unsafe { ffi::twig_builder_add_image(b, dp, dl, hd, rp, rl, hr, out) })
    }

    /// Add a generic directive of the given form and name.
    pub fn add_directive(&mut self, form: DirectiveForm, name: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_directive(b, form.to_c(), name.as_ptr(), name.len(), out) })
    }

    /// Add a generic named element (the escape hatch for HTML/XML tags).
    pub fn add_element(&mut self, name: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_element(b, name.as_ptr(), name.len(), out) })
    }

    /// Add an XML processing instruction (`<?target data?>`).
    pub fn add_processing_instruction(&mut self, target: &str, data: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_processing_instruction(b, target.as_ptr(), target.len(), data.as_ptr(), data.len(), out)
        })
    }

    /// Add a footnote definition with the given label.
    pub fn add_footnote(&mut self, label: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_footnote(b, label.as_ptr(), label.len(), out) })
    }

    /// Add a link/image reference definition (`label` → `destination`).
    pub fn add_reference(&mut self, label: &str, destination: &str) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_reference(b, label.as_ptr(), label.len(), destination.as_ptr(), destination.len(), out)
        })
    }

    /// Add a bullet list.
    pub fn add_bullet_list(&mut self, style: BulletStyle, tight: bool) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_bullet_list(b, style.to_c(), tight as c_int, out) })
    }

    /// Add an ordered list, with an optional explicit start number.
    pub fn add_ordered_list(
        &mut self,
        numbering: OrderedNumbering,
        delim: OrderedDelim,
        tight: bool,
        start: Option<u32>,
    ) -> Result<NodeId, Error> {
        let (start_val, has_start) = match start {
            Some(s) => (s, 1),
            None => (0, 0),
        };
        self.emit(|b, out| unsafe {
            ffi::twig_builder_add_ordered_list(b, numbering.to_c(), delim.to_c(), tight as c_int, start_val, has_start, out)
        })
    }

    /// Add a task list.
    pub fn add_task_list(&mut self, tight: bool) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_task_list(b, tight as c_int, out) })
    }

    /// Add a task-list item with the given checkbox state.
    pub fn add_task_list_item(&mut self, checked: bool) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_task_list_item(b, checked as c_int, out) })
    }

    /// Add a table row (`head` marks a header row).
    pub fn add_row(&mut self, head: bool) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_row(b, head as c_int, out) })
    }

    /// Add a table cell (`head` marks a header cell).
    pub fn add_cell(&mut self, head: bool, alignment: Alignment) -> Result<NodeId, Error> {
        self.emit(|b, out| unsafe { ffi::twig_builder_add_cell(b, head as c_int, alignment.to_c(), out) })
    }

    /// Set `parent`'s children to `children` (in order), replacing any it had.
    /// Each child id should appear in exactly one `set_children` call.
    pub fn set_children(&mut self, parent: NodeId, children: &[NodeId]) -> Result<(), Error> {
        let ids: Vec<u32> = children.iter().map(|n| n.0).collect();
        let status = unsafe { ffi::twig_builder_set_children(self.raw.as_ptr(), parent.0, ids.as_ptr(), ids.len()) };
        Error::from_status(status)
    }

    /// Attach `{...}` attributes to `id` (`(key, Some(value))`, or
    /// `(key, None)` for a bare attribute), replacing any it had. An empty slice
    /// clears them.
    pub fn set_attrs(&mut self, id: NodeId, attrs: &[(&str, Option<&str>)]) -> Result<(), Error> {
        let kvs: Vec<ffi::TwigKeyVal> = attrs
            .iter()
            .map(|(k, v)| ffi::TwigKeyVal {
                key: k.as_ptr(),
                key_len: k.len(),
                value: v.map_or(std::ptr::null(), |s| s.as_ptr()),
                value_len: v.map_or(0, |s| s.len()),
            })
            .collect();
        let status = unsafe { ffi::twig_builder_set_attrs(self.raw.as_ptr(), id.0, kvs.as_ptr(), kvs.len()) };
        Error::from_status(status)
    }

    /// Render the subtree rooted at `root` to HTML (generic whole-vocabulary
    /// printer — a built tree has no djot/Markdown side tables).
    pub fn render_html(&mut self, root: NodeId) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        collect_bytes(|ptr, len| unsafe { ffi::twig_builder_render_html(raw, root.0, ptr, len) })
    }

    /// Serialize the subtree rooted at `root` to `format`'s source syntax.
    /// Returns [`Error::UnsupportedFormat`] when the target can't represent the
    /// built tree (e.g. semantic kinds into XML).
    pub fn serialize(&mut self, root: NodeId, format: Format) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        let ffi_format: ffi::TwigFormat = format.into();
        collect_bytes(|ptr, len| unsafe { ffi::twig_builder_serialize(raw, root.0, ffi_format as i32, ptr, len) })
    }

    /// Encode the subtree rooted at `root` as pretty-printed JSON.
    pub fn ast_json(&mut self, root: NodeId) -> Result<Vec<u8>, Error> {
        let raw = self.raw.as_ptr();
        collect_bytes(|ptr, len| unsafe { ffi::twig_builder_ast_json(raw, root.0, ptr, len) })
    }

    /// Resolve a selector against the subtree rooted at `root` (same grammar as
    /// [`Document::query`]).
    pub fn query(&mut self, root: NodeId, selector: &str) -> Result<Vec<QueryMatch>, Error> {
        let raw = self.raw.as_ptr();
        collect_matches(|ptr, len| unsafe {
            ffi::twig_builder_query(raw, root.0, selector.as_ptr(), selector.len(), ptr, len)
        })
    }

    /// Shared plumbing for the `add*` constructors: run `call` (which writes the
    /// new node's id) and wrap the result.
    fn emit(
        &mut self,
        call: impl FnOnce(*mut ffi::TwigBuilder, *mut u32) -> ffi::TwigStatus,
    ) -> Result<NodeId, Error> {
        let mut id: u32 = 0;
        let status = call(self.raw.as_ptr(), &mut id);
        Error::from_status(status)?;
        Ok(NodeId(id))
    }
}

impl Drop for Builder {
    fn drop(&mut self) {
        unsafe { ffi::twig_builder_destroy(self.raw.as_ptr()) }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn abi_version_matches() {
        // The linked library must speak the exact ABI layout this crate's
        // `#[repr(C)]` mirrors assume. If this fails, the Zig `TWIG_ABI_VERSION`
        // was bumped without updating `ffi::TWIG_ABI_VERSION` (and the mirrors).
        assert_eq!(abi_version(), ffi::TWIG_ABI_VERSION);
    }

    #[test]
    fn parses_and_renders_markdown_html() {
        let mut doc = Document::parse_str("# hi\n", Format::Markdown).expect("parse markdown");
        let html = doc.render_html().expect("render html");
        assert_eq!(String::from_utf8_lossy(&html), "<h1>hi</h1>\n");
    }

    #[test]
    fn parses_html_input() {
        let mut doc = Document::parse_str("<p>hi</p>", Format::Html).expect("parse html");
        let html = doc.render_html().expect("render html");
        assert!(String::from_utf8_lossy(&html).contains("hi"));
    }

    #[test]
    fn serialize_round_trips_and_cross_converts() {
        let mut doc = Document::parse_str("# hi\n", Format::Markdown).expect("parse markdown");

        let canonical = doc.serialize(Format::Markdown).expect("serialize markdown");
        assert!(String::from_utf8_lossy(&canonical).contains("# hi"));

        // Cross-format Markdown -> XML has no serializer.
        assert_eq!(doc.serialize(Format::Xml), Err(Error::UnsupportedFormat));
    }

    #[test]
    fn serialize_markdown_to_djot() {
        let mut doc =
            Document::parse_str("This is *markdown*.\n", Format::Markdown).expect("parse markdown");
        let djot = doc.serialize(Format::Djot).expect("serialize djot");
        assert!(String::from_utf8_lossy(&djot).contains("_markdown_"));
    }

    #[test]
    fn ast_json_dumps_the_tree() {
        let mut doc = Document::parse_str("hello\n", Format::Djot).expect("parse djot");
        let json = doc.ast_json().expect("ast json");
        assert!(String::from_utf8_lossy(&json).contains("\"kind\": \"doc\""));
    }

    #[test]
    fn query_finds_nodes_by_selector() {
        let source = "# One\n\n## Two\n";
        let mut doc = Document::parse_str(source, Format::Markdown).expect("parse markdown");
        let matches = doc.query("heading").expect("query");

        assert_eq!(matches.len(), 2);
        for m in &matches {
            assert_eq!(m.kind, "heading");
            assert!(m.span.start < m.span.end);
        }
    }

    #[test]
    fn query_recovers_code_spans() {
        let source = "prose `code` more prose\n";
        let mut doc = Document::parse_str(source, Format::Markdown).expect("parse markdown");
        let matches = doc.query("verbatim").expect("query");

        assert_eq!(matches.len(), 1);
        assert_eq!(&source[matches[0].span.clone()], "`code`");
    }

    #[test]
    fn query_rejects_a_malformed_selector() {
        let mut doc = Document::parse_str("hi\n", Format::Markdown).expect("parse markdown");
        assert_eq!(doc.query("list >"), Err(Error::InvalidArgument));
    }

    #[test]
    fn editor_edits_by_index_path() {
        let mut ed = Editor::new_str("<a><b>hi</b></a>", Format::Xml).expect("editor");
        ed.replace_content("0.0", "bye").expect("replace_content");
        assert_eq!(ed.source_str().expect("source"), "<a><b>bye</b></a>");
    }

    #[test]
    fn editor_insert_child_and_delete() {
        let mut ed = Editor::new_str("<r><a/><c/></r>", Format::Xml).expect("editor");
        ed.insert_child("0", 1, "<b/>").expect("insert_child");
        assert_eq!(ed.source_str().expect("source"), "<r><a/><b/><c/></r>");
        ed.delete("0.1").expect("delete");
        assert_eq!(ed.source_str().expect("source"), "<r><a/><c/></r>");
    }

    #[test]
    fn editor_edits_by_selector() {
        let mut ed = Editor::new_str("# One\n\n## Two\n", Format::Markdown).expect("editor");
        ed.replace("heading(\"Two\")", "## Renamed").expect("replace");
        assert_eq!(ed.source_str().expect("source"), "# One\n\n## Renamed\n");
    }

    #[test]
    fn editor_locator_errors_are_distinct() {
        let mut ed = Editor::new_str("<r><a/><a/></r>", Format::Xml).expect("editor");
        assert_eq!(ed.replace("0.9", "x"), Err(Error::NotFound));
        assert_eq!(ed.replace("element", "x"), Err(Error::Ambiguous));
        assert_eq!(ed.replace("element(", "x"), Err(Error::InvalidArgument));
        // Untouched by the failed edits.
        assert_eq!(ed.source_str().expect("source"), "<r><a/><a/></r>");
    }

    #[test]
    fn editor_reparse_break_rolls_back() {
        let mut ed = Editor::new_str("<a>ok</a>", Format::Xml).expect("editor");
        assert_eq!(ed.replace_content("0", "<b>"), Err(Error::EditConflict));
        assert_eq!(ed.source_str().expect("source"), "<a>ok</a>");
    }

    #[test]
    fn editor_leaf_content_is_not_editable() {
        let mut ed = Editor::new_str("<a>hi</a>", Format::Xml).expect("editor");
        assert_eq!(ed.replace_content("0.0", "x"), Err(Error::NotEditable));
    }

    #[test]
    fn editor_query_reflects_current_tree() {
        let mut ed = Editor::new_str("<r><a/></r>", Format::Xml).expect("editor");
        ed.insert_child("0", 1, "<b/>").expect("insert_child");
        // Root <r> plus <a/> and <b/>.
        assert_eq!(ed.query("element").expect("query").len(), 3);
        let json = ed.ast_json().expect("ast_json");
        assert!(String::from_utf8_lossy(&json).contains("\"kind\": \"doc\""));
    }

    // ── offset-addressed editing & read-back (P0–P3) ────────────────────────

    #[test]
    fn editor_edit_range_types_backspaces_and_reports_change() {
        let mut ed = Editor::new_str("ab\n", Format::Markdown).expect("editor");

        // Type "X" at offset 1 (a zero-width splice = an insertion).
        let c = ed.edit_range(1, 1, "X").expect("edit_range insert");
        assert_eq!(ed.source_str().unwrap(), "aXb\n");
        assert_eq!(c.old, 1..1);
        assert_eq!(c.new, 1..2);
        assert_eq!(c.delta(), 1);

        // Backspace it (delete the "X").
        let c2 = ed.edit_range(1, 2, "").expect("edit_range delete");
        assert_eq!(ed.source_str().unwrap(), "ab\n");
        assert_eq!(c2.old, 1..2);
        assert_eq!(c2.new, 1..1);
        assert_eq!(c2.delta(), -1);
    }

    #[test]
    fn editor_edit_range_rejects_bad_ranges() {
        let mut ed = Editor::new_str("hi\n", Format::Markdown).expect("editor");
        assert_eq!(ed.edit_range(0, 99, "x"), Err(Error::InvalidArgument)); // end past len
        assert_eq!(ed.edit_range(2, 1, "x"), Err(Error::InvalidArgument)); // start > end
        assert_eq!(ed.source_str().unwrap(), "hi\n"); // untouched
    }

    #[test]
    fn editor_last_change_reports_locator_ops_too() {
        let mut ed = Editor::new_str("# One\n\n## Two\n", Format::Markdown).expect("editor");
        assert_eq!(ed.last_change(), None); // nothing edited yet

        ed.replace("heading(\"Two\")", "## Renamed").expect("replace");
        assert_eq!(ed.source_str().unwrap(), "# One\n\n## Renamed\n");
        let c = ed.last_change().expect("a change was recorded");
        // "## Two" occupied [7,13); "## Renamed" (10 bytes) now occupies [7,17).
        assert_eq!(c.old, 7..13);
        assert_eq!(c.new, 7..17);
    }

    #[test]
    fn editor_nodes_is_a_walkable_flat_tree() {
        let mut ed = Editor::new_str("# Hi\n\ntext\n", Format::Markdown).expect("editor");
        let nodes = ed.nodes().expect("nodes");
        assert!(!nodes.is_empty());

        // Dense, index-aligned ids.
        for (i, n) in nodes.iter().enumerate() {
            assert_eq!(n.id, NodeId(i as u32));
        }
        // Exactly one root (no parent), and it's the doc.
        let roots: Vec<_> = nodes.iter().filter(|n| n.parent.is_none()).collect();
        assert_eq!(roots.len(), 1);
        assert_eq!(roots[0].kind, "doc");

        // The heading carries its level; the "Hi" text is reachable as a payload.
        let heading = nodes.iter().find(|n| n.kind == "heading").expect("a heading");
        assert_eq!(heading.level, Some(1));
        assert!(nodes.iter().any(|n| n.text.as_deref() == Some("Hi")));

        // Every non-root node's parent links back to a node that lists it as a
        // child (via first_child/next_sibling).
        for n in nodes.iter().filter(|n| n.parent.is_some()) {
            let p = &nodes[n.parent.unwrap().0 as usize];
            let mut kid = p.first_child;
            let mut seen = false;
            while let Some(NodeId(k)) = kid {
                if k == n.id.0 {
                    seen = true;
                    break;
                }
                kid = nodes[k as usize].next_sibling;
            }
            assert!(seen, "node {:?} not found among its parent's children", n.id);
        }
    }

    #[test]
    fn editor_node_at_and_ancestors_hit_test_offsets() {
        let mut ed = Editor::new_str("# Hi\n\ntext\n", Format::Markdown).expect("editor");

        // Offset 2 is the "H" of the heading "# Hi" [0,4).
        let m = ed.node_at(2).expect("node_at").expect("a node covers offset 2");
        assert!(m.span.contains(&2));

        // The ancestor chain is root-first and ends at the deepest (== node_at).
        let chain = ed.ancestors_at(2).expect("ancestors_at");
        assert!(!chain.is_empty());
        assert_eq!(chain[0].kind, "doc");
        assert_eq!(chain.last().unwrap().node_id, m.node_id);

        // An out-of-range offset is an error; a gap covers nothing deeper than doc.
        assert_eq!(ed.node_at(999), Err(Error::InvalidArgument));
    }

    // ── range-oriented rich-text ops (P5) ───────────────────────────────────

    #[test]
    fn editor_wrap_and_toggle_inline_round_trip() {
        let mut ed = Editor::new_str("a word b\n", Format::Markdown).expect("editor");

        // Bold "word" [2,6); the Change reports the new "**word**" region.
        let c = ed.wrap_range(2, 6, InlineKind::Strong).expect("wrap");
        assert_eq!(ed.source_str().unwrap(), "a **word** b\n");
        assert_eq!(&ed.source_str().unwrap()[c.new.clone()], "**word**");

        // Toggle it off by selecting the strong node's interior [4,8).
        ed.toggle_inline(4, 8, InlineKind::Strong).expect("toggle off");
        assert_eq!(ed.source_str().unwrap(), "a word b\n");

        // Toggle emphasis on when the range isn't already marked.
        ed.toggle_inline(2, 6, InlineKind::Emph).expect("toggle on");
        assert_eq!(ed.source_str().unwrap(), "a *word* b\n");
    }

    #[test]
    fn editor_inline_kind_support_is_format_specific() {
        // Markdown has no highlight/mark spelling.
        let mut md = Editor::new_str("a word b\n", Format::Markdown).expect("editor");
        assert_eq!(md.wrap_range(2, 6, InlineKind::Mark), Err(Error::UnsupportedFormat));

        // Djot spells it {=…=}.
        let mut dj = Editor::new_str("a word b\n", Format::Djot).expect("editor");
        dj.wrap_range(2, 6, InlineKind::Mark).expect("djot mark");
        assert_eq!(dj.source_str().unwrap(), "a {=word=} b\n");
    }

    #[test]
    fn editor_toggle_strips_verbatim_without_content_span() {
        let mut ed = Editor::new_str("a `code` b\n", Format::Markdown).expect("editor");
        // The verbatim node [2,8) has no content_span; toggle peels the backticks.
        ed.toggle_inline(2, 8, InlineKind::Verbatim).expect("toggle code off");
        assert_eq!(ed.source_str().unwrap(), "a code b\n");
    }

    #[test]
    fn editor_set_block_switches_para_and_heading_levels() {
        let mut ed = Editor::new_str("Title\n\nbody text\n", Format::Markdown).expect("editor");

        // Paragraph -> H2 (offset 0 is inside "Title").
        ed.set_block(0, BlockKind::Heading(2)).expect("to h2");
        assert_eq!(ed.source_str().unwrap(), "## Title\n\nbody text\n");

        // H2 -> H1 (offset now inside "## Title").
        ed.set_block(3, BlockKind::Heading(1)).expect("to h1");
        assert_eq!(ed.source_str().unwrap(), "# Title\n\nbody text\n");

        // Heading -> paragraph, dropping the marker.
        ed.set_block(2, BlockKind::Paragraph).expect("to para");
        assert_eq!(ed.source_str().unwrap(), "Title\n\nbody text\n");
    }

    #[test]
    fn editor_set_block_rejects_bad_level_and_format() {
        let mut md = Editor::new_str("hi\n", Format::Markdown).expect("editor");
        assert_eq!(md.set_block(0, BlockKind::Heading(9)), Err(Error::InvalidArgument));

        let mut xml = Editor::new_str("<a>hi</a>", Format::Xml).expect("editor");
        assert_eq!(xml.set_block(1, BlockKind::Heading(1)), Err(Error::UnsupportedFormat));
    }

    #[test]
    fn editor_undo_redo_round_trip() {
        let mut ed = Editor::new_str("hello\n", Format::Markdown).expect("editor");
        ed.edit_range(5, 5, "!").expect("edit");
        assert_eq!(ed.source_str().unwrap(), "hello!\n");

        let change = ed.undo().expect("undo ok").expect("something to undo");
        assert_eq!(ed.source_str().unwrap(), "hello\n");
        assert_eq!(change.new.end, 5);
        assert!(ed.undo().expect("undo ok").is_none(), "history exhausted");

        ed.redo().expect("redo ok").expect("something to redo");
        assert_eq!(ed.source_str().unwrap(), "hello!\n");
    }

    #[test]
    fn editor_coalesce_folds_a_run() {
        let mut ed = Editor::new_str("\n", Format::Markdown).expect("editor");
        ed.edit_range(0, 0, "a").expect("edit");
        ed.edit_range(1, 1, "b").expect("edit");
        ed.coalesce_last_undo().expect("coalesce");
        assert_eq!(ed.source_str().unwrap(), "ab\n");
        // One undo removes the whole coalesced run.
        ed.undo().expect("undo ok").expect("something to undo");
        assert_eq!(ed.source_str().unwrap(), "\n");
        assert!(ed.undo().expect("undo ok").is_none());
    }

    #[test]
    fn editor_set_block_converts_setext_heading() {
        // A setext heading rebuilt from its content_span collapses the underline.
        let mut ed = Editor::new_str("Title\n=====\n\nbody\n", Format::Markdown).expect("editor");
        ed.set_block(0, BlockKind::Heading(1)).expect("setext to atx");
        assert_eq!(ed.source_str().unwrap(), "# Title\n\nbody\n");
    }

    #[test]
    fn editor_unwrap_and_smart_delete() {
        let mut ed = Editor::new_str("<r><box><b/><c/></box></r>", Format::Xml).expect("editor");
        ed.unwrap_node("0.0").expect("unwrap"); // <box>
        assert_eq!(ed.source_str().expect("source"), "<r><b/><c/></r>");

        let mut md = Editor::new_str("A\n\nB\n\nC\n", Format::Markdown).expect("editor");
        md.delete_smart("1").expect("delete_smart"); // the "B" paragraph
        assert_eq!(md.source_str().expect("source"), "A\n\nC\n");
    }

    #[test]
    fn editor_directives_require_the_extension_flag() {
        let src = ":::vis{.public}\nhi\n:::\n";
        // Without the flag, the colon-fence lines are plain paragraph text —
        // no directive node.
        let mut plain = Editor::new_str(src, Format::Markdown).expect("editor");
        assert_eq!(plain.query("directive").expect("query").len(), 0);
        // With it enabled, the container directive is recognized.
        let mut ext = Editor::new_ext(
            src.as_bytes(),
            Format::Markdown,
            MarkdownExtensions { directives: true, ..Default::default() },
        )
        .expect("editor");
        assert_eq!(ext.query("directive").expect("query").len(), 1);
    }

    #[test]
    fn editor_filter_public_audience_view() {
        let src = "# Archive\n\n:::vis{.public}\nPublic.\n:::\n\n:::vis{.family}\nPrivate.\n:::\n";
        let mut ed = Editor::new_ext(
            src.as_bytes(),
            Format::Markdown,
            MarkdownExtensions { directives: true, ..Default::default() },
        )
        .expect("editor");
        // Drop every vis block except the public one, then unwrap it.
        ed.filter(
            "directive[name=vis]",
            Some("directive[class~=public]"),
            true,
        )
        .expect("filter");
        assert_eq!(ed.source_str().expect("source"), "# Archive\n\nPublic.\n");
    }

    #[test]
    fn editor_filter_rejects_a_malformed_selector() {
        let mut ed = Editor::new_str("hi\n", Format::Markdown).expect("editor");
        assert_eq!(ed.filter("list >", None, false), Err(Error::InvalidArgument));
    }

    #[test]
    fn builder_builds_and_renders_a_document() {
        let mut b = Builder::new().expect("builder");

        // # Title\n\nhello *world*
        let title = b.add_text(TextKind::Str, "Title").unwrap();
        let heading = b.add_heading(1).unwrap();
        b.set_children(heading, &[title]).unwrap();

        let hello = b.add_text(TextKind::Str, "hello ").unwrap();
        let world = b.add_text(TextKind::Str, "world").unwrap();
        let emph = b.add(VoidKind::Emph).unwrap();
        b.set_children(emph, &[world]).unwrap();
        let para = b.add(VoidKind::Para).unwrap();
        b.set_children(para, &[hello, emph]).unwrap();

        let doc = b.add(VoidKind::Doc).unwrap();
        b.set_children(doc, &[heading, para]).unwrap();

        let html = String::from_utf8(b.render_html(doc).unwrap()).unwrap();
        assert!(html.contains("<h1>Title</h1>"), "{html}");
        assert!(html.contains("<em>world</em>"), "{html}");

        let md = String::from_utf8(b.serialize(doc, Format::Markdown).unwrap()).unwrap();
        assert!(md.contains("# Title"), "{md}");
        assert!(md.contains("*world*"), "{md}");

        let matches = b.query(doc, "heading").unwrap();
        assert_eq!(matches.len(), 1);
        assert_eq!(matches[0].kind, "heading");

        let json = String::from_utf8(b.ast_json(doc).unwrap()).unwrap();
        assert!(json.contains("\"kind\": \"doc\""), "{json}");
    }

    #[test]
    fn builder_element_with_attributes() {
        let mut b = Builder::new().expect("builder");
        let inner = b.add_text(TextKind::Str, "hi").unwrap();
        let el = b.add_element("section").unwrap();
        b.set_children(el, &[inner]).unwrap();
        b.set_attrs(el, &[("class", Some("note")), ("hidden", None)]).unwrap();

        let html = String::from_utf8(b.render_html(el).unwrap()).unwrap();
        assert!(html.contains("<section"), "{html}");
        assert!(html.contains("class=\"note\""), "{html}");
        assert!(html.contains("hidden"), "{html}");
    }

    #[test]
    fn builder_lists_round_trip_to_markdown() {
        let mut b = Builder::new().expect("builder");

        // An ordered list: 1. one / 2. two
        let one_txt = b.add_text(TextKind::Str, "one").unwrap();
        let one_para = b.add(VoidKind::Para).unwrap();
        b.set_children(one_para, &[one_txt]).unwrap();
        let one = b.add(VoidKind::ListItem).unwrap();
        b.set_children(one, &[one_para]).unwrap();

        let two_txt = b.add_text(TextKind::Str, "two").unwrap();
        let two_para = b.add(VoidKind::Para).unwrap();
        b.set_children(two_para, &[two_txt]).unwrap();
        let two = b.add(VoidKind::ListItem).unwrap();
        b.set_children(two, &[two_para]).unwrap();

        let list = b
            .add_ordered_list(OrderedNumbering::Decimal, OrderedDelim::Period, true, Some(1))
            .unwrap();
        b.set_children(list, &[one, two]).unwrap();
        let doc = b.add(VoidKind::Doc).unwrap();
        b.set_children(doc, &[list]).unwrap();

        let md = String::from_utf8(b.serialize(doc, Format::Markdown).unwrap()).unwrap();
        assert!(md.contains("1. one"), "{md}");
        assert!(md.contains("2. two"), "{md}");
    }

    #[test]
    fn builder_rejects_invalid_kind_and_id() {
        let b = Builder::new().expect("builder");
        // `heading` (code 2) carries a payload, so the void-kind `add` rejects it
        // — the safe `VoidKind` enum has no such variant, so we go through the raw
        // ABI to prove the guard.
        let mut id = 0u32;
        let status = unsafe { ffi::twig_builder_add(b.raw.as_ptr(), 2, &mut id) };
        assert_eq!(Error::from_status(status), Err(Error::InvalidArgument));

        // A root id past the end can't be rendered.
        let mut ptr = std::ptr::null();
        let mut len = 0usize;
        let status = unsafe { ffi::twig_builder_render_html(b.raw.as_ptr(), 4242, &mut ptr, &mut len) };
        assert_eq!(Error::from_status(status), Err(Error::InvalidArgument));
    }
}