patchloom 0.37.2

Structured file editing library and CLI for AI agents: parser-backed JSON/YAML/TOML edits, AST-aware code operations, multi-file batching, markdown operations, and MCP server
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
//! Aider-style SEARCH/REPLACE and DiffFenced parse.
//!
//! Apply lives in [`crate::api::apply_search_replace_blocks`]. Hosts must not
//! `replacen(..., 1)` or raw `fs::write` for this format. CLI / MCP / tx
//! detect this grammar via [`looks_like_search_replace`] (#2221).

/// Shared refuse when `replace_all` is set on unified or Begin Patch.
pub(crate) const REPLACE_ALL_ONLY_FOR_SEARCH_REPLACE: &str =
    "replace_all is only valid for SEARCH/REPLACE documents";

/// Dest-less SEARCH/REPLACE without a file hint (CLI / MCP / tx / library).
pub(crate) const SEARCH_REPLACE_EMPTY_PATH: &str =
    "SEARCH/REPLACE path must not be empty; put dest on its own line after SEARCH, then -------";

/// True when any line trims to `<<<<<<< SEARCH`.
#[must_use]
pub fn has_search_replace_marker(input: &str) -> bool {
    input.lines().any(|l| l.trim() == "<<<<<<< SEARCH")
}

/// When unified parse finds no files but the document contains SEARCH/REPLACE
/// markers, hint that the document must start with SEARCH or a wrapping fence.
/// First-line detect ([`looks_like_search_replace`]) is unchanged so unified
/// diffs that mention SEARCH later still parse as unified.
pub(crate) fn map_unified_parse_error(input: &str, err: &str) -> String {
    if err == "no files found in patch" && has_search_replace_marker(input) {
        format!(
            "{err}; SEARCH/REPLACE documents must start with `<<<<<<< SEARCH` (or a wrapping fence)"
        )
    } else {
        err.to_string()
    }
}

/// Typed parse_error for apply surfaces that wrap unified-diff parse.
pub(crate) fn unified_parse_anyhow(input: &str, err: &str) -> anyhow::Error {
    anyhow::Error::new(crate::exit::ParseErrorError {
        msg: format!("patch parse error: {}", map_unified_parse_error(input, err)),
    })
}

/// True when the payload is a SEARCH/REPLACE or DiffFenced document.
///
/// First non-empty line must be `<<<<<<< SEARCH` or a fence (` ``` `) so a
/// unified diff that happens to mention that marker as later content is
/// still parsed as a unified diff.
#[must_use]
pub fn looks_like_search_replace(input: &str) -> bool {
    if !has_search_replace_marker(input) {
        return false;
    }
    match first_nonempty_line(input) {
        Some("<<<<<<< SEARCH") => true,
        Some(l) if l.starts_with("```") => true,
        _ => false,
    }
}

fn first_nonempty_line(input: &str) -> Option<&str> {
    input.lines().map(str::trim).find(|l| !l.is_empty())
}

fn first_nonempty_is_fence(input: &str) -> bool {
    first_nonempty_line(input).is_some_and(|l| l.starts_with("```"))
}

/// True when SEARCH/REPLACE markers appear with Begin Patch or unified-diff
/// file headers in a document that is otherwise a SEARCH/REPLACE payload.
#[must_use]
pub fn has_mixed_search_replace_grammar(input: &str) -> bool {
    if !looks_like_search_replace(input) {
        return false;
    }
    crate::ops::begin_patch::looks_like_begin_patch(input)
        || crate::ops::begin_patch::has_col0_begin_patch_start(input)
        || has_unified_diff_headers(input)
}

fn has_unified_diff_headers(input: &str) -> bool {
    input
        .lines()
        .any(crate::ops::patch::line_looks_like_unified_file_header)
}

/// Parse SEARCH/REPLACE, or DiffFenced (fenced unwrap) when the document
/// wraps blocks in triple backticks.
pub fn parse_search_replace_document(
    input: &str,
) -> Result<Vec<SearchReplaceBlock>, SearchReplaceParseError> {
    if has_mixed_search_replace_grammar(input) {
        return Err(SearchReplaceParseError::malformed(
            "mixed SEARCH/REPLACE and unified-diff or Begin Patch grammar is not supported",
        ));
    }
    // DiffFenced unwrap only when the document starts with a fence. Inner
    // ```rust / ``` lines in SEARCH/REPLACE bodies stay in old/new.
    if first_nonempty_is_fence(input) {
        parse_diff_fenced(input)
    } else {
        parse_search_replace(input)
    }
}

/// Dest paths declared in a SEARCH/REPLACE / DiffFenced document.
pub fn search_replace_declared_paths(input: &str) -> Result<Vec<String>, SearchReplaceParseError> {
    let mut paths = Vec::new();
    for block in parse_search_replace_document(input)? {
        if block.path.is_empty() {
            continue;
        }
        if !paths.iter().any(|p| p == &block.path) {
            paths.push(block.path);
        }
    }
    Ok(paths)
}

/// One SEARCH/REPLACE block (path + exact old / new).
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchReplaceBlock {
    pub path: String,
    pub old: String,
    pub new: String,
}

/// Parse error for SEARCH/REPLACE / DiffFenced documents.
#[derive(Debug)]
pub struct SearchReplaceParseError {
    pub message: String,
    /// Complete blocks parsed before a truncated last block.
    pub complete: Vec<SearchReplaceBlock>,
    pub truncated: bool,
}

impl std::fmt::Display for SearchReplaceParseError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str(&self.message)
    }
}

impl std::error::Error for SearchReplaceParseError {}

impl SearchReplaceParseError {
    fn malformed(msg: impl Into<String>) -> Self {
        Self {
            message: msg.into(),
            complete: Vec::new(),
            truncated: false,
        }
    }

    fn truncated(complete: Vec<SearchReplaceBlock>) -> Self {
        let n = complete.len();
        Self {
            message: format!(
                "truncated SEARCH/REPLACE: {n} complete block(s) before incomplete last block"
            ),
            complete,
            truncated: true,
        }
    }
}

/// Parse `<<<<<<< SEARCH` / `=======` / `>>>>>>> REPLACE` blocks.
pub fn parse_search_replace(
    input: &str,
) -> Result<Vec<SearchReplaceBlock>, SearchReplaceParseError> {
    parse_search_replace_inner(input)
}

/// DiffFenced: unwrap fenced code blocks, then parse SEARCH/REPLACE.
pub fn parse_diff_fenced(input: &str) -> Result<Vec<SearchReplaceBlock>, SearchReplaceParseError> {
    let unwrapped = strip_fences_for_search_replace(input);
    parse_search_replace_inner(&unwrapped)
}

fn parse_search_replace_inner(
    response: &str,
) -> Result<Vec<SearchReplaceBlock>, SearchReplaceParseError> {
    let cleaned = strip_eos_tokens(response);
    let mut actions = Vec::new();
    let mut remaining: &str = &cleaned;

    while let Some(start) = remaining.find("<<<<<<< SEARCH") {
        let block = &remaining[start..];

        let (end, end_marker_len) =
            if let Some(pos) = find_whole_line_marker(block, ">>>>>>> REPLACE") {
                (pos, ">>>>>>> REPLACE".len())
            } else if let Some(pos) = find_whole_line_marker(block, ">>>>>>>") {
                let after = &block[pos + ">>>>>>>".len()..];
                let trimmed = after.trim_start();
                if trimmed.is_empty()
                    || trimmed.starts_with('\n')
                    || trimmed.starts_with("<<<<<<< SEARCH")
                {
                    (pos, ">>>>>>>".len())
                } else if actions.is_empty() {
                    return Err(SearchReplaceParseError::malformed(
                        "missing >>>>>>> REPLACE marker",
                    ));
                } else {
                    return Err(SearchReplaceParseError::truncated(actions));
                }
            } else if actions.is_empty() {
                return Err(SearchReplaceParseError::malformed(
                    "missing >>>>>>> REPLACE marker",
                ));
            } else {
                return Err(SearchReplaceParseError::truncated(actions));
            };

        let block = &block[..end + end_marker_len];

        let separator = find_whole_line_marker(block, "=======")
            .ok_or_else(|| SearchReplaceParseError::malformed("missing ======= separator"))?;

        let search_section = skip_one_eol(&block["<<<<<<< SEARCH".len()..separator]);

        // Dest is a whole line that is exactly `-------` (optional trailing
        // space / CR). Inline dashes in dest-less SEARCH stay dest-less.
        let (file, old_content) =
            if let Some(dash_pos) = find_whole_line_marker(search_section, "-------") {
                let f = lf_normalize(search_section[..dash_pos].trim());
                let c = after_whole_line(search_section, dash_pos);
                (f, lf_normalize(c).trim_end_matches('\n').to_string())
            } else {
                // Dest-less: every SEARCH line is old text. apply_patch supplies
                // dest via file_hint. Multi-file documents use the ------- form.
                (
                    String::new(),
                    lf_normalize(search_section)
                        .trim_end_matches('\n')
                        .to_string(),
                )
            };

        // Suffix-strip the close line (not a mid-line substring).
        let before_close = &block[..end];
        let replace_body = after_whole_line(before_close, separator);
        let new_raw = replace_body.strip_suffix('\n').unwrap_or(replace_body);
        let new_content = lf_normalize(new_raw);

        actions.push(SearchReplaceBlock {
            path: file,
            old: old_content,
            new: new_content,
        });

        remaining = &remaining[start + end + end_marker_len..];
    }

    Ok(actions)
}

/// Byte offset of a whole line that is exactly `marker` (optional trailing whitespace).
fn find_whole_line_marker(block: &str, marker: &str) -> Option<usize> {
    let mut offset = 0;
    for line in block.split_inclusive('\n') {
        let without_nl = line.strip_suffix('\n').unwrap_or(line);
        let without_eol = without_nl.strip_suffix('\r').unwrap_or(without_nl);
        if without_eol.trim_end() == marker {
            return Some(offset);
        }
        offset += line.len();
    }
    None
}

fn after_whole_line(block: &str, line_start: usize) -> &str {
    let rest = &block[line_start..];
    match rest.find('\n') {
        Some(n) => &rest[n + 1..],
        None => "",
    }
}

fn skip_one_eol(s: &str) -> &str {
    s.strip_prefix("\r\n")
        .or_else(|| s.strip_prefix('\n'))
        .unwrap_or(s)
}

fn lf_normalize(s: &str) -> String {
    s.replace("\r\n", "\n").replace('\r', "")
}

fn strip_eos_tokens(response: &str) -> String {
    const EOS_PATTERNS: &[&str] = &[
        "<|eos|>",
        "<|eot_id|>",
        "<|end|>",
        "<|im_end|>",
        "<|endoftext|>",
    ];
    let mut cleaned = response.to_string();
    for pat in EOS_PATTERNS {
        cleaned = cleaned.replace(pat, "");
    }
    cleaned
}

fn strip_fences_for_search_replace(input: &str) -> String {
    let mut unwrapped = String::with_capacity(input.len());
    let mut in_fence = false;

    for line in input.lines() {
        let trimmed = line.trim();
        if !in_fence && (trimmed == "```" || trimmed.starts_with("```")) {
            in_fence = true;
            continue;
        }
        if in_fence && trimmed == "```" {
            in_fence = false;
            continue;
        }
        unwrapped.push_str(line);
        unwrapped.push('\n');
    }

    unwrapped
}

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

    #[test]
    fn parse_search_replace_valid() {
        let input = "\
<<<<<<< SEARCH
src/foo.rs
-------
old line
=======
new line
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("parse");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].path, "src/foo.rs");
        assert_eq!(blocks[0].old, "old line");
        assert_eq!(blocks[0].new, "new line");
    }

    #[test]
    fn parse_search_replace_eos_token_stripped() {
        let input = "\
<<<<<<< SEARCH
a.rs
-------
old
=======
new
>>>>>>><|eos|>
";
        let blocks = parse_search_replace(input).expect("eos");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].new, "new");
    }

    #[test]
    fn parse_search_replace_eot_id_stripped() {
        let input = "\
<<<<<<< SEARCH
a.rs
-------
old
=======
new
>>>>>>><|eot_id|>
";
        let blocks = parse_search_replace(input).expect("eot");
        assert_eq!(blocks[0].path, "a.rs");
    }

    #[test]
    fn parse_search_replace_bare_close() {
        let input = "\
<<<<<<< SEARCH
a.rs
-------
old
=======
new
>>>>>>>
";
        let blocks = parse_search_replace(input).expect("bare");
        assert_eq!(blocks[0].old, "old");
        assert_eq!(blocks[0].new, "new");
    }

    #[test]
    fn parse_search_replace_truncated_after_first_block() {
        let input = "\
<<<<<<< SEARCH
a.rs
-------
old
=======
new
>>>>>>> REPLACE
<<<<<<< SEARCH
b.rs
-------
incomplete
";
        let err = parse_search_replace(input).expect_err("truncated");
        assert!(err.truncated);
        assert_eq!(err.complete.len(), 1);
        assert_eq!(err.complete[0].path, "a.rs");
    }

    #[test]
    fn parse_diff_fenced_unwraps_fence() {
        let input = "\
```
<<<<<<< SEARCH
a.rs
-------
old
=======
new
>>>>>>> REPLACE
```
";
        let blocks = parse_diff_fenced(input).expect("fenced");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].path, "a.rs");
    }

    #[test]
    fn parse_search_replace_document_unwraps_leading_fence() {
        let input = "\
```
<<<<<<< SEARCH
a.rs
-------
old
=======
new
>>>>>>> REPLACE
```
";
        let blocks = parse_search_replace_document(input).expect("leading fence");
        assert_eq!(blocks[0].path, "a.rs");
        assert_eq!(blocks[0].old, "old");
        assert_eq!(blocks[0].new, "new");
    }

    #[test]
    fn parse_search_replace_document_keeps_inner_markdown_fences() {
        let input = "\
<<<<<<< SEARCH
README.md
-------
before
```rust
fn x() {}
```
after
=======
before
```rust
fn y() {}
```
after
>>>>>>> REPLACE
";
        assert!(
            looks_like_search_replace(input),
            "first line is SEARCH, not a wrapping fence"
        );
        let blocks = parse_search_replace_document(input).expect("inner fences stay");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].path, "README.md");
        assert_eq!(
            blocks[0].old, "before\n```rust\nfn x() {}\n```\nafter",
            "SEARCH body fences must not be stripped, got {:?}",
            blocks[0].old
        );
        assert_eq!(
            blocks[0].new, "before\n```rust\nfn y() {}\n```\nafter",
            "REPLACE body fences must not be stripped, got {:?}",
            blocks[0].new
        );
    }

    #[test]
    fn parse_search_replace_inline_close_stays_in_new() {
        let input = "\
<<<<<<< SEARCH
close.rs
-------
alpha
=======
see >>>>>>> REPLACE in docs
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("inline close");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].path, "close.rs");
        assert_eq!(blocks[0].old, "alpha");
        assert_eq!(
            blocks[0].new, "see >>>>>>> REPLACE in docs",
            "inline close text must stay in new, got {:?}",
            blocks[0].new
        );
    }

    #[test]
    fn looks_like_search_replace_first_line_or_fence() {
        assert!(looks_like_search_replace(
            "<<<<<<< SEARCH\nfile.rs\n-------\nold\n=======\nnew\n>>>>>>> REPLACE\n"
        ));
        assert!(looks_like_search_replace(
            "```\n<<<<<<< SEARCH\nfile.rs\n-------\nold\n=======\nnew\n>>>>>>> REPLACE\n```\n"
        ));
        assert!(!looks_like_search_replace(
            "--- a/file.rs\n+++ b/file.rs\n@@ -1 +1 @@\n-old\n+new\n"
        ));
        assert!(
            !looks_like_search_replace(
                "--- a/file.rs\n+++ b/file.rs\n@@ -1,3 +1,3 @@\n context\n <<<<<<< SEARCH\n+keep\n"
            ),
            "unified diff that mentions SEARCH later is not SEARCH/REPLACE"
        );
        let prose_first = "here is a patch\n<<<<<<< SEARCH\ncode.rs\n-------\nfn old() {}\n=======\nfn new() {}\n>>>>>>> REPLACE\n";
        assert!(
            !looks_like_search_replace(prose_first),
            "prose before SEARCH must stay unified (first-line detect unchanged)"
        );
        assert!(has_search_replace_marker(prose_first));
        assert!(has_search_replace_marker("--- a/x\n<<<<<<< SEARCH\nkeep\n"));
        assert!(!has_search_replace_marker("--- a/x\n+++ b/x\n"));
        let mapped = map_unified_parse_error(prose_first, "no files found in patch");
        assert!(
            mapped.contains("no files found in patch")
                && mapped.contains("<<<<<<< SEARCH")
                && mapped.contains("wrapping fence"),
            "apply surfaces must hint SEARCH/REPLACE start, got {mapped}"
        );
        assert_eq!(
            map_unified_parse_error("just some text\n", "no files found in patch"),
            "no files found in patch"
        );
        assert_eq!(
            map_unified_parse_error(prose_first, "no hunks found for file x.rs"),
            "no hunks found for file x.rs"
        );
    }

    #[test]
    fn mixed_search_replace_and_unified_headers_refused() {
        let input = "\
<<<<<<< SEARCH
file.rs
-------
old
=======
new
>>>>>>> REPLACE
--- a/file.rs
+++ b/file.rs
";
        assert!(has_mixed_search_replace_grammar(input));
        let err = parse_search_replace_document(input).expect_err("mixed");
        assert!(!err.truncated, "mixed grammar is malformed, not truncated");
        assert!(
            err.message.contains("mixed SEARCH/REPLACE"),
            "expected mixed-grammar refuse, got {}",
            err.message
        );
    }

    #[test]
    fn mixed_search_replace_and_backslash_unified_headers_refused() {
        let input = "\
<<<<<<< SEARCH
file.rs
-------
old
=======
new
>>>>>>> REPLACE
--- a\\file.rs
+++ b\\file.rs
";
        assert!(has_mixed_search_replace_grammar(input));
        let err = parse_search_replace_document(input).expect_err("mixed backslash");
        assert!(!err.truncated, "mixed grammar is malformed, not truncated");
        assert!(
            err.message.contains("mixed SEARCH/REPLACE"),
            "expected mixed-grammar refuse, got {}",
            err.message
        );
    }

    #[test]
    fn has_mixed_search_replace_then_begin_patch_refused() {
        let input = "\
<<<<<<< SEARCH
code.rs
-------
fn old() {}
=======
fn new() {}
>>>>>>> REPLACE
*** Begin Patch
*** Update File: code.rs
@@
-fn new() {}
+fn other() {}
*** End Patch
";
        assert!(looks_like_search_replace(input));
        assert!(
            !crate::ops::begin_patch::looks_like_begin_patch(input),
            "first non-blank is SEARCH, not Begin Patch"
        );
        assert!(has_mixed_search_replace_grammar(input));
        let err = parse_search_replace_document(input).expect_err("mixed SEARCH then Begin Patch");
        assert!(!err.truncated, "mixed grammar is malformed, not truncated");
        assert!(
            err.message.contains("mixed SEARCH/REPLACE"),
            "expected mixed-grammar refuse, got {}",
            err.message
        );
    }

    #[test]
    fn has_mixed_search_replace_then_update_file_refused() {
        let input = "\
<<<<<<< SEARCH
code.rs
-------
fn old() {}
=======
fn new() {}
>>>>>>> REPLACE
*** Update File: code.rs
";
        assert!(looks_like_search_replace(input));
        assert!(has_mixed_search_replace_grammar(input));
        let err = parse_search_replace_document(input).expect_err("mixed SEARCH then Update File");
        assert!(
            err.message.contains("mixed SEARCH/REPLACE"),
            "expected mixed-grammar refuse, got {}",
            err.message
        );
    }

    #[test]
    fn has_mixed_search_replace_begin_patch_first_stays_begin_patch() {
        let input = "\
*** Begin Patch
<<<<<<< SEARCH
code.rs
-------
fn old() {}
=======
fn new() {}
>>>>>>> REPLACE
*** End Patch
";
        assert!(
            !looks_like_search_replace(input),
            "Begin-Patch-first is not a SEARCH/REPLACE payload"
        );
        assert!(!has_mixed_search_replace_grammar(input));
        assert!(crate::ops::begin_patch::looks_like_begin_patch(input));
        assert!(has_search_replace_marker(input));
    }

    #[test]
    fn parse_search_replace_destless_keeps_first_line_as_search() {
        let input = "\
<<<<<<< SEARCH
only.rs
the old text
=======
the new text
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("dest-less");
        assert_eq!(
            blocks[0].path, "",
            "no ------- dest: first SEARCH line is body, not dest"
        );
        assert_eq!(blocks[0].old, "only.rs\nthe old text");
        assert_eq!(blocks[0].new, "the new text");
    }

    #[test]
    fn parse_search_replace_destless_code_line_is_not_dest() {
        let input = "\
<<<<<<< SEARCH
            pub fn set(&mut self, deg: u32) -> Result<u64, Error> {
        if deg == 0 {
=======
    pub fn set(&mut self, deg: u32) -> Result<u64, Error> {
        if deg == 0 {
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("dest-less code");
        assert!(
            blocks[0].path.is_empty(),
            "code line must not become dest, got {:?}",
            blocks[0].path
        );
        assert!(
            blocks[0]
                .old
                .contains("pub fn set(&mut self, deg: u32) -> Result<u64, Error> {"),
            "first SEARCH line stays in old, got {:?}",
            blocks[0].old
        );
    }

    #[test]
    fn search_replace_declared_paths_skips_destless_blocks() {
        let destless = "\
<<<<<<< SEARCH
only.rs
the old text
=======
the new text
>>>>>>> REPLACE
";
        assert_eq!(
            search_replace_declared_paths(destless).expect("dest-less"),
            Vec::<String>::new(),
            "dest-less must not declare the first SEARCH line as dest"
        );

        let mixed = "\
<<<<<<< SEARCH
keep.rs
-------
old
=======
new
>>>>>>> REPLACE
<<<<<<< SEARCH
skip.rs
body
=======
other
>>>>>>> REPLACE
";
        assert_eq!(
            search_replace_declared_paths(mixed).expect("mixed"),
            vec!["keep.rs".to_string()],
            "only ------- dests are declared"
        );
    }

    #[test]
    fn parse_search_replace_banner_equals_is_not_separator() {
        let input = "\
<<<<<<< SEARCH
f.py
-------
# ==========
title
=======
# ==========
renamed
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("banner equals");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].path, "f.py");
        assert_eq!(blocks[0].old, "# ==========\ntitle");
        assert_eq!(blocks[0].new, "# ==========\nrenamed");
    }

    #[test]
    fn parse_search_replace_setext_underline_is_not_separator() {
        let input = "\
<<<<<<< SEARCH
doc.md
-------
Heading
==========
=======
Heading
==========
updated
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("setext underline");
        assert_eq!(blocks.len(), 1);
        assert_eq!(blocks[0].path, "doc.md");
        assert_eq!(blocks[0].old, "Heading\n==========");
        assert_eq!(blocks[0].new, "Heading\n==========\nupdated");
    }

    #[test]
    fn parse_search_replace_separator_allows_trailing_whitespace() {
        let input = "\
<<<<<<< SEARCH
a.rs
-------
old
=======  
new
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("trailing ws on separator");
        assert_eq!(blocks[0].old, "old");
        assert_eq!(blocks[0].new, "new");
    }

    #[test]
    fn parse_search_replace_crlf_dest_present_matches_lf() {
        let lf = "\
<<<<<<< SEARCH
code.rs
-------
fn old() {}
=======
fn new() {}
>>>>>>> REPLACE
";
        let crlf = lf.replace('\n', "\r\n");
        let lf_blocks = parse_search_replace(lf).expect("lf");
        let crlf_blocks = parse_search_replace(&crlf).expect("crlf");
        assert_eq!(crlf_blocks, lf_blocks);
        assert_eq!(crlf_blocks[0].path, "code.rs");
        assert_eq!(crlf_blocks[0].old, "fn old() {}");
        assert_eq!(crlf_blocks[0].new, "fn new() {}");
        assert!(
            !crlf_blocks[0].old.contains('\r'),
            "old must not keep CR: {:?}",
            crlf_blocks[0].old
        );
        assert!(
            !crlf_blocks[0].new.contains('\r'),
            "new must not keep CR: {:?}",
            crlf_blocks[0].new
        );
    }

    #[test]
    fn parse_search_replace_crlf_destless_has_empty_path_without_cr() {
        let lf = "\
<<<<<<< SEARCH
only.rs
the old text
=======
the new text
>>>>>>> REPLACE
";
        let crlf = lf.replace('\n', "\r\n");
        let blocks = parse_search_replace(&crlf).expect("dest-less crlf");
        assert_eq!(blocks[0].path, "");
        assert_eq!(blocks[0].old, "only.rs\nthe old text");
        assert_eq!(blocks[0].new, "the new text");
        assert!(
            !blocks[0].old.contains('\r'),
            "old must not keep CR: {:?}",
            blocks[0].old
        );
        assert!(
            !blocks[0].new.contains('\r'),
            "new must not keep CR: {:?}",
            blocks[0].new
        );
    }

    #[test]
    fn parse_search_replace_inline_dashes_in_destless_search_are_not_dest() {
        let input = "\
<<<<<<< SEARCH
x = \"-------\"
=======
x = \"eq\"
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("inline dashes");
        assert_eq!(
            blocks[0].path, "",
            "inline ------- in SEARCH is not dest, got {:?}",
            blocks[0].path
        );
        assert_eq!(blocks[0].old, "x = \"-------\"");
        assert_eq!(blocks[0].new, "x = \"eq\"");
    }

    #[test]
    fn parse_search_replace_dest_present_old_may_contain_dashes() {
        let input = "\
<<<<<<< SEARCH
code.rs
-------
x = \"-------\"
=======
x = \"eq\"
>>>>>>> REPLACE
";
        let blocks = parse_search_replace(input).expect("dest-present dashes in old");
        assert_eq!(blocks[0].path, "code.rs");
        assert_eq!(blocks[0].old, "x = \"-------\"");
        assert_eq!(blocks[0].new, "x = \"eq\"");
    }
}