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
mod compare;
mod entry;
mod helpers;
mod movements;
use helpers::{
append_comma_space_to_entry, ensure_top_level_empty_renders_as_flow, index_after_entry_line,
FlowInsertPos,
};
use super::{
ensure_trailing_newline, entry_key, entry_line_terminated, entry_value, fresh_token,
has_child_token, trailing_newline_reachable, Lang, Sequence, SyntaxNode,
};
use crate::as_yaml::{AsYaml, YamlKind};
use crate::lex::SyntaxKind;
use crate::yaml::{
collapse_empty_child_collection_in_parent as collapse_empty_child_mapping_in_parent,
dump_cst_to_string, ends_with_newline, ValueNode,
};
use rowan::ast::AstNode;
use rowan::GreenNodeBuilder;
ast_node!(
MappingEntry,
MAPPING_ENTRY,
"A key-value pair in a YAML mapping"
);
ast_node!(Mapping, MAPPING, "A YAML mapping (key-value pairs)");
impl Mapping {
/// Dump the CST (Concrete Syntax Tree) structure to a human-readable string.
///
/// This is intended for debugging and testing. The output shows the full
/// node hierarchy with indentation.
pub fn dump_cst(&self) -> String {
dump_cst_to_string(&self.0, 0)
}
/// Iterate over all keys in this mapping as [`YamlNode`](crate::as_yaml::YamlNode)s.
///
/// Each key is returned as a [`YamlNode`](crate::as_yaml::YamlNode) wrapping
/// the underlying CST node, preserving quoting style and other formatting.
/// The nodes implement [`AsYaml`](crate::AsYaml), so they can be passed
/// back to [`get`](Self::get), [`contains_key`](Self::contains_key), etc.,
/// and compared semantically with [`yaml_eq`](crate::yaml_eq).
///
/// Prefer [`entries`](Self::entries) when you also need the values, or
/// [`iter`](Self::iter) for `(key, value)` pairs as `(YamlNode, YamlNode)`.
/// For raw CST nodes, use `pairs()`.
pub fn keys(&self) -> impl Iterator<Item = crate::as_yaml::YamlNode> + '_ {
self.pairs().filter_map(|(k, _)| {
k.children()
.next()
.and_then(crate::as_yaml::YamlNode::from_syntax)
})
}
/// Iterate over raw KEY/VALUE syntax nodes for each mapping entry.
///
/// Each item is `(key_node, value_node)`, both raw CST wrapper nodes
/// (`KEY`/`VALUE`), not the content nodes inside them. Entries with a
/// missing key or value (which indicate a parse error in the source) are
/// silently skipped.
///
/// For most use cases prefer [`iter`](Self::iter) (which yields
/// `(YamlNode, YamlNode)` pairs) or [`entries`](Self::entries) (which
/// yields typed [`MappingEntry`] handles that give access to the full
/// entry including key, value, and mutation methods).
pub(crate) fn pairs(&self) -> impl Iterator<Item = (SyntaxNode, SyntaxNode)> + '_ {
self.0
.children()
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
.filter_map(|entry| Some((entry_key(&entry)?, entry_value(&entry)?)))
}
/// Get the value associated with `key` as a [`YamlNode`](crate::as_yaml::YamlNode).
///
/// Returns `None` if the key does not exist.
///
/// Matching is semantic but type-strict, so a key's type has to match as
/// well as its text: `1` does not find the string key `"1"`, and the
/// null key of `: v` is found with
/// [`ScalarValue::null`](crate::ScalarValue::null) rather than `""`,
/// which finds the distinct empty-string key of `"": v`.
///
/// ```rust
/// # use std::str::FromStr;
/// # use yaml_edit::{Document, ScalarValue};
/// let doc = Document::from_str(": a\n\"\": b\n").unwrap();
/// let mapping = doc.as_mapping().unwrap();
/// assert!(mapping.get(ScalarValue::null()).is_some());
/// assert!(mapping.get("").is_some());
/// ```
pub fn get(&self, key: impl crate::AsYaml) -> Option<crate::as_yaml::YamlNode> {
self.get_node(key)
.and_then(crate::as_yaml::YamlNode::from_syntax)
}
/// Get the raw content syntax node for `key` (for advanced CST access).
///
/// Returns the content node inside the `VALUE` wrapper - i.e. the actual
/// `SCALAR`, `MAPPING`, or `SEQUENCE` node. Returns `None` if the key does
/// not exist. For most use cases prefer [`get`](Self::get).
pub(crate) fn get_node(&self, key: impl crate::AsYaml) -> Option<SyntaxNode> {
self.find_entry_by_key(key)
.and_then(|entry| entry.value())
.and_then(|value_node| {
// VALUE nodes wrap the actual content, return the content instead
value_node.children().next()
})
}
/// Get the value for `key` as a nested [`Mapping`].
///
/// Returns `None` if the key does not exist or its value is not a mapping.
pub fn get_mapping(&self, key: impl crate::AsYaml) -> Option<Mapping> {
self.get(key).and_then(|n| n.as_mapping().cloned())
}
/// Modify a nested mapping in place by applying a closure to it.
///
/// Returns `true` if `key` exists and its value is a mapping (and `f` was
/// called); returns `false` if the key is missing or its value is not a
/// mapping.
///
/// Because [`Mapping`] uses interior mutability via rowan's `SyntaxNode`,
/// the closure receives a shared reference - mutations are still possible
/// through the node's `set`, `remove`, and other `&self` methods.
pub fn modify_mapping<F>(&self, key: impl crate::AsYaml, f: F) -> bool
where
F: FnOnce(&Mapping),
{
// The closure mutates through rowan's interior mutability, so the
// node found here is the one in the tree - nothing to splice back.
let nested = self.0.children().find_map(|node| {
if node.kind() != SyntaxKind::MAPPING_ENTRY {
return None;
}
let key_node = entry_key(&node)?;
if !key_content_matches(&key_node, &key) {
return None;
}
entry_value(&node)?
.children()
.find(|n| n.kind() == SyntaxKind::MAPPING)
});
let Some(mapping_node) = nested else {
return false;
};
f(&Mapping(mapping_node));
true
}
/// Get the value for `key` as a nested [`Sequence`].
///
/// Returns `None` if the key does not exist or its value is not a sequence.
pub fn get_sequence(&self, key: impl crate::AsYaml) -> Option<Sequence> {
self.get(key).and_then(|n| n.as_sequence().cloned())
}
/// Returns `true` if this mapping contains an entry with the given key.
pub fn contains_key(&self, key: impl crate::AsYaml) -> bool {
self.find_entry_by_key(key).is_some()
}
/// Iterate over the raw `KEY` wrapper nodes for all entries.
///
/// For most use cases prefer [`keys`](Self::keys) which yields
/// [`YamlNode`](crate::as_yaml::YamlNode) keys (formatting-preserving but
/// comparable via `yaml_eq`), or [`entries`](Self::entries) which yields
/// full [`MappingEntry`] handles.
pub(crate) fn key_nodes(&self) -> impl Iterator<Item = SyntaxNode> + '_ {
self.pairs().map(|(k, _)| k)
}
/// Check if the mapping is empty
pub fn is_empty(&self) -> bool {
self.pairs().next().is_none()
}
/// Get the number of key-value pairs in this mapping
pub fn len(&self) -> usize {
self.pairs().count()
}
/// Iterate over the values in this mapping as [`YamlNode`](crate::as_yaml::YamlNode)s.
///
/// Only entries whose value can be successfully wrapped in a `YamlNode` are
/// yielded; malformed or unrecognised value nodes are silently skipped.
/// Use [`iter`](Self::iter) to get both the key and value simultaneously, or
/// `pairs()` for the raw `SyntaxNode` pairs.
pub fn values(&self) -> impl Iterator<Item = crate::as_yaml::YamlNode> + '_ {
self.pairs().filter_map(|(_, value_node)| {
// VALUE node contains the actual content as children
value_node
.children()
.next()
.and_then(crate::as_yaml::YamlNode::from_syntax)
})
}
/// Iterate over `(key, value)` pairs, both as [`YamlNode`](crate::as_yaml::YamlNode)s.
///
/// Entries that cannot be fully wrapped (malformed key or value nodes) are
/// silently skipped. For raw CST nodes, use `pairs()`; for
/// typed entry handles, prefer [`entries`](Self::entries).
pub fn iter(
&self,
) -> impl Iterator<Item = (crate::as_yaml::YamlNode, crate::as_yaml::YamlNode)> + '_ {
self.pairs().filter_map(|(key_node, value_node)| {
// KEY and VALUE nodes wrap the actual content - extract children
let key = key_node
.children()
.next()
.and_then(crate::as_yaml::YamlNode::from_syntax)?;
let value = value_node
.children()
.next()
.and_then(crate::as_yaml::YamlNode::from_syntax)?;
Some((key, value))
})
}
/// Create a new empty mapping
pub fn new() -> Self {
Self::new_pending_block()
}
/// An empty mapping that renders as `{}` and stays flow when filled.
///
/// Use this for a mapping that is meant to be flow-style in the output,
/// including one that is left empty.
pub fn new_flow() -> Self {
Self::empty_with_brace_text("{", "}")
}
/// An empty mapping that becomes a block mapping once an entry is added.
///
/// YAML has no block syntax for an empty mapping: block collections are
/// written as their entries, so with none left there is nothing to write,
/// and a bare `key:` reads back as null. An empty mapping is therefore
/// `{}` whatever its eventual style, and block-vs-flow only becomes a
/// real choice once there is an entry.
///
/// This renders as exactly `{}`, plus a zero-width token that marks it as
/// destined for block style. [`Mapping::set`] rewrites it into block form
/// when the first entry arrives; a `{}` that came from the source has no
/// such marker and keeps its flow style.
///
/// The marker lives only in the tree. Serializing and re-parsing yields
/// an ordinary `{}`, which stays flow, since YAML has nowhere to record
/// the intent.
pub fn new_pending_block() -> Self {
let mut builder = GreenNodeBuilder::new();
builder.start_node(SyntaxKind::MAPPING.into());
builder.token(SyntaxKind::LEFT_BRACE.into(), "{");
// Zero-width sentinel: renders as nothing, so this is still exactly
// `{}` in the text, but marks the mapping as one that should become
// block when it gets its first entry.
builder.token(SyntaxKind::WHITESPACE.into(), "");
builder.token(SyntaxKind::RIGHT_BRACE.into(), "}");
builder.finish_node();
Mapping(SyntaxNode::new_root_mut(builder.finish()))
}
fn empty_with_brace_text(open: &str, close: &str) -> Self {
let mut builder = GreenNodeBuilder::new();
builder.start_node(SyntaxKind::MAPPING.into());
builder.token(SyntaxKind::LEFT_BRACE.into(), open);
builder.token(SyntaxKind::RIGHT_BRACE.into(), close);
builder.finish_node();
Mapping(SyntaxNode::new_root_mut(builder.finish()))
}
/// Is this an empty mapping awaiting its first entry? See
/// [`Mapping::new_pending_block`].
pub(crate) fn is_block_placeholder(&self) -> bool {
!self
.0
.children()
.any(|c| c.kind() == SyntaxKind::MAPPING_ENTRY)
&& self
.0
.children_with_tokens()
.filter_map(|c| c.into_token())
.any(|t| t.kind() == SyntaxKind::WHITESPACE && t.text().is_empty())
}
/// Slice this mapping's children into leading decoration, one
/// `(entry, postscript)` group per entry, and trailing decoration.
///
/// A group carries the tokens between its entry and the next, so
/// reshuffling groups keeps a between-entry comment glued to the entry it
/// visually followed.
#[allow(clippy::type_complexity)]
fn slice_into_entry_groups(
&self,
all: &[rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>],
) -> (
Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>>,
Vec<(
SyntaxNode,
Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>>,
)>,
Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>>,
) {
let entry_indices: Vec<usize> = all
.iter()
.enumerate()
.filter_map(|(i, c)| {
c.as_node()
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
.map(|_| i)
})
.collect();
let leading = all[..*entry_indices.first().unwrap_or(&all.len())].to_vec();
let mut trailing = entry_indices
.last()
.map(|&i| all[i + 1..].to_vec())
.unwrap_or_default();
// An explicit-key entry (`? k` / `: v`) doesn't own its line break;
// the NEWLINE sits beside it. For the last entry that token lands in
// `trailing`, which stays put -- so reordering it to a non-final
// position would run it into the entry that follows. Hand it back so
// it travels with the entry.
let last_needs_terminator = entry_indices.last().is_some_and(|&i| {
all[i]
.as_node()
.is_some_and(|n| !trailing_newline_reachable(n))
});
let last_entry_terminator = (last_needs_terminator
&& trailing
.first()
.is_some_and(|c| c.kind() == SyntaxKind::NEWLINE))
.then(|| trailing.remove(0));
let mut groups: Vec<(SyntaxNode, Vec<_>)> = entry_indices
.windows(2)
.map(|w| {
let entry = all[w[0]].as_node().cloned().unwrap();
let postscript = all[w[0] + 1..w[1]].to_vec();
(entry, postscript)
})
.collect();
if let Some(&last) = entry_indices.last() {
let postscript = last_entry_terminator.into_iter().collect();
groups.push((all[last].as_node().cloned().unwrap(), postscript));
}
(leading, groups, trailing)
}
/// Reorder fields according to the specified order.
///
/// Fields not in the order list will appear after the ordered fields,
/// in their original relative order.
pub fn reorder_fields<I, K>(&self, order: I)
where
I: IntoIterator<Item = K>,
K: crate::AsYaml,
{
let order_keys: Vec<K> = order.into_iter().collect();
// Slice the children into leading decoration, (entry, tokens
// that follow it up to the next entry), and trailing
// decoration. Reshuffling (entry, postscript) pairs keeps a
// between-entry comment glued to the entry it visually
// followed.
let all: Vec<_> = self.0.children_with_tokens().collect();
let (leading, mut groups, trailing) = self.slice_into_entry_groups(&all);
// Take each named key's group in the order given; anything the
// caller did not name keeps its relative position at the end.
let entry_has_key = |entry: &SyntaxNode, key: &K| {
entry
.children()
.find(|n| n.kind() == SyntaxKind::KEY)
.is_some_and(|k| key_content_matches(&k, key))
};
let mut ordered: Vec<_> = order_keys
.iter()
.filter_map(|key| {
let pos = groups
.iter()
.position(|(entry, _)| entry_has_key(entry, key))?;
Some(groups.remove(pos))
})
.collect();
ordered.extend(groups);
let mut new_children = leading;
for (entry, postscript) in ordered {
new_children.push(entry.into());
new_children.extend(postscript);
}
new_children.extend(trailing);
self.0.splice_children(0..all.len(), new_children);
}
}
/// Check whether the CST key node matches `key` using semantic equality.
///
/// `key_node` may be a raw KEY wrapper; `from_syntax_peeled` unwraps it.
pub(super) fn key_content_matches(key_node: &SyntaxNode, key: impl crate::AsYaml) -> bool {
match crate::as_yaml::YamlNode::from_syntax_peeled(key_node.clone()) {
Some(node) => crate::as_yaml::yaml_eq(&node, &key),
None => false,
}
}
impl Mapping {
/// Check if this mapping is in flow style (JSON/inline format with `{}`).
///
/// Returns `true` if the mapping uses flow style (e.g., `{key: value}`),
/// `false` if it uses block style (e.g., `key: value`).
pub fn is_flow_style(&self) -> bool {
// Flow-style mappings start with LEFT_BRACE token. A block
// placeholder is `{}` in the text but is destined to become block, so
// it does not count as flow.
has_child_token(&self.0, |k| k == SyntaxKind::LEFT_BRACE) && !self.is_block_placeholder()
}
/// Find the [`MappingEntry`] whose key matches `key`, or `None` if not found.
///
/// Matching is semantic (quoting style is ignored), so `"foo"`, `'foo'`,
/// and `foo` all match the scalar `"foo"`.
pub fn find_entry_by_key(&self, key: impl crate::AsYaml) -> Option<MappingEntry> {
self.0
.children()
.filter_map(MappingEntry::cast)
.find(|entry| entry.key().is_some_and(|k| key_content_matches(&k, &key)))
}
/// Find all entries with a given key.
///
/// Returns an iterator over all [`MappingEntry`] instances that match the
/// given key. This is useful for handling duplicate keys in YAML (which
/// are allowed by the spec but semantically ambiguous).
///
/// Matching is semantic (quoting style is ignored), so `"foo"`, `'foo'`,
/// and `foo` all match the scalar `"foo"`.
///
/// # Example
///
/// ```rust
/// # use std::str::FromStr;
/// # use yaml_edit::Document;
/// let yaml = r#"
/// Reference: First
/// Reference: Second
/// Reference: Third
/// "#;
///
/// let doc = Document::from_str(yaml).unwrap();
/// let mapping = doc.as_mapping().unwrap();
///
/// // Collect all Reference entries
/// let refs: Vec<_> = mapping.find_all_entries_by_key("Reference").collect();
/// assert_eq!(refs.len(), 3);
///
/// // Remove all but the first occurrence
/// let _: Vec<()> = refs.into_iter().skip(1).map(|entry| entry.remove()).collect();
/// ```
pub fn find_all_entries_by_key<'a>(
&'a self,
key: impl crate::AsYaml + 'a,
) -> impl Iterator<Item = MappingEntry> + 'a {
self.0
.children()
.filter_map(MappingEntry::cast)
.filter(move |entry| entry.key().is_some_and(|k| key_content_matches(&k, &key)))
}
/// Iterate over all entries in this mapping as typed [`MappingEntry`] handles.
///
/// Each [`MappingEntry`] gives access to the key, value, and mutation
/// methods for that entry. For decoded `(key, value)` pairs, prefer
/// [`iter`](Self::iter); for raw CST nodes, use `pairs()`.
pub fn entries(&self) -> impl Iterator<Item = MappingEntry> {
self.0.children().filter_map(MappingEntry::cast)
}
/// Return an [`Entry`](crate::Entry) view into the entry for `key`.
///
/// Mirrors [`std::collections::BTreeMap::entry`], enabling
/// insert-or-update patterns while preserving formatting.
///
/// ```rust
/// use std::str::FromStr;
/// use yaml_edit::Document;
///
/// let doc = Document::from_str("name: Alice\n").unwrap();
/// let mapping = doc.as_mapping().unwrap();
///
/// mapping.entry("age").or_insert(30);
/// mapping.entry("name").or_insert("Bob");
///
/// assert_eq!(doc.to_string(), "name: Alice\nage: 30\n");
/// ```
pub fn entry<K: crate::AsYaml>(&self, key: K) -> crate::Entry<'_, K> {
match self.find_entry_by_key(&key) {
Some(entry) => crate::Entry::Occupied(crate::OccupiedEntry {
mapping: self,
entry,
}),
None => crate::Entry::Vacant(crate::VacantEntry { mapping: self, key }),
}
}
/// Find the child index of a mapping entry by its key.
///
/// Returns the index within the mapping's children (including non-entry
/// tokens like whitespace), or `None` if no entry with the given key exists.
/// This index is suitable for use with `splice_children`.
pub fn find_entry_index_by_key(&self, key: impl crate::AsYaml) -> Option<usize> {
// Look through all children (not just entries, to get accurate index)
self.0
.children_with_tokens()
.enumerate()
.find_map(|(i, child)| {
let node = child.as_node()?;
if node.kind() != SyntaxKind::MAPPING_ENTRY {
return None;
}
let entry = MappingEntry::cast(node.clone())?;
if entry.key().is_some_and(|k| key_content_matches(&k, &key)) {
Some(i)
} else {
None
}
})
}
/// Set a key-value pair, replacing the existing value if the key exists or
/// appending a new entry if it does not. Accepts any value that implements
/// [`AsYaml`](crate::AsYaml) - scalars, mappings, sequences, etc.
///
/// This method always succeeds; it never silently ignores input. See also
/// [`insert_after`](Self::insert_after) and [`insert_before`](Self::insert_before)
/// which return `bool` to indicate whether the anchor key was found.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
///
/// `set` replaces the value with the node you pass. It does not infer
/// YAML 1.1 merge keys from a resolved map. To keep identity, pass an
/// alias node (`*name`) or a mapping that already contains `<<: *name`.
/// Merge **reads** (`get_resolved()`, `merged()`) stay separate from
/// this CST replace.
///
/// ```
/// use std::str::FromStr;
/// use yaml_edit::Document;
///
/// let doc = Document::from_str(
/// "shared: &shared\n timeout: 30\n retries: 3\nservice_a: old\n",
/// )
/// .unwrap();
/// let mapping = doc.as_mapping().unwrap();
/// let merge = Document::from_str("<<: *shared\ntimeout: 60\n").unwrap();
/// mapping.set("service_a", merge.as_mapping().unwrap());
/// assert_eq!(
/// doc.to_string(),
/// "shared: &shared\n timeout: 30\n retries: 3\nservice_a:\n <<: *shared\n timeout: 60\n"
/// );
/// ```
pub fn set(&self, key: impl crate::AsYaml, value: impl crate::AsYaml) {
self.set_as_yaml(key, value);
}
/// Detect if this mapping uses explicit key indicators (?)
pub(super) fn uses_explicit_keys(&self) -> bool {
// Check if any existing entries use explicit key format
// The QUESTION token is a child of MAPPING_ENTRY (sibling to KEY), not inside KEY
for child in self.0.children() {
if child.kind() == SyntaxKind::MAPPING_ENTRY {
// Check if this entry has a QUESTION token as a child
if has_child_token(&child, |k| k == SyntaxKind::QUESTION) {
return true;
}
}
}
false
}
/// Internal unified method to set any YAML value type
fn set_as_yaml<K: crate::AsYaml, V: crate::AsYaml>(&self, key: K, value: V) {
// A placeholder from `Mapping::new_pending_block` turns into a real block
// mapping now that it has an entry to hold. This runs before the
// flow_context check below so the entry is laid out as block.
if self.is_block_placeholder() && !crate::nodes::sequence::must_render_flow(&self.0) {
crate::yaml::convert_placeholder_to_block(&self.0);
}
// Detect if this mapping is in flow style (JSON format)
let flow_context = self.is_flow_style();
// Detect if existing entries use explicit keys
let use_explicit_keys = self.uses_explicit_keys();
// An existing entry with this key takes the value in place.
let existing = self
.0
.children_with_tokens()
.enumerate()
.find_map(|(i, c)| {
let entry = MappingEntry::cast(c.into_node()?)?;
let matches = entry.key().is_some_and(|k| key_content_matches(&k, &key));
matches.then_some((i, entry))
});
if let Some((i, entry)) = existing {
entry.set_value(value, flow_context);
self.0.splice_children(i..i + 1, vec![entry.0.into()]);
return;
}
// Entry doesn't exist, create a new one. Tell the constructor at
// what column its key will sit so a node-backed block value has its
// interior indentation shifted to line up under the new entry.
let key_indent = self.detect_indentation_level();
let new_entry =
MappingEntry::new_at_indent(key, value, flow_context, use_explicit_keys, key_indent);
self.insert_entry_cst(&new_entry.0);
}
/// Insert `new_entry` into a flow-style mapping (`{...}`) at the position
/// dictated by `where_at`, wiring up `, ` separators so the entries stay
/// syntactically valid inside the braces.
pub(super) fn insert_flow_entry_cst_at(&self, new_entry: &SyntaxNode, where_at: FlowInsertPos) {
let brace_pos = self.0.children_with_tokens().position(|c| {
c.as_token()
.is_some_and(|t| t.kind() == SyntaxKind::RIGHT_BRACE)
});
// Resolve the target index. Anchor by node identity so a subsequent
// splice targets the right slot even if we've added separators.
let target_idx = match where_at {
FlowInsertPos::End => {
brace_pos.unwrap_or_else(|| self.0.children_with_tokens().count())
}
FlowInsertPos::After(ref n) => self
.0
.children_with_tokens()
.position(|c| c.as_node() == Some(n))
.map_or_else(|| brace_pos.unwrap_or(0), |i| i + 1),
FlowInsertPos::Before(ref n) => self
.0
.children_with_tokens()
.position(|c| c.as_node() == Some(n))
.unwrap_or_else(|| brace_pos.unwrap_or(0)),
};
// If a MAPPING_ENTRY precedes the target position, append `, ` to
// it so the two entries are properly delimited.
let prev_entry = self
.0
.children_with_tokens()
.take(target_idx)
.filter_map(|c| c.into_node())
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
.last();
if let Some(prev) = prev_entry {
append_comma_space_to_entry(&prev);
}
// If a MAPPING_ENTRY follows the target position, append `, ` to
// the *new* entry so it separates from the next one.
let has_following_entry = self.0.children_with_tokens().skip(target_idx).any(|c| {
c.as_node()
.is_some_and(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
});
if has_following_entry {
append_comma_space_to_entry(new_entry);
}
self.0
.splice_children(target_idx..target_idx, vec![new_entry.clone().into()]);
}
/// Internal method to insert a new entry at the end (does not check for duplicates)
fn insert_entry_cst(&self, new_entry: &SyntaxNode) {
if self.is_flow_style() {
self.insert_flow_entry_cst_at(new_entry, FlowInsertPos::End);
return;
}
// Count children and check if last entry has trailing newline
let mut count = 0;
let mut last_mapping_entry: Option<SyntaxNode> = None;
for child in self.0.children_with_tokens() {
count += 1;
if let Some(node) = child
.as_node()
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
{
last_mapping_entry = Some(node.clone());
}
}
// Does the last entry end with a NEWLINE leaf? Checking
// last_token().kind() == NEWLINE alone misses the case where
// the tail token is a zero-width implicit-null (e.g. `? b\n`
// under a tagged mapping) but a real NEWLINE sits just before
// it in the token stream. Walk the token tail instead.
let has_trailing_newline = if let Some(entry) = &last_mapping_entry {
entry_line_terminated(entry)
} else {
trailing_newline_reachable(&self.0)
};
let mut new_elements = Vec::new();
let insert_pos = count;
// Give the previous entry its own trailing NEWLINE (see
// insert_at_index for why standalone separators are fragile).
if count > 0 && !has_trailing_newline {
if let Some(prev_entry) = &last_mapping_entry {
ensure_trailing_newline(prev_entry);
}
}
let indent_level = self.detect_indentation_level();
if indent_level > 0 && count > 0 {
new_elements.push(fresh_token(SyntaxKind::INDENT, &" ".repeat(indent_level)).into());
}
new_elements.push(new_entry.clone().into());
// Note: We don't add a trailing newline here because MappingEntry::new()
// already adds one as part of the newline ownership model (entries own their trailing newlines)
self.0.splice_children(insert_pos..insert_pos, new_elements);
// If the mapping had been empty and sits inside a `key:\n \n`
// placeholder, strip the outer MAPPING_ENTRY's trailing NEWLINE
// that acted as the placeholder marker (see issue #18).
if count == 0 {
crate::yaml::detach_empty_collection_placeholder_newline(&self.0, new_entry);
}
}
/// Set a key-value pair with field ordering support
/// If the key exists, updates its value. If the key doesn't exist, inserts it
/// at the correct position based on the provided field order.
/// Fields not in the order list are placed at the end.
pub fn set_with_field_order<I, K>(
&self,
key: impl crate::AsYaml,
value: impl crate::AsYaml,
field_order: I,
) where
I: IntoIterator<Item = K>,
K: crate::AsYaml,
{
// Collect field_order so we can iterate it multiple times.
let field_order: Vec<K> = field_order.into_iter().collect();
// An existing key just takes the new value, wherever it sits.
if self.find_entry_by_key(&key).is_some() {
self.set_as_yaml(&key, &value);
return;
}
let children: Vec<_> = self.0.children_with_tokens().collect();
// Key doesn't exist, need to find the correct insertion position based on field order.
// Find position of this key in the field order (if it matches any)
let key_position_in_order = field_order
.iter()
.position(|field| crate::as_yaml::yaml_eq(&key, field));
if let Some(key_index) = key_position_in_order {
// Key is in the field order, find the right position to insert
let mut insert_after_node: Option<SyntaxNode> = None;
let mut insert_before_node: Option<SyntaxNode> = None;
// The nearest preceding field that is actually present decides
// where the new entry goes.
for field in field_order.iter().take(key_index).rev() {
if let Some(entry) = self.find_entry_by_key(field) {
insert_after_node = Some(entry.0);
break;
}
}
// If no predecessor found, look for the first existing key in document order
// that comes after this one in field_order
if insert_after_node.is_none() {
// Nothing precedes it, so go before the first present field
// that the order puts after it.
insert_before_node = self.entries().find_map(|entry| {
let key_node = entry.key()?;
let pos = field_order
.iter()
.position(|field| key_content_matches(&key_node, field))?;
(pos > key_index).then_some(entry.0)
});
}
// Build the new entry with proper newline ownership
let flow_context = self.is_flow_style();
let use_explicit_keys = self.uses_explicit_keys();
let key_indent = self.detect_indentation_level();
let new_entry = MappingEntry::new_at_indent(
&key,
&value,
flow_context,
use_explicit_keys,
key_indent,
)
.0;
match (insert_after_node, insert_before_node) {
(Some(after), _) if flow_context => {
self.insert_flow_entry_cst_at(&new_entry, FlowInsertPos::After(after));
}
(Some(after), _) => self.insert_block_entry_after(&children, &new_entry, &after),
(None, Some(before)) if flow_context => {
self.insert_flow_entry_cst_at(&new_entry, FlowInsertPos::Before(before));
}
(None, Some(before)) => {
self.insert_block_entry_before(&children, &new_entry, &before)
}
// No ordered key is present yet, so order says nothing about
// where this one goes.
(None, None) => self.set_as_yaml(&key, &value),
}
} else {
// Key is not in field order, append at the end using CST
self.set_as_yaml(&key, &value);
}
}
/// The INDENT token entries of this mapping are preceded by, if any.
fn entry_indent_token(&self) -> Option<rowan::SyntaxToken<Lang>> {
let level = self.detect_indentation_level();
(level > 0).then(|| super::fresh_token(SyntaxKind::INDENT, &" ".repeat(level)))
}
/// Splice `new_entry` into this block mapping on the line after `after`.
fn insert_block_entry_after(
&self,
children: &[rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>],
new_entry: &SyntaxNode,
after: &SyntaxNode,
) {
ensure_trailing_newline(after);
let idx = children
.iter()
.position(|c| c.as_node() == Some(after))
.expect("after was found in children earlier");
let at = index_after_entry_line(&self.0, idx);
let mut elements: Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>> = self
.entry_indent_token()
.into_iter()
.map(Into::into)
.collect();
elements.push(new_entry.clone().into());
self.0.splice_children(at..at, elements);
}
/// Splice `new_entry` into this block mapping ahead of `before`.
fn insert_block_entry_before(
&self,
children: &[rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>],
new_entry: &SyntaxNode,
before: &SyntaxNode,
) {
let idx = children
.iter()
.position(|c| c.as_node() == Some(before))
.expect("before was found in children earlier");
if let Some(prev) = children[..idx].iter().rev().find_map(|c| {
c.as_node()
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
}) {
ensure_trailing_newline(prev);
}
// The indent preceding `before` (the parent VALUE's for the first
// child, a sibling INDENT token otherwise) now serves the new entry,
// so the displaced `before` needs its own sibling INDENT.
let mut elements: Vec<rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>> =
vec![new_entry.clone().into()];
elements.extend(self.entry_indent_token().map(Into::into));
self.0.splice_children(idx..idx, elements);
}
/// Detect the indentation level (in spaces) used by entries in this mapping.
///
/// Returns `0` for root-level mappings where entries have no leading indentation.
pub fn detect_indentation_level(&self) -> usize {
// Look for an INDENT token that precedes an entry inside this mapping.
// For a multi-entry mapping the parser stores that column here. An
// INDENT introducing a COMMENT says nothing about where keys sit, so
// skip those: comments may be indented arbitrarily.
let children: Vec<_> = self.0.children_with_tokens().collect();
for (i, child) in children.iter().enumerate() {
if let Some(token) = child.as_token() {
if token.kind() == SyntaxKind::INDENT {
let introduces_comment = children[i + 1..]
.iter()
.find(|c| !matches!(c.kind(), SyntaxKind::WHITESPACE))
.is_some_and(|c| c.kind() == SyntaxKind::COMMENT);
if !introduces_comment {
return token.text().len();
}
}
}
}
// Single-entry mapping (or empty): the column of the first entry
// isn't stored here, it's the INDENT that precedes the MAPPING node
// in its parent's VALUE. Fall back to that.
crate::as_yaml::source_base_indent(&self.0)
}
/// The child position of the entry whose key matches `entry`'s, if any.
///
/// The position is in `children_with_tokens` space, which is what
/// `splice_children` indexes, so it is not the entry's ordinal.
fn child_index_of_matching_entry(&self, entry: &SyntaxNode) -> Option<usize> {
let key_node = MappingEntry::cast(entry.clone())?.key()?;
let existing = self.entries().find(|e| {
e.key()
.is_some_and(|k| self.compare_key_nodes(&k, &key_node))
})?;
self.0
.children_with_tokens()
.position(|c| c.as_node() == Some(existing.syntax()))
}
/// Insert a key-value pair at a specific index (0-based), preserving formatting.
///
/// If `new_key` already exists in the mapping, the existing entry is replaced
/// with a newly built entry at the **same position** (the `index` argument is
/// ignored). Surrounding whitespace in the file is preserved, but the entry
/// node itself is rebuilt (comments attached to the old entry may be lost).
/// If `index` is out of bounds, the entry is appended at the end.
pub fn insert_at_index_preserving(
&self,
index: usize,
new_key: impl crate::AsYaml,
new_value: impl crate::AsYaml,
) {
// Create the new entry using create_mapping_entry
let (new_entry, _has_trailing_newline) = self.create_mapping_entry(new_key, new_value);
// An existing entry with this key is replaced where it stands, so the
// index is only consulted for a key that is not there yet. New
// entries always end with a newline (DESIGN.md), so the old entry's
// own terminator goes with it.
if let Some(i) = self.child_index_of_matching_entry(&new_entry) {
self.0.splice_children(i..i + 1, vec![new_entry.into()]);
return;
}
// Key doesn't exist, insert at the specified index
let children: Vec<_> = self.0.children_with_tokens().collect();
// Count existing MAPPING_ENTRY nodes to find insertion point
let mut entry_indices = Vec::new();
for (i, child) in children.iter().enumerate() {
if child
.as_node()
.is_some_and(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
{
entry_indices.push(i);
}
}
let mut new_elements = Vec::new();
// Determine insertion position in children_with_tokens space
let insert_pos = if entry_indices.is_empty() {
// Empty mapping - insert at beginning
0
} else if index >= entry_indices.len() {
// Index beyond end - insert after last entry
let last_entry_idx = entry_indices[entry_indices.len() - 1];
// Find the end of the last entry (including its newline if present)
let mut pos = last_entry_idx + 1;
while pos < children.len() {
if let Some(token) = children[pos].as_token() {
if token.kind() == SyntaxKind::NEWLINE {
pos += 1;
break;
}
}
pos += 1;
}
pos
} else {
// Insert before the entry at the specified index
entry_indices[index]
};
// Add newline before entry if inserting after existing content
// Check if previous element ends with newline (either as token or inside node)
if insert_pos > 0 && !entry_indices.is_empty() {
let has_newline_before = if let Some(child) = children.get(insert_pos - 1) {
match child {
rowan::NodeOrToken::Token(t) => t.kind() == SyntaxKind::NEWLINE,
rowan::NodeOrToken::Node(n) => ends_with_newline(n),
}
} else {
false
};
if !has_newline_before {
new_elements.push(fresh_token(SyntaxKind::NEWLINE, "\n").into());
}
}
// Use the already-created MAPPING_ENTRY node (already ends with newline)
new_elements.push(new_entry.into());
// Insert at the calculated position
self.0.splice_children(insert_pos..insert_pos, new_elements);
}
/// Remove a key-value pair, returning the removed entry.
///
/// Returns `Some(entry)` if the key existed and was removed, or `None` if
/// the key was not found. The returned [`MappingEntry`] is detached from
/// the tree; callers can inspect its key and value or re-insert it
/// elsewhere.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn remove(&self, key: impl crate::AsYaml) -> Option<MappingEntry> {
let children: Vec<_> = self.0.children_with_tokens().collect();
for (i, child) in children.iter().enumerate() {
let Some(node) = child.as_node() else {
continue;
};
if node.kind() != SyntaxKind::MAPPING_ENTRY {
continue;
}
let Some(entry) = MappingEntry::cast(node.clone()) else {
continue;
};
if !entry.key_matches(&key) {
continue;
}
self.remove_entry_at(&children, i, node);
return Some(entry);
}
None
}
/// Splice the entry at child index `i` out of this mapping, and
/// restore the tail-newline convention on the new last entry.
///
/// Shared by [`Mapping::remove`] and [`Mapping::remove_nth_occurrence`].
/// The rule is: if we're removing the last MAPPING_ENTRY and it had
/// no trailing NEWLINE (an unterminated source), strip the trailing
/// NEWLINE from the new last entry too so the doc's terminator
/// character is preserved. Otherwise leave the previous entry's
/// NEWLINE in place.
fn remove_entry_at(
&self,
children: &[rowan::NodeOrToken<SyntaxNode, rowan::SyntaxToken<Lang>>],
i: usize,
removed: &SyntaxNode,
) {
let is_last = !children.iter().skip(i + 1).any(|c| {
c.as_node()
.is_some_and(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
});
let removed_had_newline = removed
.last_token()
.is_some_and(|t| t.kind() == SyntaxKind::NEWLINE);
// In a block mapping every entry but the first is preceded by an
// INDENT token that puts it at the right column; the first
// entry's indent sits outside, on the parent VALUE. That token
// belongs to the entry, so it goes with it -- otherwise it
// orphans onto the following entry, over-indenting it, or is
// left dangling as trailing whitespace when the entry was last.
let indent_before = i.checked_sub(1).and_then(|p| {
children[p]
.as_token()
.filter(|t| t.kind() == SyntaxKind::INDENT)
.cloned()
});
self.0.splice_children(i..(i + 1), vec![]);
// Removing the first entry promotes the next one, but the parent
// VALUE already supplies its indent, so the INDENT now leading
// this mapping would double it. Drop whichever applies.
let orphaned_indent = indent_before.or_else(|| {
self.0
.children_with_tokens()
.next()
.and_then(|c| c.into_token())
.filter(|t| t.kind() == SyntaxKind::INDENT)
});
if let Some(indent) = orphaned_indent {
indent.detach();
}
// Nested mapping drained by remove: collapse to `key: {}` so
// `set_path("a.b.c", v) + remove_path(...)` doesn't leave a
// dangling indent scaffold. Top-level drain is left alone here
// -- callers may add more entries and injecting `{}` would
// poison subsequent block-style `set`s; `Mapping::clear`
// handles the explicit-empty case.
if !self
.0
.children()
.any(|c| c.kind() == SyntaxKind::MAPPING_ENTRY)
{
collapse_empty_child_mapping_in_parent(&self.0);
}
if !(is_last && i > 0 && !removed_had_newline) {
return;
}
let Some(prev_entry_node) = children[..i].iter().rev().find_map(|c| {
c.as_node()
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
}) else {
return;
};
if !prev_entry_node
.last_token()
.is_some_and(|t| t.kind() == SyntaxKind::NEWLINE)
{
return;
}
let count = prev_entry_node.children_with_tokens().count();
prev_entry_node.splice_children((count - 1)..count, vec![]);
}
/// Remove the nth occurrence of a key, returning the removed entry.
///
/// Returns `Some(entry)` if the nth occurrence exists and was removed,
/// or `None` if there are fewer than `n+1` occurrences of the key.
/// The index `n` is 0-based (n=0 removes the first occurrence, n=1 removes
/// the second, etc.).
///
/// This is useful for handling duplicate keys in YAML. While duplicate keys
/// are semantically ambiguous, they are allowed by the YAML spec, and this
/// method provides fine-grained control over which occurrence to remove.
///
/// # Example
///
/// ```rust
/// # use std::str::FromStr;
/// # use yaml_edit::Document;
/// let yaml = r#"
/// Reference: First
/// Reference: Second
/// Reference: Third
/// "#;
///
/// let doc = Document::from_str(yaml).unwrap();
/// let mapping = doc.as_mapping().unwrap();
///
/// // Remove the second occurrence (index 1)
/// let removed = mapping.remove_nth_occurrence("Reference", 1);
/// assert!(removed.is_some());
///
/// // Now only two Reference entries remain
/// let count = mapping.find_all_entries_by_key("Reference").count();
/// assert_eq!(count, 2);
/// ```
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn remove_nth_occurrence(&self, key: impl crate::AsYaml, n: usize) -> Option<MappingEntry> {
let children: Vec<_> = self.0.children_with_tokens().collect();
let mut occurrence_count = 0;
for (i, child) in children.iter().enumerate() {
let Some(node) = child.as_node() else {
continue;
};
if node.kind() != SyntaxKind::MAPPING_ENTRY {
continue;
}
let Some(entry) = MappingEntry::cast(node.clone()) else {
continue;
};
if !entry.key_matches(&key) {
continue;
}
if occurrence_count != n {
occurrence_count += 1;
continue;
}
self.remove_entry_at(&children, i, node);
return Some(entry);
}
None
}
/// Remove all key-value pairs from this mapping.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn clear(&self) {
let keys: Vec<crate::as_yaml::YamlNode> = self.keys().collect();
for key in keys {
self.remove(key);
}
ensure_top_level_empty_renders_as_flow(&self.0);
}
/// Rename a key while preserving its value and formatting.
///
/// The new key is built using the same `AsYaml` infrastructure as other
/// write methods, so quoting and escaping are handled automatically.
/// Returns `true` if the key was found and renamed, `false` if `old_key`
/// does not exist.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn rename_key(&self, old_key: impl crate::AsYaml, new_key: impl crate::AsYaml) -> bool {
let children: Vec<_> = self.0.children_with_tokens().collect();
for (i, child) in children.iter().enumerate() {
let Some(node) = child
.as_node()
.filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
else {
continue;
};
let Some(key_node) = entry_key(node) else {
continue;
};
if !key_content_matches(&key_node, &old_key) {
continue;
}
let mut builder = GreenNodeBuilder::new();
builder.start_node(SyntaxKind::MAPPING_ENTRY.into());
for entry_child in node.children_with_tokens() {
match entry_child {
rowan::NodeOrToken::Node(n) if n.kind() == SyntaxKind::KEY => {
Self::rebuild_key(&mut builder, &n, &new_key);
}
rowan::NodeOrToken::Node(n) => {
crate::yaml::copy_node_to_builder(&mut builder, &n);
}
rowan::NodeOrToken::Token(t) => {
builder.token(t.kind().into(), t.text());
}
}
}
builder.finish_node();
let new_entry = SyntaxNode::new_root_mut(builder.finish());
self.0.splice_children(i..i + 1, vec![new_entry.into()]);
return true;
}
false
}
/// Rebuild an entry's KEY node around `new_key`, keeping the layout
/// tokens the old one carried.
///
/// An explicit key (`? k\n : v`) puts the `:` on its own line, and the
/// parser keeps that line break and indent inside KEY. They describe the
/// entry's layout rather than the key, so they carry over; dropped, the
/// entry collapses onto one line and reparses as one node.
fn rebuild_key(builder: &mut GreenNodeBuilder, old: &SyntaxNode, new_key: &impl crate::AsYaml) {
builder.start_node(SyntaxKind::KEY.into());
super::build_key_content(builder, new_key);
for trailing in old
.children_with_tokens()
.skip_while(|c| !matches!(c.as_token().map(|t| t.kind()), Some(SyntaxKind::NEWLINE)))
.filter_map(|c| c.into_token())
{
builder.token(trailing.kind().into(), trailing.text());
}
builder.finish_node();
}
/// Helper to create a MAPPING_ENTRY node from key and value strings
pub(super) fn create_mapping_entry(
&self,
key: impl crate::AsYaml,
value: impl crate::AsYaml,
) -> (SyntaxNode, bool) {
let mut builder = GreenNodeBuilder::new();
builder.start_node(SyntaxKind::MAPPING_ENTRY.into());
// Add KEY node
builder.start_node(SyntaxKind::KEY.into());
super::build_key_content(&mut builder, &key);
builder.finish_node(); // KEY
// Add colon
builder.token(SyntaxKind::COLON.into(), ":");
// Check if value is inline - if not, add newline + indent before VALUE
if !value.is_inline() {
builder.token(SyntaxKind::NEWLINE.into(), "\n");
builder.token(SyntaxKind::INDENT.into(), " "); // 2-space indent
} else {
builder.token(SyntaxKind::WHITESPACE.into(), " ");
}
// Add VALUE node
builder.start_node(SyntaxKind::VALUE.into());
let value_ends_with_newline = value.build_content(&mut builder, 2, false);
builder.finish_node(); // VALUE
// Every block-style MAPPING_ENTRY ends with NEWLINE
// Only add if the value content didn't already end with one
let added_newline = if !value_ends_with_newline {
builder.token(SyntaxKind::NEWLINE.into(), "\n");
true
} else {
false
};
builder.finish_node(); // MAPPING_ENTRY
(
SyntaxNode::new_root_mut(builder.finish()),
added_newline || value_ends_with_newline,
)
}
/// Insert a key-value pair immediately after an existing key.
///
/// If `key` already exists in the mapping, its value is updated in-place and
/// it remains at its current position (it is **not** moved to after `after_key`).
/// Returns `true` in both the update and the insert cases.
/// Returns `false` only if `after_key` is not found.
///
/// Use [`move_after`](Self::move_after) if you want
/// an existing entry to be moved to the new position.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn insert_after(
&self,
after_key: impl crate::AsYaml,
key: impl crate::AsYaml,
value: impl crate::AsYaml,
) -> bool {
// Check if the new key already exists - if so, just update it
if self.find_entry_by_key(&key).is_some() {
self.set_as_yaml(&key, &value);
return self.find_entry_by_key(&after_key).is_some();
}
// Key doesn't exist yet - delegate to move_after, which already contains
// the correct insertion logic (including newline handling for entries
// that lack a trailing newline). The two methods differ only in what
// they do when the key *already* exists.
self.move_after(after_key, key, value)
}
/// Insert a key-value pair immediately before an existing key.
///
/// If `key` already exists in the mapping, its value is updated in-place and
/// it remains at its current position (it is **not** moved to before `before_key`).
/// Returns `true` in both the update and the insert cases.
/// Returns `false` only if `before_key` is not found.
///
/// Use [`move_before`](Self::move_before) if you want
/// an existing entry to be moved to the new position.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn insert_before(
&self,
before_key: impl crate::AsYaml,
key: impl crate::AsYaml,
value: impl crate::AsYaml,
) -> bool {
// Key exists → update in-place (don't move).
if self.find_entry_by_key(&key).is_some() {
self.set_as_yaml(&key, &value);
// Only return true if before_key also exists (contract: false when
// reference key is not found).
return self.find_entry_by_key(&before_key).is_some();
}
// Key doesn't exist yet - delegate to move_before, which already contains
// the correct insertion logic. The two methods differ only in what they do
// when the key *already* exists.
self.move_before(before_key, key, value)
}
/// Insert a key-value pair at a specific index (0-based).
///
/// If `key` already exists in the mapping, its value is updated in-place and
/// it remains at its current position (the `index` argument is ignored).
/// If `index` is out of bounds, the entry is appended at the end.
/// This method always succeeds; it never returns an error.
///
/// Mutates in place despite `&self` (see crate docs on interior mutability).
pub fn insert_at_index(
&self,
index: usize,
key: impl crate::AsYaml,
value: impl crate::AsYaml,
) {
// Check if the key already exists - if so, just update it
if self.find_entry_by_key(&key).is_some() {
self.set_as_yaml(&key, &value);
return;
}
// Create the new mapping entry
let flow_context = self.is_flow_style();
let use_explicit_keys = self.uses_explicit_keys();
let key_indent = self.detect_indentation_level();
let new_entry =
MappingEntry::new_at_indent(&key, &value, flow_context, use_explicit_keys, key_indent);
// Flow needs bracket-aware placement (see insert_flow_entry_cst_at);
// the block splice below would drop after `}`.
if flow_context {
let actual_index = index.min(self.entries().count());
let where_at = self
.entries()
.nth(actual_index)
.map_or(FlowInsertPos::End, |e| {
FlowInsertPos::Before(e.syntax().clone())
});
self.insert_flow_entry_cst_at(&new_entry.0, where_at);
return;
}
// Count existing entries to determine actual insertion position
let entry_count = self.entries().count();
let actual_index = index.min(entry_count);
// Find the position in children_with_tokens corresponding to the nth entry
let mut entry_positions = Vec::new();
for (i, child) in self.0.children_with_tokens().enumerate() {
if child
.as_node()
.is_some_and(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
{
entry_positions.push(i);
}
}
// Determine where to insert
let insert_pos = if actual_index < entry_positions.len() {
entry_positions[actual_index]
} else {
self.0.children_with_tokens().count()
};
let mut new_elements = Vec::new();
if insert_pos > 0 {
// Give the previous entry its own trailing NEWLINE so
// the "each block MAPPING_ENTRY owns its terminator"
// invariant holds (see src/nodes/mod.rs); a standalone
// NEWLINE between entries would render fine now but be
// fragile against later reshuffles.
// An INDENT directly before the insertion point belongs to the
// entry being displaced, not to the line above; look past it for
// whatever actually terminates the previous line.
let preceding: Vec<_> = self
.0
.children_with_tokens()
.take(insert_pos)
.filter(|c| c.kind() != SyntaxKind::INDENT)
.collect();
if let Some(prev_node) = preceding.last() {
if let rowan::NodeOrToken::Node(prev) = prev_node {
if prev.kind() == SyntaxKind::MAPPING_ENTRY {
ensure_trailing_newline(prev);
}
} else if let rowan::NodeOrToken::Token(t) = prev_node {
if t.kind() != SyntaxKind::NEWLINE {
new_elements.push(fresh_token(SyntaxKind::NEWLINE, "\n").into());
}
}
}
}
// Add the new entry
new_elements.push(new_entry.0.into());
// Inserting before an existing entry hands the new entry the indent
// that already precedes it, so the displaced entry needs a fresh one.
// Appending at the end has no such donor: the indent goes in front.
let displaces_entry = insert_pos < self.0.children_with_tokens().count();
let indent_level = self.detect_indentation_level();
if indent_level > 0 {
let token = fresh_token(SyntaxKind::INDENT, &" ".repeat(indent_level));
if displaces_entry {
new_elements.push(token.into());
} else {
new_elements.insert(0, token.into());
}
}
// Insert at the calculated position
self.0.splice_children(insert_pos..insert_pos, new_elements);
}
crate::nodes::ast_node_spans!("mapping");
}
impl Default for Mapping {
fn default() -> Self {
Self::new()
}
}
// Iterator trait implementations for Mapping
impl<'a> IntoIterator for &'a Mapping {
type Item = (crate::as_yaml::YamlNode, crate::as_yaml::YamlNode);
type IntoIter =
Box<dyn Iterator<Item = (crate::as_yaml::YamlNode, crate::as_yaml::YamlNode)> + 'a>;
fn into_iter(self) -> Self::IntoIter {
Box::new(self.iter())
}
}
impl AsYaml for Mapping {
fn as_node(&self) -> Option<&SyntaxNode> {
Some(&self.0)
}
fn kind(&self) -> YamlKind {
YamlKind::Mapping
}
fn build_content(
&self,
builder: &mut rowan::GreenNodeBuilder,
indent: usize,
_flow_context: bool,
) -> bool {
builder.start_node(SyntaxKind::MAPPING.into());
crate::as_yaml::copy_node_content_with_indent(builder, &self.0, indent);
builder.finish_node();
self.0
.last_token()
.is_some_and(|t| t.kind() == SyntaxKind::NEWLINE)
}
fn is_inline(&self) -> bool {
ValueNode::is_inline(self)
}
}
#[cfg(test)]
mod tests;