Skip to main content

yaml_edit/nodes/mapping/
mod.rs

1mod entry;
2mod helpers;
3mod movements;
4
5pub(crate) use helpers::build_block_value_node;
6pub(crate) use helpers::flow_form;
7pub(crate) use helpers::{
8    block_scalar_body_shift, drop_tagged_anchor, held_anchor_token, kept_anchor_token,
9    source_anchor_text,
10};
11
12use super::empty_collection::{self, render_empty};
13use super::trivia::{self, Slot};
14use super::{
15    entry_key, entry_value, fresh_token, has_child_token, held_node, insert_children,
16    replace_children, starts_a_flow_collection, Lang, Sequence, SyntaxNode,
17};
18use crate::as_yaml::{AsYaml, YamlKind};
19use crate::lex::SyntaxKind;
20use crate::yaml::{dump_cst_to_string, ValueNode};
21use rowan::ast::AstNode;
22use rowan::GreenNodeBuilder;
23
24ast_node!(
25    MappingEntry,
26    MAPPING_ENTRY,
27    "A key-value pair in a YAML mapping"
28);
29
30ast_node!(Mapping, MAPPING, "A YAML mapping (key-value pairs)");
31
32impl Mapping {
33    /// Dump the CST (Concrete Syntax Tree) structure to a human-readable string.
34    ///
35    /// This is intended for debugging and testing. The output shows the full
36    /// node hierarchy with indentation.
37    pub fn dump_cst(&self) -> String {
38        dump_cst_to_string(&self.0, 0)
39    }
40
41    /// Iterate over all keys in this mapping as [`YamlNode`](crate::as_yaml::YamlNode)s.
42    ///
43    /// Each key is returned as a [`YamlNode`](crate::as_yaml::YamlNode) wrapping
44    /// the underlying CST node, preserving quoting style and other formatting.
45    /// The nodes implement [`AsYaml`](crate::AsYaml), so they can be passed
46    /// back to [`get`](Self::get), [`contains_key`](Self::contains_key), etc.,
47    /// and compared semantically with [`yaml_eq`](crate::yaml_eq).
48    ///
49    /// Prefer [`entries`](Self::entries) when you also need the values, or
50    /// [`iter`](Self::iter) for `(key, value)` pairs as `(YamlNode, YamlNode)`.
51    /// For raw CST nodes, use `pairs()`.
52    pub fn keys(&self) -> impl Iterator<Item = crate::as_yaml::YamlNode> + '_ {
53        self.pairs().filter_map(|(k, _)| held_node(&k))
54    }
55
56    /// Iterate over raw KEY/VALUE syntax nodes for each mapping entry.
57    ///
58    /// Each item is `(key_node, value_node)`, both raw CST wrapper nodes
59    /// (`KEY`/`VALUE`), not the content nodes inside them. Entries with a
60    /// missing key or value (which indicate a parse error in the source) are
61    /// silently skipped.
62    ///
63    /// For most use cases prefer [`iter`](Self::iter) (which yields
64    /// `(YamlNode, YamlNode)` pairs) or [`entries`](Self::entries) (which
65    /// yields typed [`MappingEntry`] handles that give access to the full
66    /// entry including key, value, and mutation methods).
67    pub(crate) fn pairs(&self) -> impl Iterator<Item = (SyntaxNode, SyntaxNode)> + '_ {
68        self.0
69            .children()
70            .filter(|n| n.kind() == SyntaxKind::MAPPING_ENTRY)
71            .filter_map(|entry| Some((entry_key(&entry)?, entry_value(&entry)?)))
72    }
73
74    /// Get the value associated with `key` as a [`YamlNode`](crate::as_yaml::YamlNode).
75    ///
76    /// Returns `None` if the key does not exist.
77    ///
78    /// Matching is semantic but type-strict, so a key's type has to match as
79    /// well as its text: `1` does not find the string key `"1"`, and the
80    /// null key of `: v` is found with
81    /// [`ScalarValue::null`](crate::ScalarValue::null) rather than `""`,
82    /// which finds the distinct empty-string key of `"": v`.
83    ///
84    /// ```rust
85    /// # use std::str::FromStr;
86    /// # use yaml_edit::{Document, ScalarValue};
87    /// let doc = Document::from_str(": a\n\"\": b\n").unwrap();
88    /// let mapping = doc.as_mapping().unwrap();
89    /// assert!(mapping.get(ScalarValue::null()).is_some());
90    /// assert!(mapping.get("").is_some());
91    /// ```
92    pub fn get(&self, key: impl crate::AsYaml) -> Option<crate::as_yaml::YamlNode> {
93        self.get_node(key)
94            .and_then(crate::as_yaml::YamlNode::from_syntax)
95    }
96
97    /// Get the raw content syntax node for `key` (for advanced CST access).
98    ///
99    /// Returns the content node inside the `VALUE` wrapper - i.e. the actual
100    /// `SCALAR`, `MAPPING`, or `SEQUENCE` node. Returns `None` if the key does
101    /// not exist. For most use cases prefer [`get`](Self::get).
102    pub(crate) fn get_node(&self, key: impl crate::AsYaml) -> Option<SyntaxNode> {
103        self.find_entry_by_key(key)
104            // VALUE nodes wrap the actual content, return the content instead
105            .and_then(|entry| entry.value().children().next())
106    }
107
108    /// Get the value for `key` as a nested [`Mapping`].
109    ///
110    /// Returns `None` if the key does not exist or its value is not a mapping.
111    /// A tag on the value is looked through: `key: !custom` over a block
112    /// mapping still gives that mapping.
113    pub fn get_mapping(&self, key: impl crate::AsYaml) -> Option<Mapping> {
114        self.get(key)?.mapping_content()
115    }
116
117    /// Modify a nested mapping in place by applying a closure to it.
118    ///
119    /// Returns `true` if `key` exists and its value is a mapping (and `f` was
120    /// called); returns `false` if the key is missing or its value is not a
121    /// mapping.
122    ///
123    /// Because [`Mapping`] uses interior mutability via rowan's `SyntaxNode`,
124    /// the closure receives a shared reference - mutations are still possible
125    /// through the node's `set`, `remove`, and other `&self` methods.
126    pub fn modify_mapping<F>(&self, key: impl crate::AsYaml, f: F) -> bool
127    where
128        F: FnOnce(&Mapping),
129    {
130        // The closure mutates through rowan's interior mutability, so the
131        // node found here is the one in the tree - nothing to splice back.
132        let Some(nested) = self.get_mapping(key) else {
133            return false;
134        };
135        f(&nested);
136        true
137    }
138
139    /// Get the value for `key` as a nested [`Sequence`].
140    ///
141    /// Returns `None` if the key does not exist or its value is not a sequence.
142    /// A tag on the value is looked through, as for
143    /// [`get_mapping`](Self::get_mapping).
144    pub fn get_sequence(&self, key: impl crate::AsYaml) -> Option<Sequence> {
145        self.get(key)?.sequence_content()
146    }
147
148    /// Returns `true` if this mapping contains an entry with the given key.
149    pub fn contains_key(&self, key: impl crate::AsYaml) -> bool {
150        self.find_entry_by_key(key).is_some()
151    }
152
153    /// Iterate over the raw `KEY` wrapper nodes for all entries.
154    ///
155    /// For most use cases prefer [`keys`](Self::keys) which yields
156    /// [`YamlNode`](crate::as_yaml::YamlNode) keys (formatting-preserving but
157    /// comparable via `yaml_eq`), or [`entries`](Self::entries) which yields
158    /// full [`MappingEntry`] handles.
159    pub(crate) fn key_nodes(&self) -> impl Iterator<Item = SyntaxNode> + '_ {
160        self.pairs().map(|(k, _)| k)
161    }
162
163    /// Check if the mapping is empty
164    pub fn is_empty(&self) -> bool {
165        self.pairs().next().is_none()
166    }
167
168    /// Get the number of key-value pairs in this mapping
169    pub fn len(&self) -> usize {
170        self.pairs().count()
171    }
172
173    /// Iterate over the values in this mapping as [`YamlNode`](crate::as_yaml::YamlNode)s.
174    ///
175    /// Only entries whose value can be successfully wrapped in a `YamlNode` are
176    /// yielded; malformed or unrecognised value nodes are silently skipped.
177    /// Use [`iter`](Self::iter) to get both the key and value simultaneously, or
178    /// `pairs()` for the raw `SyntaxNode` pairs.
179    pub fn values(&self) -> impl Iterator<Item = crate::as_yaml::YamlNode> + '_ {
180        self.pairs().filter_map(|(_, v)| held_node(&v))
181    }
182
183    /// Iterate over `(key, value)` pairs, both as [`YamlNode`](crate::as_yaml::YamlNode)s.
184    ///
185    /// Entries that cannot be fully wrapped (malformed key or value nodes) are
186    /// silently skipped. For raw CST nodes, use `pairs()`; for
187    /// typed entry handles, prefer [`entries`](Self::entries).
188    pub fn iter(
189        &self,
190    ) -> impl Iterator<Item = (crate::as_yaml::YamlNode, crate::as_yaml::YamlNode)> + '_ {
191        self.pairs()
192            .filter_map(|(k, v)| Some((held_node(&k)?, held_node(&v)?)))
193    }
194
195    /// Create a new empty mapping
196    pub fn new() -> Self {
197        Self::new_pending_block()
198    }
199
200    /// An empty mapping that renders as `{}` and stays flow when filled.
201    ///
202    /// Use this for a mapping that is meant to be flow-style in the output,
203    /// including one that is left empty.
204    pub fn new_flow() -> Self {
205        Self::empty_with_brace_text("{", "}")
206    }
207
208    /// An empty mapping that becomes a block mapping once an entry is added.
209    ///
210    /// YAML has no block syntax for an empty mapping: block collections are
211    /// written as their entries, so with none left there is nothing to write,
212    /// and a bare `key:` reads back as null. An empty mapping is therefore
213    /// `{}` whatever its eventual style, and block-vs-flow only becomes a
214    /// real choice once there is an entry.
215    ///
216    /// This renders as exactly `{}`, plus a zero-width token that marks it as
217    /// destined for block style. [`Mapping::set`] rewrites it into block form
218    /// when the first entry arrives; a `{}` that came from the source has no
219    /// such marker and keeps its flow style.
220    ///
221    /// A block mapping that loses its last entry to `remove` or `clear` is
222    /// written the same way, marker included.
223    ///
224    /// The marker lives only in the tree. Serializing and re-parsing yields
225    /// an ordinary `{}`, which stays flow, since YAML has nowhere to record
226    /// the intent.
227    pub fn new_pending_block() -> Self {
228        let mut builder = GreenNodeBuilder::new();
229        builder.start_node(SyntaxKind::MAPPING.into());
230        builder.token(SyntaxKind::LEFT_BRACE.into(), "{");
231        // Zero-width sentinel: renders as nothing, so this is still exactly
232        // `{}` in the text, but marks the mapping as one that should become
233        // block when it gets its first entry.
234        builder.token(SyntaxKind::WHITESPACE.into(), "");
235        builder.token(SyntaxKind::RIGHT_BRACE.into(), "}");
236        builder.finish_node();
237        Mapping(SyntaxNode::new_root_mut(builder.finish()))
238    }
239
240    fn empty_with_brace_text(open: &str, close: &str) -> Self {
241        let mut builder = GreenNodeBuilder::new();
242        builder.start_node(SyntaxKind::MAPPING.into());
243        builder.token(SyntaxKind::LEFT_BRACE.into(), open);
244        builder.token(SyntaxKind::RIGHT_BRACE.into(), close);
245        builder.finish_node();
246        Mapping(SyntaxNode::new_root_mut(builder.finish()))
247    }
248
249    /// Wrap a flow pair in braces, so that it reads as one mapping however
250    /// many entries it ends up with: `[a: 1, b: 2]` would be two.
251    fn brace_flow_pair(&self) {
252        if !is_flow_pair(&self.0) {
253            return;
254        }
255        let end = self.0.children_with_tokens().count();
256        insert_children(
257            &self.0,
258            end,
259            vec![fresh_token(SyntaxKind::RIGHT_BRACE, "}").into()],
260        );
261        insert_children(
262            &self.0,
263            0,
264            vec![fresh_token(SyntaxKind::LEFT_BRACE, "{").into()],
265        );
266    }
267
268    /// Reorder fields according to the specified order.
269    ///
270    /// Fields not in the order list will appear after the ordered fields,
271    /// in their original relative order.
272    ///
273    /// An alias that ends up before the node it refers to becomes a copy of
274    /// it, anchor included, and the node an alias where it can.
275    pub fn reorder_fields<I, K>(&self, order: I)
276    where
277        I: IntoIterator<Item = K>,
278        K: crate::AsYaml,
279    {
280        let order_keys: Vec<K> = order.into_iter().collect();
281        let entry_has_key = |entry: &SyntaxNode, key: &K| {
282            entry
283                .children()
284                .find(|n| n.kind() == SyntaxKind::KEY)
285                .is_some_and(|k| key_content_matches(&k, key))
286        };
287        // Take each named key's entry in the order given; anything the
288        // caller did not name keeps its relative position at the end.
289        let mut rest: Vec<SyntaxNode> = self.entries().map(|e| e.0).collect();
290        let mut ordered: Vec<SyntaxNode> = order_keys
291            .iter()
292            .filter_map(|key| {
293                let pos = rest.iter().position(|entry| entry_has_key(entry, key))?;
294                Some(rest.remove(pos))
295            })
296            .collect();
297        ordered.extend(rest);
298        self.arrange_entries(&ordered);
299    }
300}
301
302/// Is `node` a single pair in a flow sequence (`[a: 1]`), a flow mapping
303/// written without braces?
304pub(crate) fn is_flow_pair(node: &SyntaxNode) -> bool {
305    node.kind() == SyntaxKind::MAPPING
306        && !starts_a_flow_collection(node)
307        && node
308            .parent()
309            .filter(|p| p.kind() == SyntaxKind::SEQUENCE_ENTRY)
310            .and_then(|p| p.parent())
311            .is_some_and(|seq| starts_a_flow_collection(&seq))
312}
313
314/// Check whether the CST key node matches `key` using semantic equality.
315///
316/// An alias equals no node under `yaml_eq`, so an alias in a key is matched
317/// by an alias of the same name instead, not by the node it refers to:
318/// `*a` by `*a`, and `[*a]` by `[*a]`.
319///
320/// `key_node` may be a raw KEY wrapper.
321pub(super) fn key_content_matches(key_node: &SyntaxNode, key: impl crate::AsYaml) -> bool {
322    use crate::as_yaml::lookup_identity;
323    let Some(own) = lookup_identity(key_node) else {
324        return false;
325    };
326    let given = match key.value_node() {
327        Some(node) => lookup_identity(&node),
328        None => crate::as_yaml::identity_of(&key, None).ok().flatten(),
329    };
330    given.is_some_and(|given| given == own)
331}
332
333/// The anchor and tag on a KEY node, which sit in KEY itself or in the
334/// TAGGED_NODE it holds.
335fn key_annotations(key: &SyntaxNode) -> (Option<String>, Option<String>) {
336    let tagged = key
337        .children()
338        .next()
339        .filter(|n| n.kind() == SyntaxKind::TAGGED_NODE);
340    let tokens = key
341        .children_with_tokens()
342        .chain(tagged.iter().flat_map(|n| n.children_with_tokens()))
343        .filter_map(|c| c.into_token());
344    let (mut anchor, mut tag) = (None, None);
345    for token in tokens {
346        match token.kind() {
347            SyntaxKind::ANCHOR => anchor = anchor.or(Some(token.text().to_string())),
348            SyntaxKind::TAG => tag = tag.or(Some(token.text().to_string())),
349            _ => {}
350        }
351    }
352    (anchor, tag)
353}
354
355/// `key` under `tag`, if it has no tag of its own and is still the same key
356/// with it: `!!str` suits a string but not `1`, and a custom tag suits
357/// nothing given untagged.
358fn retagged_key(
359    tag: &str,
360    key: &impl crate::AsYaml,
361    flow: Option<crate::as_yaml::FlowQuoting>,
362) -> Option<crate::as_yaml::YamlNode> {
363    if matches!(key.kind(), YamlKind::Tagged(_)) {
364        return None;
365    }
366    let mut builder = GreenNodeBuilder::new();
367    builder.start_node(SyntaxKind::TAGGED_NODE.into());
368    builder.token(SyntaxKind::TAG.into(), tag);
369    builder.token(SyntaxKind::WHITESPACE.into(), " ");
370    super::build_key_content(&mut builder, key, 0, flow);
371    builder.finish_node();
372    let tagged = crate::as_yaml::YamlNode::from_syntax(SyntaxNode::new_root_mut(builder.finish()))?;
373    crate::as_yaml::yaml_eq(&tagged, key).then_some(tagged)
374}
375
376impl Mapping {
377    /// Check if this mapping is in flow style (JSON/inline format with `{}`).
378    ///
379    /// Returns `true` if the mapping uses flow style (e.g., `{key: value}`,
380    /// or a single pair in a flow sequence such as `[key: value]`), `false`
381    /// if it uses block style (e.g., `key: value`).
382    pub fn is_flow_style(&self) -> bool {
383        // Flow-style mappings start with LEFT_BRACE token. A block
384        // placeholder is `{}` in the text but is destined to become block, so
385        // it does not count as flow.
386        (starts_a_flow_collection(&self.0) && !empty_collection::is_block_placeholder(&self.0))
387            || is_flow_pair(&self.0)
388    }
389
390    /// Find the [`MappingEntry`] whose key matches `key`, or `None` if not found.
391    ///
392    /// Matching is semantic (quoting style is ignored), so `"foo"`, `'foo'`,
393    /// and `foo` all match the scalar `"foo"`.
394    pub fn find_entry_by_key(&self, key: impl crate::AsYaml) -> Option<MappingEntry> {
395        self.0
396            .children()
397            .filter_map(MappingEntry::cast)
398            .find(|entry| entry.key().is_some_and(|k| key_content_matches(&k, &key)))
399    }
400
401    /// Find all entries with a given key.
402    ///
403    /// Returns an iterator over all [`MappingEntry`] instances that match the
404    /// given key. This is useful for handling duplicate keys in YAML (which
405    /// are allowed by the spec but semantically ambiguous).
406    ///
407    /// Matching is semantic (quoting style is ignored), so `"foo"`, `'foo'`,
408    /// and `foo` all match the scalar `"foo"`.
409    ///
410    /// # Example
411    ///
412    /// ```rust
413    /// # use std::str::FromStr;
414    /// # use yaml_edit::Document;
415    /// let yaml = r#"
416    /// Reference: First
417    /// Reference: Second
418    /// Reference: Third
419    /// "#;
420    ///
421    /// let doc = Document::from_str(yaml).unwrap();
422    /// let mapping = doc.as_mapping().unwrap();
423    ///
424    /// // Collect all Reference entries
425    /// let refs: Vec<_> = mapping.find_all_entries_by_key("Reference").collect();
426    /// assert_eq!(refs.len(), 3);
427    ///
428    /// // Remove all but the first occurrence
429    /// let _: Vec<()> = refs.into_iter().skip(1).map(|entry| entry.remove()).collect();
430    /// ```
431    pub fn find_all_entries_by_key<'a>(
432        &'a self,
433        key: impl crate::AsYaml + 'a,
434    ) -> impl Iterator<Item = MappingEntry> + 'a {
435        self.0
436            .children()
437            .filter_map(MappingEntry::cast)
438            .filter(move |entry| entry.key().is_some_and(|k| key_content_matches(&k, &key)))
439    }
440
441    /// Iterate over all entries in this mapping as typed [`MappingEntry`] handles.
442    ///
443    /// Each [`MappingEntry`] gives access to the key, value, and mutation
444    /// methods for that entry. For decoded `(key, value)` pairs, prefer
445    /// [`iter`](Self::iter); for raw CST nodes, use `pairs()`.
446    pub fn entries(&self) -> impl Iterator<Item = MappingEntry> {
447        self.0.children().filter_map(MappingEntry::cast)
448    }
449
450    /// Return an [`Entry`](crate::Entry) view into the entry for `key`.
451    ///
452    /// Mirrors [`std::collections::BTreeMap::entry`], enabling
453    /// insert-or-update patterns while preserving formatting.
454    ///
455    /// ```rust
456    /// use std::str::FromStr;
457    /// use yaml_edit::Document;
458    ///
459    /// let doc = Document::from_str("name: Alice\n").unwrap();
460    /// let mapping = doc.as_mapping().unwrap();
461    ///
462    /// mapping.entry("age").or_insert(30);
463    /// mapping.entry("name").or_insert("Bob");
464    ///
465    /// assert_eq!(doc.to_string(), "name: Alice\nage: 30\n");
466    /// ```
467    pub fn entry<K: crate::AsYaml>(&self, key: K) -> crate::Entry<'_, K> {
468        match self.find_entry_by_key(&key) {
469            Some(entry) => crate::Entry::Occupied(crate::OccupiedEntry {
470                mapping: self,
471                entry,
472            }),
473            None => crate::Entry::Vacant(crate::VacantEntry { mapping: self, key }),
474        }
475    }
476
477    /// Find the child index of a mapping entry by its key.
478    ///
479    /// Returns the index within the mapping's children (including non-entry
480    /// tokens like whitespace), or `None` if no entry with the given key exists.
481    /// This index is suitable for use with `splice_children`.
482    pub fn find_entry_index_by_key(&self, key: impl crate::AsYaml) -> Option<usize> {
483        // Look through all children (not just entries, to get accurate index)
484        self.0
485            .children_with_tokens()
486            .enumerate()
487            .find_map(|(i, child)| {
488                let node = child.as_node()?;
489                if node.kind() != SyntaxKind::MAPPING_ENTRY {
490                    return None;
491                }
492                let entry = MappingEntry::cast(node.clone())?;
493                if entry.key().is_some_and(|k| key_content_matches(&k, &key)) {
494                    Some(i)
495                } else {
496                    None
497                }
498            })
499    }
500
501    /// Set a key-value pair, replacing the existing value if the key exists or
502    /// appending a new entry if it does not. Accepts any value that implements
503    /// [`AsYaml`](crate::AsYaml) - scalars, mappings, sequences, etc.
504    ///
505    /// This method always succeeds; it never silently ignores input. See also
506    /// [`insert_after`](Self::insert_after) and [`insert_before`](Self::insert_before)
507    /// which return `bool` to indicate whether the anchor key was found.
508    ///
509    /// Mutates in place despite `&self` (see crate docs on interior mutability).
510    ///
511    /// `set` replaces the value with the node you pass. It does not infer
512    /// YAML 1.1 merge keys from a resolved map. To keep identity, pass an
513    /// alias node (`*name`) or a mapping that already contains `<<: *name`.
514    /// Merge **reads** (`get_resolved()`, `merged()`) stay separate from
515    /// this CST replace.
516    ///
517    /// An anchor on the replaced value stays, on the new value, so aliases
518    /// to it still resolve: `b: &x 2` set to `6` gives `b: &x 6`. A node
519    /// value that has an anchor of its own keeps it only if the old value
520    /// had none. The first alias to an anchor deeper in the old value
521    /// becomes a copy of the anchored node: `b: {c: &y 1}` and `d: *y` give
522    /// `b: 6` and `d: &y 1`.
523    ///
524    /// ```
525    /// use std::str::FromStr;
526    /// use yaml_edit::Document;
527    ///
528    /// let doc = Document::from_str(
529    ///     "shared: &shared\n  timeout: 30\n  retries: 3\nservice_a: old\n",
530    /// )
531    /// .unwrap();
532    /// let mapping = doc.as_mapping().unwrap();
533    /// let merge = Document::from_str("<<: *shared\ntimeout: 60\n").unwrap();
534    /// mapping.set("service_a", merge.as_mapping().unwrap());
535    /// assert_eq!(
536    ///     doc.to_string(),
537    ///     "shared: &shared\n  timeout: 30\n  retries: 3\nservice_a:\n  <<: *shared\n  timeout: 60\n"
538    /// );
539    /// ```
540    pub fn set(&self, key: impl crate::AsYaml, value: impl crate::AsYaml) {
541        // An existing entry with this key takes the value in place.
542        let Some(entry) = self.find_entry_by_key(&key) else {
543            self.insert_new(Slot::End, key, value);
544            return;
545        };
546        self.styled_value(&value, |v, flow_context| entry.set_value(v, flow_context));
547    }
548
549    /// Detect if this mapping uses explicit key indicators (?)
550    pub(super) fn uses_explicit_keys(&self) -> bool {
551        // Only block explicit keys count, whose `?` is a child of
552        // MAPPING_ENTRY. In flow context the parser puts it inside KEY, and
553        // new entries there are written implicit.
554        for child in self.0.children() {
555            if child.kind() == SyntaxKind::MAPPING_ENTRY {
556                // Check if this entry has a QUESTION token as a child
557                if has_child_token(&child, |k| k == SyntaxKind::QUESTION) {
558                    return true;
559                }
560            }
561        }
562        false
563    }
564
565    /// Hand `put` `value` as an entry of this mapping holds it, in flow form
566    /// in a flow mapping, and whether the mapping is flow. The flow form is
567    /// shifted to the entry's line when put in, so its continuation lines
568    /// are given relative to that.
569    fn styled_value(&self, value: &impl crate::AsYaml, put: impl FnOnce(&dyn crate::AsYaml, bool)) {
570        let flow_context = self.is_flow_style();
571        let flow = flow_context
572            .then(|| crate::nodes::flow_quoting(&self.0))
573            .and_then(|q| flow_form(value, 2, q));
574        match &flow {
575            Some(flow) => put(flow, flow_context),
576            None => put(value, flow_context),
577        }
578    }
579
580    /// Add an entry for `key`, which is not in this mapping yet, at `slot`,
581    /// written in the mapping's style.
582    fn insert_new(&self, slot: Slot, key: impl crate::AsYaml, value: impl crate::AsYaml) {
583        // A placeholder from `Mapping::new_pending_block` turns into a real
584        // block mapping now that it has an entry to hold, before the entry
585        // is laid out.
586        empty_collection::convert_placeholder_to_block(&self.0);
587        let flow = self
588            .is_flow_style()
589            .then(|| crate::nodes::flow_quoting(&self.0));
590        // The column of the key tells the constructor how far to shift a
591        // node-backed block value.
592        let new_entry = MappingEntry::new_in(
593            key,
594            value,
595            flow,
596            self.uses_explicit_keys(),
597            self.detect_indentation_level(),
598        );
599        self.attach(&new_entry.0, slot);
600    }
601
602    /// Splice `new_entry` into this mapping at `slot`.
603    pub(super) fn attach(&self, new_entry: &SyntaxNode, slot: Slot) {
604        if self.is_flow_style() {
605            self.brace_flow_pair();
606            trivia::attach_flow_entry(&self.0, slot, new_entry);
607        } else {
608            trivia::attach_entry(&self.0, slot, new_entry);
609        }
610    }
611
612    /// Set a key-value pair with field ordering support
613    /// If the key exists, updates its value. If the key doesn't exist, inserts it
614    /// at the correct position based on the provided field order.
615    /// Fields not in the order list are placed at the end.
616    pub fn set_with_field_order<I, K>(
617        &self,
618        key: impl crate::AsYaml,
619        value: impl crate::AsYaml,
620        field_order: I,
621    ) where
622        I: IntoIterator<Item = K>,
623        K: crate::AsYaml,
624    {
625        // Collect field_order so we can iterate it multiple times.
626        let field_order: Vec<K> = field_order.into_iter().collect();
627
628        // An existing key just takes the new value, wherever it sits.
629        if self.find_entry_by_key(&key).is_some() {
630            self.set(&key, &value);
631            return;
632        }
633
634        let Some(key_index) = field_order
635            .iter()
636            .position(|field| crate::as_yaml::yaml_eq(&key, field))
637        else {
638            self.insert_new(Slot::End, key, value);
639            return;
640        };
641        // The nearest preceding field that is present decides where the new
642        // entry goes. With none, it goes before the first present field that
643        // the order puts after it, and with no ordered key present at the end.
644        let before_later = || {
645            self.entries().find_map(|entry| {
646                let key_node = entry.key()?;
647                let pos = field_order
648                    .iter()
649                    .position(|field| key_content_matches(&key_node, field))?;
650                (pos > key_index).then_some(Slot::Before(entry.0))
651            })
652        };
653        let slot = field_order[..key_index]
654            .iter()
655            .rev()
656            .find_map(|field| self.find_entry_by_key(field))
657            .map(|entry| Slot::After(entry.0))
658            .or_else(before_later)
659            .unwrap_or(Slot::End);
660        self.insert_new(slot, key, value);
661    }
662
663    /// Detect the indentation level (in spaces) used by entries in this mapping.
664    ///
665    /// Returns `0` for root-level mappings where entries have no leading indentation.
666    pub fn detect_indentation_level(&self) -> usize {
667        trivia::entry_column(&self.0)
668    }
669
670    /// Insert a key-value pair at a specific index (0-based), preserving formatting.
671    ///
672    /// If `new_key` already exists in the mapping, the existing entry is replaced
673    /// with a newly built entry at the **same position** (the `index` argument is
674    /// ignored). Surrounding whitespace in the file is preserved, but the entry
675    /// node itself is rebuilt (comments attached to the old entry may be lost).
676    /// An anchor on the old value stays on the new one, as with
677    /// [`set`](Self::set).
678    /// If `index` is out of bounds, the entry is appended at the end.
679    pub fn insert_at_index_preserving(
680        &self,
681        index: usize,
682        new_key: impl crate::AsYaml,
683        new_value: impl crate::AsYaml,
684    ) {
685        match self.find_entry_by_key(&new_key) {
686            Some(old) => {
687                self.replace_entry(&old.0, new_key, new_value, true);
688            }
689            None => self.insert_new_entry_at(index, new_key, new_value),
690        }
691    }
692
693    /// Replace `old`, an entry of this mapping, with a new entry built the
694    /// way `set` builds one, in the same place, and return it. If
695    /// `keep_anchor` is set, an anchor on the old value goes on the new one
696    /// unless that is an alias, as with `set`; otherwise the old value goes
697    /// as with `remove`.
698    pub(super) fn replace_entry(
699        &self,
700        old: &SyntaxNode,
701        key: impl crate::AsYaml,
702        value: impl crate::AsYaml,
703        keep_anchor: bool,
704    ) -> SyntaxNode {
705        let kept = MappingEntry::cast(old.clone())
706            .map(|e| e.value())
707            .filter(|_| keep_anchor)
708            .and_then(|v| kept_anchor_token(&v, &value));
709        let anchor = kept.as_ref().map(|t| t.text().to_string());
710        let mut new = None;
711        crate::nodes::kept_aliases::keeping_aliases(old, kept, || {
712            // The entry is built without the value's anchor; putting the
713            // value in again settles which anchor it gets, as in set_value.
714            let entry = MappingEntry(self.splice_in_entry(old, key, &value));
715            self.put_value(&entry, &value, anchor.as_deref());
716            new = Some(entry.0.clone());
717            Some(entry.value())
718        });
719        new.expect("the edit ran")
720    }
721
722    /// Replace the value of `entry`, an entry of this mapping, with `value`
723    /// under `anchor`, as `set` does.
724    pub(super) fn put_value(
725        &self,
726        entry: &MappingEntry,
727        value: impl crate::AsYaml,
728        anchor: Option<&str>,
729    ) {
730        self.styled_value(&value, |v, flow_context| {
731            entry.replace_value_under(v, flow_context, anchor)
732        });
733    }
734
735    /// The edit of [`replace_entry`](Self::replace_entry), without the
736    /// kept anchor. Returns the new entry.
737    fn splice_in_entry(
738        &self,
739        old: &SyntaxNode,
740        key: impl crate::AsYaml,
741        value: impl crate::AsYaml,
742    ) -> SyntaxNode {
743        let flow_context = self.is_flow_style();
744        let new_entry = MappingEntry::new_in(
745            key,
746            value,
747            flow_context.then(|| crate::nodes::flow_quoting(&self.0)),
748            self.uses_explicit_keys(),
749            self.detect_indentation_level(),
750        )
751        .0;
752        if flow_context {
753            // The separator to the next entry lives in the entry before it,
754            // as does the line break ending its line.
755            let mut separator: Vec<_> = old
756                .children_with_tokens()
757                .skip_while(|c| c.kind() != SyntaxKind::COMMA)
758                .collect();
759            if separator.is_empty() {
760                separator.extend(
761                    old.last_child_or_token()
762                        .filter(|c| c.kind() == SyntaxKind::NEWLINE),
763                );
764            }
765            for c in &separator {
766                c.detach();
767            }
768            crate::nodes::append_children(&new_entry, separator);
769        } else {
770            // The new entry brings its own line break, unless the old one
771            // ended the input without one.
772            if !trivia::ends_with_line_break(old) {
773                let last = new_entry
774                    .last_child_or_token()
775                    .filter(|c| c.kind() == SyntaxKind::NEWLINE);
776                if let Some(last) = last {
777                    last.detach();
778                }
779            }
780        }
781        let i = old.index();
782        replace_children(&self.0, i..i + 1, vec![new_entry.clone().into()]);
783        new_entry
784    }
785
786    /// Remove a key-value pair, returning the removed entry.
787    ///
788    /// Returns `Some(entry)` if the key existed and was removed, or `None` if
789    /// the key was not found. The returned [`MappingEntry`] is detached from
790    /// the tree; callers can inspect its key and value or re-insert it
791    /// elsewhere.
792    ///
793    /// The first alias to an anchor in the removed entry becomes a copy of
794    /// the anchored node, so it and later aliases keep their value.
795    ///
796    /// Mutates in place despite `&self` (see crate docs on interior mutability).
797    pub fn remove(&self, key: impl crate::AsYaml) -> Option<MappingEntry> {
798        let entry = self.entries().find(|e| e.key_matches(&key))?;
799        self.remove_entry(entry.syntax());
800        Some(entry)
801    }
802
803    /// Splice `removed`, an entry of this mapping, out of it with the
804    /// trivia that belongs to it.
805    fn remove_entry(&self, removed: &SyntaxNode) {
806        // Without its pair, a flow pair would leave `[]`, an empty sequence.
807        if is_flow_pair(&self.0) {
808            self.brace_flow_pair();
809        }
810        crate::nodes::kept_aliases::keeping_aliases(removed, None, || {
811            trivia::detach_entry(&self.0, removed);
812            None
813        });
814    }
815
816    /// Remove the nth occurrence of a key, returning the removed entry.
817    ///
818    /// Returns `Some(entry)` if the nth occurrence exists and was removed,
819    /// or `None` if there are fewer than `n+1` occurrences of the key.
820    /// The index `n` is 0-based (n=0 removes the first occurrence, n=1 removes
821    /// the second, etc.).
822    ///
823    /// This is useful for handling duplicate keys in YAML. While duplicate keys
824    /// are semantically ambiguous, they are allowed by the YAML spec, and this
825    /// method provides fine-grained control over which occurrence to remove.
826    ///
827    /// # Example
828    ///
829    /// ```rust
830    /// # use std::str::FromStr;
831    /// # use yaml_edit::Document;
832    /// let yaml = r#"
833    /// Reference: First
834    /// Reference: Second
835    /// Reference: Third
836    /// "#;
837    ///
838    /// let doc = Document::from_str(yaml).unwrap();
839    /// let mapping = doc.as_mapping().unwrap();
840    ///
841    /// // Remove the second occurrence (index 1)
842    /// let removed = mapping.remove_nth_occurrence("Reference", 1);
843    /// assert!(removed.is_some());
844    ///
845    /// // Now only two Reference entries remain
846    /// let count = mapping.find_all_entries_by_key("Reference").count();
847    /// assert_eq!(count, 2);
848    /// ```
849    ///
850    /// Mutates in place despite `&self` (see crate docs on interior mutability).
851    pub fn remove_nth_occurrence(&self, key: impl crate::AsYaml, n: usize) -> Option<MappingEntry> {
852        let entry = self.entries().filter(|e| e.key_matches(&key)).nth(n)?;
853        self.remove_entry(entry.syntax());
854        Some(entry)
855    }
856
857    /// Remove all key-value pairs from this mapping.
858    ///
859    /// Mutates in place despite `&self` (see crate docs on interior mutability).
860    pub fn clear(&self) {
861        let line_break = self
862            .entries()
863            .last()
864            .and_then(|e| trivia::line_break(e.syntax()));
865        // Entries are removed one by one, as keeping aliases resolving may
866        // rewrite a later key.
867        while let Some(entry) = self.entries().next() {
868            self.remove_entry(entry.syntax());
869        }
870        render_empty(&self.0, line_break.as_deref());
871    }
872
873    /// Rename a key while preserving its value and formatting.
874    ///
875    /// The new key is built using the same `AsYaml` infrastructure as other
876    /// write methods, so quoting and escaping are handled automatically.
877    /// Returns `true` if the key was found and renamed, `false` if `old_key`
878    /// does not exist.
879    ///
880    /// If `new_key` differs from `old_key` and is already present, the
881    /// existing `new_key` entry is removed, as with [`set`](Self::set) and
882    /// [`move_after`](Self::move_after), so the rename does not create a
883    /// duplicate key. The renamed entry keeps its position, value and
884    /// comments.
885    ///
886    /// The key keeps its anchor, so aliases to it still resolve; an anchor
887    /// on a `new_key` node is used only if the old key had none. The key's
888    /// tag is kept if `new_key` has no tag of its own and still means the
889    /// same with it: `!!str a` renamed to `"b"` gives `!!str b`, but renamed
890    /// to `1` gives `1`, as `!!str 1` would be a string. The first alias to
891    /// an anchor deeper in the old key becomes a copy of the anchored node.
892    ///
893    /// ```
894    /// # use std::str::FromStr;
895    /// # use yaml_edit::Document;
896    /// let doc = Document::from_str("a: 1\nb: 2\nc: 3\n").unwrap();
897    /// assert!(doc.as_mapping().unwrap().rename_key("a", "b"));
898    /// assert_eq!(doc.to_string(), "b: 1\nc: 3\n");
899    /// ```
900    ///
901    /// Mutates in place despite `&self` (see crate docs on interior mutability).
902    pub fn rename_key(&self, old_key: impl crate::AsYaml, new_key: impl crate::AsYaml) -> bool {
903        let Some(node) = self.find_entry_by_key(&old_key).map(|e| e.0) else {
904            return false;
905        };
906
907        let renames_to_itself = entry_key(&node).is_some_and(|k| key_content_matches(&k, &new_key));
908        if !renames_to_itself {
909            self.remove_other_entries(&node, &new_key);
910        }
911        let old = entry_key(&node).expect("a mapping entry has a key");
912        let kept = held_anchor_token(&old);
913        crate::nodes::kept_aliases::keeping_aliases(&old, kept, || {
914            Some(self.replace_key(&node, new_key, None))
915        });
916        true
917    }
918
919    /// Replace the key of `node`, an entry of this mapping, with `new_key`
920    /// under `anchor`, and return the new KEY.
921    pub(crate) fn replace_key(
922        &self,
923        node: &SyntaxNode,
924        new_key: impl crate::AsYaml,
925        anchor: Option<&str>,
926    ) -> SyntaxNode {
927        if let Some(key) = flow_form(&new_key, 2, crate::nodes::flow_quoting(&self.0)) {
928            return self.replace_key(node, key, anchor);
929        }
930        let indent = self.detect_indentation_level();
931        // A key spanning lines has to be explicit, with the `:` on a line
932        // of its own.
933        let make_explicit = !self.is_flow_style()
934            && !has_child_token(node, |k| k == SyntaxKind::QUESTION)
935            && super::key_spans_lines(&new_key);
936        let old_key = entry_key(node).expect("a mapping entry has a key");
937        let mut builder = GreenNodeBuilder::new();
938        builder.start_node(SyntaxKind::ROOT.into());
939        if make_explicit {
940            builder.token(SyntaxKind::QUESTION.into(), "?");
941            builder.token(SyntaxKind::WHITESPACE.into(), " ");
942        }
943        let flow = self
944            .is_flow_style()
945            .then(|| crate::nodes::flow_quoting(&self.0));
946        Self::rebuild_key(&mut builder, &old_key, &new_key, anchor, flow);
947        if make_explicit {
948            builder.token(SyntaxKind::NEWLINE.into(), "\n");
949            if indent > 0 {
950                builder.token(SyntaxKind::INDENT.into(), &" ".repeat(indent));
951            }
952        }
953        builder.finish_node();
954        let built = SyntaxNode::new_root_mut(builder.finish());
955        let new_key = built
956            .children()
957            .find(|n| n.kind() == SyntaxKind::KEY)
958            .expect("a KEY was just built");
959        if anchor.is_some() {
960            drop_tagged_anchor(&new_key);
961        }
962
963        // Whitespace between the key and the `:` would now start the `:`
964        // line. Detached one by one, as a multi-child splice can skip some.
965        if make_explicit {
966            let stale: Vec<_> = old_key
967                .siblings_with_tokens(rowan::Direction::Next)
968                .skip(1)
969                .map_while(|c| {
970                    c.into_token()
971                        .filter(|t| t.kind() == SyntaxKind::WHITESPACE)
972                })
973                .collect();
974            for token in stale {
975                token.detach();
976            }
977        }
978        let old_ended_line = trivia::ends_with_line_break(&old_key);
979        let i = old_key.index();
980        replace_children(
981            node,
982            i..i + 1,
983            built.children_with_tokens().collect::<Vec<_>>(),
984        );
985        if has_child_token(node, |k| k == SyntaxKind::QUESTION) {
986            Self::settle_explicit_key_line(&new_key, old_ended_line);
987        }
988        if self.is_flow_style() {
989            Self::separate_adjacent_value(&new_key);
990        }
991        crate::nodes::separate_key_from_colon(node);
992        new_key
993    }
994
995    /// Put a space after the `:` following `key` if the value starts right
996    /// after it and `key` is not JSON-like: only after a quoted scalar or a
997    /// flow collection does `"a":b` read as a key and a value, while `a:b`
998    /// is one plain scalar.
999    fn separate_adjacent_value(key: &SyntaxNode) {
1000        let trivia = |k: SyntaxKind| {
1001            matches!(
1002                k,
1003                SyntaxKind::WHITESPACE
1004                    | SyntaxKind::INDENT
1005                    | SyntaxKind::NEWLINE
1006                    | SyntaxKind::COMMENT
1007            )
1008        };
1009        // The `:` may be on a later line, after a comment.
1010        let Some(colon) = key
1011            .siblings_with_tokens(rowan::Direction::Next)
1012            .skip(1)
1013            .find(|c| !trivia(c.kind()))
1014            .and_then(|c| c.into_token())
1015            .filter(|t| t.kind() == SyntaxKind::COLON)
1016        else {
1017            return;
1018        };
1019        let json_like = key
1020            .descendants_with_tokens()
1021            .filter_map(|c| c.into_token())
1022            .filter(|t| !t.text().is_empty() && !trivia(t.kind()))
1023            .last()
1024            .is_some_and(|t| {
1025                matches!(
1026                    t.kind(),
1027                    SyntaxKind::RIGHT_BRACKET | SyntaxKind::RIGHT_BRACE
1028                ) || (t.kind() == SyntaxKind::STRING && t.text().starts_with(['"', '\'']))
1029            });
1030        let value_adjacent = std::iter::successors(colon.next_token(), |t| t.next_token())
1031            .find_map(|t| t.text().chars().next())
1032            .is_some_and(|c| !c.is_whitespace() && !matches!(c, ',' | ']' | '}'));
1033        if !json_like && value_adjacent {
1034            let i = colon.index() + 1;
1035            insert_children(
1036                &colon.parent().expect("a COLON is in an entry"),
1037                i,
1038                vec![fresh_token(SyntaxKind::WHITESPACE, " ").into()],
1039            );
1040        }
1041    }
1042
1043    /// Fix up the line of a block explicit key whose content was replaced.
1044    ///
1045    /// A block key (`? - a\n`) ends its own line, while the entry holds the
1046    /// line break after an inline one (`? a` NEWLINE). An empty key may
1047    /// follow the `?` directly, a non-empty one needs a space.
1048    fn settle_explicit_key_line(key: &SyntaxNode, old_ended_line: bool) {
1049        let entry = key.parent().expect("a KEY is in an entry");
1050        let before = key.prev_sibling_or_token();
1051        if before
1052            .as_ref()
1053            .is_some_and(|c| c.kind() == SyntaxKind::QUESTION)
1054            && !key.text().is_empty()
1055        {
1056            let i = key.index();
1057            insert_children(
1058                &entry,
1059                i,
1060                vec![fresh_token(SyntaxKind::WHITESPACE, " ").into()],
1061            );
1062        }
1063        // Without a `:` line, the key's line is the entry's.
1064        let has_colon = has_child_token(&entry, |k| k == SyntaxKind::COLON);
1065        let ends_line = trivia::ends_with_line_break(key);
1066        let newline_after = if has_colon {
1067            key.next_sibling_or_token()
1068        } else {
1069            entry.last_child_or_token()
1070        }
1071        .filter(|c| c.kind() == SyntaxKind::NEWLINE);
1072        if ends_line && !old_ended_line {
1073            if let Some(newline) = newline_after {
1074                newline.detach();
1075            }
1076        } else if old_ended_line && !ends_line {
1077            if has_colon {
1078                insert_children(
1079                    &entry,
1080                    key.index() + 1,
1081                    vec![fresh_token(SyntaxKind::NEWLINE, "\n").into()],
1082                );
1083            } else {
1084                trivia::terminate(&entry);
1085            }
1086        }
1087    }
1088
1089    /// Remove every entry other than `keep` whose key matches `key`.
1090    fn remove_other_entries(&self, keep: &SyntaxNode, key: &impl crate::AsYaml) {
1091        while let Some(other) = self.entries().find(|e| e.0 != *keep && e.key_matches(key)) {
1092            self.remove_entry(other.syntax());
1093        }
1094    }
1095
1096    /// Rebuild an entry's KEY node around `new_key`, keeping the layout
1097    /// tokens the old one carried.
1098    ///
1099    /// In a flow mapping the `?` sits inside KEY, so it carries over, as do
1100    /// any tokens after the key's content. The line break before block
1101    /// content (`?\n- a`) goes, as the new key is written inline, and the
1102    /// one after an empty key (`?\n}`) follows the new key.
1103    ///
1104    /// A comment before the old content stays on its line, or follows the
1105    /// new KEY if the content was on that line too.
1106    ///
1107    /// The old key's anchor stays; failing that the key takes `anchor`, or
1108    /// the anchor before a `new_key` node where it was copied from.
1109    fn rebuild_key(
1110        builder: &mut GreenNodeBuilder,
1111        old: &SyntaxNode,
1112        new_key: &impl crate::AsYaml,
1113        anchor: Option<&str>,
1114        flow: Option<crate::as_yaml::FlowQuoting>,
1115    ) {
1116        builder.start_node(SyntaxKind::KEY.into());
1117        let indent = old
1118            .parent()
1119            .map_or(0, |entry| crate::column::node_column(&entry));
1120        let leading: Vec<_> = old
1121            .children_with_tokens()
1122            .map_while(|c| c.into_token())
1123            .collect();
1124        let mut rest = &leading[..];
1125        if let Some((question, after)) = rest
1126            .split_first()
1127            .filter(|(t, _)| t.kind() == SyntaxKind::QUESTION)
1128        {
1129            builder.token(question.kind().into(), question.text());
1130            let ws = after
1131                .iter()
1132                .take_while(|t| t.kind() == SyntaxKind::WHITESPACE)
1133                .count();
1134            for t in &after[..ws] {
1135                builder.token(t.kind().into(), t.text());
1136            }
1137            if ws == 0 {
1138                builder.token(SyntaxKind::WHITESPACE.into(), " ");
1139            }
1140            rest = &after[ws..];
1141        }
1142        // A comment on the `?` line stays there if the content starts on a
1143        // later line, and otherwise goes after the new key.
1144        let comment = rest.iter().position(|t| t.kind() == SyntaxKind::COMMENT);
1145        let comment_lines = comment
1146            .filter(|&i| rest[i..].iter().any(|t| t.kind() == SyntaxKind::NEWLINE))
1147            .map(|i| &rest[i..]);
1148        let comment_after = comment
1149            .filter(|_| comment_lines.is_none())
1150            .map(|i| rest[i].text().to_string());
1151        let (old_anchor, tag) = key_annotations(old);
1152        let anchor = old_anchor
1153            .or_else(|| anchor.map(str::to_string))
1154            .or_else(|| new_key.value_node().and_then(|n| source_anchor_text(&n)));
1155        if let Some(anchor) = anchor {
1156            builder.token(SyntaxKind::ANCHOR.into(), &anchor);
1157            builder.token(SyntaxKind::WHITESPACE.into(), " ");
1158        }
1159        // On a line of its own, only a block sequence may start at the
1160        // column of the `?`; anything else has to be indented past it.
1161        let mut lines = comment_lines.unwrap_or_default();
1162        let line_indent = match lines.last() {
1163            Some(t) if t.kind() == SyntaxKind::INDENT => {
1164                lines = &lines[..lines.len() - 1];
1165                Some(t.text())
1166            }
1167            _ => None,
1168        };
1169        let block_sequence =
1170            new_key.kind() == crate::as_yaml::YamlKind::Sequence && !new_key.is_inline();
1171        let deeper = " ".repeat(indent + 2);
1172        let line_indent = match line_indent {
1173            Some(text) if block_sequence || text.len() > indent => Some(text),
1174            _ if comment_lines.is_some() && !block_sequence => Some(deeper.as_str()),
1175            other => other,
1176        };
1177        for t in lines {
1178            builder.token(t.kind().into(), t.text());
1179        }
1180        if let Some(text) = line_indent {
1181            builder.token(SyntaxKind::INDENT.into(), text);
1182        }
1183        match tag.and_then(|tag| retagged_key(&tag, new_key, flow)) {
1184            Some(tagged) => super::build_key_content(builder, &tagged, indent, flow),
1185            None => super::build_key_content(builder, new_key, indent, flow),
1186        }
1187        // What follows the old key's last node, such as the line break
1188        // ending an explicit key, stays after the new one.
1189        let last_node = old.last_child().expect("a KEY holds a node");
1190        for trailing in last_node
1191            .siblings_with_tokens(rowan::Direction::Next)
1192            .skip(1)
1193            .filter_map(|c| c.into_token())
1194        {
1195            builder.token(trailing.kind().into(), trailing.text());
1196        }
1197        builder.finish_node();
1198        if let Some(comment) = comment_after {
1199            builder.token(SyntaxKind::WHITESPACE.into(), "  ");
1200            builder.token(SyntaxKind::COMMENT.into(), &comment);
1201        }
1202        // The line break after an empty key now follows the new one.
1203        let old_empty = old.children().next().is_some_and(|n| n.text().is_empty());
1204        if old_empty && comment.is_none() {
1205            for t in rest
1206                .iter()
1207                .filter(|t| matches!(t.kind(), SyntaxKind::NEWLINE | SyntaxKind::INDENT))
1208            {
1209                builder.token(t.kind().into(), t.text());
1210            }
1211        }
1212    }
1213
1214    /// Insert a key-value pair immediately after an existing key.
1215    ///
1216    /// If `key` already exists in the mapping, its value is updated in-place and
1217    /// it remains at its current position (it is **not** moved to after `after_key`).
1218    /// Returns `true` in both the update and the insert cases.
1219    /// Returns `false` only if `after_key` is not found.
1220    ///
1221    /// Use [`move_after`](Self::move_after) if you want
1222    /// an existing entry to be moved to the new position.
1223    ///
1224    /// Mutates in place despite `&self` (see crate docs on interior mutability).
1225    pub fn insert_after(
1226        &self,
1227        after_key: impl crate::AsYaml,
1228        key: impl crate::AsYaml,
1229        value: impl crate::AsYaml,
1230    ) -> bool {
1231        self.insert_around(after_key, key, value, true)
1232    }
1233
1234    /// Insert a key-value pair immediately before an existing key.
1235    ///
1236    /// If `key` already exists in the mapping, its value is updated in-place and
1237    /// it remains at its current position (it is **not** moved to before `before_key`).
1238    /// Returns `true` in both the update and the insert cases.
1239    /// Returns `false` only if `before_key` is not found.
1240    ///
1241    /// Use [`move_before`](Self::move_before) if you want
1242    /// an existing entry to be moved to the new position.
1243    ///
1244    /// Mutates in place despite `&self` (see crate docs on interior mutability).
1245    pub fn insert_before(
1246        &self,
1247        before_key: impl crate::AsYaml,
1248        key: impl crate::AsYaml,
1249        value: impl crate::AsYaml,
1250    ) -> bool {
1251        self.insert_around(before_key, key, value, false)
1252    }
1253
1254    /// Shared body of [`insert_after`](Self::insert_after) and
1255    /// [`insert_before`](Self::insert_before): an existing `key` is updated
1256    /// where it is, a new one goes next to `ref_key`.
1257    fn insert_around(
1258        &self,
1259        ref_key: impl crate::AsYaml,
1260        key: impl crate::AsYaml,
1261        value: impl crate::AsYaml,
1262        after: bool,
1263    ) -> bool {
1264        if self.find_entry_by_key(&key).is_some() {
1265            self.set(&key, &value);
1266            return self.find_entry_by_key(&ref_key).is_some();
1267        }
1268        self.move_around(&ref_key, &key, &value, after)
1269    }
1270
1271    /// Insert a key-value pair at a specific index (0-based).
1272    ///
1273    /// If `key` already exists in the mapping, its value is updated in-place and
1274    /// it remains at its current position (the `index` argument is ignored).
1275    /// If `index` is out of bounds, the entry is appended at the end.
1276    /// This method always succeeds; it never returns an error.
1277    ///
1278    /// Mutates in place despite `&self` (see crate docs on interior mutability).
1279    pub fn insert_at_index(
1280        &self,
1281        index: usize,
1282        key: impl crate::AsYaml,
1283        value: impl crate::AsYaml,
1284    ) {
1285        // Check if the key already exists - if so, just update it
1286        if self.find_entry_by_key(&key).is_some() {
1287            self.set(&key, &value);
1288            return;
1289        }
1290        self.insert_new_entry_at(index, key, value);
1291    }
1292
1293    /// Insert an entry for a key that is not in the mapping yet before the
1294    /// `index`th entry, or at the end if there are fewer.
1295    fn insert_new_entry_at(
1296        &self,
1297        index: usize,
1298        key: impl crate::AsYaml,
1299        value: impl crate::AsYaml,
1300    ) {
1301        let slot = self
1302            .entries()
1303            .nth(index)
1304            .map_or(Slot::End, |e| Slot::Before(e.0));
1305        self.insert_new(slot, key, value);
1306    }
1307
1308    crate::nodes::ast_node_spans!("mapping");
1309}
1310
1311impl Default for Mapping {
1312    fn default() -> Self {
1313        Self::new()
1314    }
1315}
1316
1317// Iterator trait implementations for Mapping
1318
1319impl<'a> IntoIterator for &'a Mapping {
1320    type Item = (crate::as_yaml::YamlNode, crate::as_yaml::YamlNode);
1321    type IntoIter =
1322        Box<dyn Iterator<Item = (crate::as_yaml::YamlNode, crate::as_yaml::YamlNode)> + 'a>;
1323
1324    fn into_iter(self) -> Self::IntoIter {
1325        Box::new(self.iter())
1326    }
1327}
1328
1329impl AsYaml for Mapping {
1330    fn as_node(&self) -> Option<&SyntaxNode> {
1331        Some(&self.0)
1332    }
1333
1334    fn kind(&self) -> YamlKind {
1335        YamlKind::Mapping
1336    }
1337
1338    fn build_content(
1339        &self,
1340        builder: &mut rowan::GreenNodeBuilder,
1341        indent: usize,
1342        _flow_context: bool,
1343    ) -> bool {
1344        let is_flow = self.is_flow_style();
1345        let mut delta =
1346            indent as isize - crate::as_yaml::source_reindent_base(&self.0, is_flow) as isize;
1347        if is_flow {
1348            delta = crate::as_yaml::clear_parent_column(&self.0, indent, delta);
1349        }
1350        builder.start_node(SyntaxKind::MAPPING.into());
1351        crate::as_yaml::copy_node_content_reindent(builder, &self.0, delta);
1352        builder.finish_node();
1353        self.0
1354            .last_token()
1355            .is_some_and(|t| t.kind() == SyntaxKind::NEWLINE)
1356    }
1357
1358    fn is_inline(&self) -> bool {
1359        ValueNode::is_inline(self)
1360    }
1361}