summaryrefslogtreecommitdiff
path: root/src/format.rs
blob: 4495638e9ead6fdb5551380bfb3682e30d0eedd8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
//! Format note content the way Apple Notes expects to look.
//!
//! Follows Apple Support guidance for Notes paragraph styles and lists:
//! <https://support.apple.com/guide/iphone/create-and-format-notes-iph1ac0b3a2/ios>
//! <https://support.apple.com/guide/notes/format-notes-apd1955d3b21/mac>
//! <https://support.apple.com/guide/notes/add-lists-apd93c815aa0/mac>
//!
//! Structure: Title (first line) → Heading / Subheading sections → Body →
//! lists (bulleted / dashed / numbered / checklist) → optional dividers,
//! block quotes, monostyled blocks, and simple tables.
//!
//! Converts common agent/Markdown noise into clean Notes-friendly plain text.
//! Paragraph style hints are also emitted for the browser layer when available.

#![allow(dead_code)]

#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ParagraphStyle {
    Title,
    Heading,
    Subheading,
    Body,
    Bullet,
    Dashed,
    Numbered,
    Checklist,
    Monospace,
    /// Apple Notes “Insert Divider Line” (plain-text stand-in).
    Divider,
    /// Apple Notes Block Quote style.
    BlockQuote,
}

#[derive(Debug, Clone, PartialEq, Eq)]
pub struct Paragraph {
    pub style: ParagraphStyle,
    pub text: String,
    /// Checklist done state (only for Checklist).
    pub checked: bool,
}

/// Public entry: Apple-style note text (first line = title).
pub fn format_apple_note(title: &str, body: &str) -> String {
    paragraphs_to_plain(&build_paragraphs(title, body))
}

/// Structured paragraphs for richer Notes styling when the web API supports it.
pub fn build_paragraphs(title: &str, body: &str) -> Vec<Paragraph> {
    let title = clean_title(title);
    let body = body.replace("\r\n", "\n").replace('\r', "\n");
    let body = strip_outer_fence(&body);

    let mut out = Vec::new();
    if !title.is_empty() {
        out.push(Paragraph {
            style: ParagraphStyle::Title,
            text: title.clone(),
            checked: false,
        });
    }

    let mut in_code = false;
    let mut code_buf: Vec<String> = Vec::new();
    let mut para_buf: Vec<String> = Vec::new();
    let mut table_buf: Vec<String> = Vec::new();

    let flush_para = |buf: &mut Vec<String>, out: &mut Vec<Paragraph>| {
        if buf.is_empty() {
            return;
        }
        let text = buf.join(" ").trim().to_string();
        buf.clear();
        if text.is_empty() {
            return;
        }
        // Skip body line that merely repeats the title
        if out
            .first()
            .map(|p| p.style == ParagraphStyle::Title && titles_equal(&p.text, &text))
            .unwrap_or(false)
            && out.len() == 1
        {
            return;
        }
        out.push(Paragraph {
            style: ParagraphStyle::Body,
            text,
            checked: false,
        });
    };

    let flush_table = |buf: &mut Vec<String>, out: &mut Vec<Paragraph>| {
        if buf.is_empty() {
            return;
        }
        let rows = std::mem::take(buf);
        if let Some(text) = format_md_table(&rows) {
            out.push(Paragraph {
                style: ParagraphStyle::Monospace,
                text,
                checked: false,
            });
        } else {
            for row in rows {
                out.push(Paragraph {
                    style: ParagraphStyle::Body,
                    text: clean_inline(row.trim_matches('|').trim()),
                    checked: false,
                });
            }
        }
    };

    let body_lines: Vec<&str> = body.lines().collect();
    let mut i = 0;
    while i < body_lines.len() {
        let line = body_lines[i].trim_end();
        let trimmed = line.trim();

        if trimmed.starts_with("```") {
            flush_table(&mut table_buf, &mut out);
            if in_code {
                let code = code_buf.join("\n").trim_end().to_string();
                code_buf.clear();
                in_code = false;
                if !code.is_empty() {
                    flush_para(&mut para_buf, &mut out);
                    out.push(Paragraph {
                        style: ParagraphStyle::Monospace,
                        text: code,
                        checked: false,
                    });
                }
            } else {
                flush_para(&mut para_buf, &mut out);
                in_code = true;
            }
            i += 1;
            continue;
        }
        if in_code {
            code_buf.push(line.to_string());
            i += 1;
            continue;
        }

        // GFM pipe tables
        if trimmed.starts_with('|') && trimmed.contains('|') {
            flush_para(&mut para_buf, &mut out);
            table_buf.push(trimmed.to_string());
            i += 1;
            continue;
        }
        if !table_buf.is_empty() {
            flush_table(&mut table_buf, &mut out);
        }

        if trimmed.is_empty() {
            flush_para(&mut para_buf, &mut out);
            i += 1;
            continue;
        }

        // Apple Notes divider line (Markdown HR → Insert Divider Line stand-in)
        if is_divider_marker(trimmed) {
            flush_para(&mut para_buf, &mut out);
            out.push(Paragraph {
                style: ParagraphStyle::Divider,
                text: String::new(),
                checked: false,
            });
            i += 1;
            continue;
        }

        if let Some(p) = parse_special_line(trimmed) {
            flush_para(&mut para_buf, &mut out);
            if p.style != ParagraphStyle::Divider && p.text.is_empty() {
                i += 1;
                continue;
            }
            // Don't re-add title-looking heading if it matches note title
            if matches!(
                p.style,
                ParagraphStyle::Heading | ParagraphStyle::Subheading
            ) && out
                .first()
                .map(|t| t.style == ParagraphStyle::Title && titles_equal(&t.text, &p.text))
                .unwrap_or(false)
            {
                i += 1;
                continue;
            }
            out.push(p);
            i += 1;
            continue;
        }

        para_buf.push(clean_inline(trimmed));
        i += 1;
    }

    if !table_buf.is_empty() {
        flush_table(&mut table_buf, &mut out);
    }
    if in_code {
        let code = code_buf.join("\n").trim_end().to_string();
        if !code.is_empty() {
            flush_para(&mut para_buf, &mut out);
            out.push(Paragraph {
                style: ParagraphStyle::Monospace,
                text: code,
                checked: false,
            });
        }
    }
    flush_para(&mut para_buf, &mut out);

    // Apple: first line of the note becomes the title
    if out.is_empty() {
        out.push(Paragraph {
            style: ParagraphStyle::Title,
            text: "Note".into(),
            checked: false,
        });
    } else if out[0].style != ParagraphStyle::Title {
        let fallback = out[0].text.chars().take(80).collect::<String>();
        out.insert(
            0,
            Paragraph {
                style: ParagraphStyle::Title,
                text: if fallback.is_empty() {
                    "Note".into()
                } else {
                    fallback
                },
                checked: false,
            },
        );
    }

    out
}

pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
    let mut lines: Vec<String> = Vec::new();
    let mut prev: Option<ParagraphStyle> = None;

    for (i, p) in paragraphs.iter().enumerate() {
        let rendered = match p.style {
            ParagraphStyle::Title => p.text.clone(),
            ParagraphStyle::Heading | ParagraphStyle::Subheading => p.text.clone(),
            ParagraphStyle::Body => p.text.clone(),
            // Apple list glyphs (support.apple.com/guide/notes/add-lists)
            ParagraphStyle::Bullet => format!("• {}", p.text),
            ParagraphStyle::Dashed => format!("– {}", p.text),
            ParagraphStyle::Numbered => {
                let n = paragraphs[..=i]
                    .iter()
                    .rev()
                    .take_while(|x| x.style == ParagraphStyle::Numbered)
                    .count();
                format!("{n}. {}", p.text)
            }
            ParagraphStyle::Checklist => {
                if p.checked {
                    format!("☑ {}", p.text)
                } else {
                    format!("☐ {}", p.text)
                }
            }
            ParagraphStyle::Monospace => p.text.clone(),
            ParagraphStyle::Divider => "────────────────".into(),
            ParagraphStyle::BlockQuote => format!("│ {}", p.text),
        };

        let listish = matches!(
            p.style,
            ParagraphStyle::Bullet
                | ParagraphStyle::Dashed
                | ParagraphStyle::Numbered
                | ParagraphStyle::Checklist
        );
        let need_blank = match (prev, p.style) {
            (None, _) => false,
            (Some(ParagraphStyle::Title), _) => true,
            (
                Some(ParagraphStyle::Heading | ParagraphStyle::Subheading),
                ParagraphStyle::Body
                | ParagraphStyle::Bullet
                | ParagraphStyle::Dashed
                | ParagraphStyle::Numbered
                | ParagraphStyle::Checklist
                | ParagraphStyle::Monospace
                | ParagraphStyle::BlockQuote
                | ParagraphStyle::Divider,
            ) => true,
            (Some(ParagraphStyle::Body), ParagraphStyle::Body) => true,
            (Some(ParagraphStyle::Body), ParagraphStyle::Heading) => true,
            (Some(ParagraphStyle::Body), ParagraphStyle::Subheading) => true,
            (Some(ParagraphStyle::Monospace), _) => true,
            (Some(ParagraphStyle::Divider), _) => true,
            (Some(_), ParagraphStyle::Divider) => true,
            (Some(ParagraphStyle::BlockQuote), ParagraphStyle::BlockQuote) => false,
            (Some(_), ParagraphStyle::BlockQuote) => true,
            (Some(ParagraphStyle::BlockQuote), _) if !listish => true,
            (Some(_), ParagraphStyle::Heading | ParagraphStyle::Subheading) => true,
            (
                Some(
                    ParagraphStyle::Bullet
                    | ParagraphStyle::Dashed
                    | ParagraphStyle::Numbered
                    | ParagraphStyle::Checklist,
                ),
                ParagraphStyle::Body,
            ) => true,
            (
                Some(ParagraphStyle::Body),
                ParagraphStyle::Bullet
                | ParagraphStyle::Dashed
                | ParagraphStyle::Numbered
                | ParagraphStyle::Checklist,
            ) => true,
            // Blank when switching list kinds (e.g. dashed → checklist)
            (
                Some(
                    ParagraphStyle::Bullet
                    | ParagraphStyle::Dashed
                    | ParagraphStyle::Numbered
                    | ParagraphStyle::Checklist,
                ),
                _,
            ) if listish
                && prev.is_some_and(|pr| {
                    !matches!(
                        (pr, p.style),
                        (ParagraphStyle::Bullet, ParagraphStyle::Bullet)
                            | (ParagraphStyle::Dashed, ParagraphStyle::Dashed)
                            | (ParagraphStyle::Numbered, ParagraphStyle::Numbered)
                            | (ParagraphStyle::Checklist, ParagraphStyle::Checklist)
                    )
                }) =>
            {
                true
            }
            _ => false,
        };
        if need_blank && lines.last().map(|s| !s.is_empty()).unwrap_or(false) {
            lines.push(String::new());
        }

        if p.style == ParagraphStyle::Monospace {
            for code_line in rendered.lines() {
                lines.push(code_line.to_string());
            }
            lines.push(String::new());
        } else {
            lines.push(rendered);
        }
        prev = Some(p.style);
    }

    while lines.last().map(|s| s.is_empty()).unwrap_or(false) {
        lines.pop();
    }
    lines.join("\n")
}

fn is_divider_marker(trimmed: &str) -> bool {
    let t = trimmed.trim();
    if t.len() < 3 {
        return false;
    }
    t.chars().all(|c| c == '-' || c == '*' || c == '_' || c == '─')
}

fn parse_special_line(trimmed: &str) -> Option<Paragraph> {
    // ATX headings → Apple Heading / Subheading (Title is the note’s first line)
    if let Some(rest) = trimmed.strip_prefix("### ") {
        return Some(Paragraph {
            style: ParagraphStyle::Subheading,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("## ") {
        return Some(Paragraph {
            style: ParagraphStyle::Heading,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("# ") {
        return Some(Paragraph {
            style: ParagraphStyle::Heading,
            text: clean_inline(rest),
            checked: false,
        });
    }

    // Block quote
    if let Some(rest) = trimmed.strip_prefix("> ") {
        return Some(Paragraph {
            style: ParagraphStyle::BlockQuote,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if trimmed == ">" {
        return Some(Paragraph {
            style: ParagraphStyle::BlockQuote,
            text: String::new(),
            checked: false,
        });
    }

    // Checklist (before plain list markers)
    for (prefix, checked) in [
        ("* [x] ", true),
        ("* [X] ", true),
        ("* [ ] ", false),
        ("- [x] ", true),
        ("- [X] ", true),
        ("- [ ] ", false),
        ("+ [x] ", true),
        ("+ [ ] ", false),
    ] {
        if let Some(rest) = trimmed.strip_prefix(prefix) {
            return Some(Paragraph {
                style: ParagraphStyle::Checklist,
                text: clean_inline(rest),
                checked,
            });
        }
    }

    // Apple typing shortcuts (Add lists in Notes):
    //   * + space → Bulleted List
    //   - + space → Dashed List
    //   1. + space → Numbered List
    if let Some(rest) = trimmed.strip_prefix("* ") {
        return Some(Paragraph {
            style: ParagraphStyle::Bullet,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("• ") {
        return Some(Paragraph {
            style: ParagraphStyle::Bullet,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("- ") {
        return Some(Paragraph {
            style: ParagraphStyle::Dashed,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("+ ") {
        // Markdown “+” lists → bulleted (closest Apple style)
        return Some(Paragraph {
            style: ParagraphStyle::Bullet,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("– ") {
        return Some(Paragraph {
            style: ParagraphStyle::Dashed,
            text: clean_inline(rest),
            checked: false,
        });
    }
    if let Some(rest) = trimmed.strip_prefix("— ") {
        return Some(Paragraph {
            style: ParagraphStyle::Dashed,
            text: clean_inline(rest),
            checked: false,
        });
    }

    // Numbered: "1. item" or "1) item"
    if let Some(dot) = trimmed.find(". ") {
        let (num, rest) = trimmed.split_at(dot);
        if !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()) {
            return Some(Paragraph {
                style: ParagraphStyle::Numbered,
                text: clean_inline(&rest[2..]),
                checked: false,
            });
        }
    }
    if let Some(paren) = trimmed.find(") ") {
        let (num, rest) = trimmed.split_at(paren);
        if !num.is_empty() && num.chars().all(|c| c.is_ascii_digit()) {
            return Some(Paragraph {
                style: ParagraphStyle::Numbered,
                text: clean_inline(&rest[2..]),
                checked: false,
            });
        }
    }

    None
}

fn format_md_table(rows: &[String]) -> Option<String> {
    if rows.len() < 2 {
        return None;
    }
    let mut cells: Vec<Vec<String>> = Vec::new();
    for (idx, row) in rows.iter().enumerate() {
        let parts: Vec<String> = row
            .trim()
            .trim_matches('|')
            .split('|')
            .map(|c| clean_inline(c.trim()))
            .collect();
        if idx == 1 && parts.iter().all(|c| is_table_separator(c)) {
            continue; // alignment row
        }
        if parts.is_empty() {
            continue;
        }
        cells.push(parts);
    }
    if cells.is_empty() {
        return None;
    }
    let cols = cells.iter().map(|r| r.len()).max().unwrap_or(0);
    if cols == 0 {
        return None;
    }
    let mut widths = vec![0usize; cols];
    for row in &cells {
        for (i, cell) in row.iter().enumerate() {
            widths[i] = widths[i].max(cell.chars().count());
        }
    }
    let mut out_lines = Vec::new();
    for (ri, row) in cells.iter().enumerate() {
        let mut line = String::new();
        for (i, w) in widths.iter().enumerate() {
            if i > 0 {
                line.push_str("  ");
            }
            let cell = row.get(i).map(|s| s.as_str()).unwrap_or("");
            line.push_str(cell);
            let pad = w.saturating_sub(cell.chars().count());
            line.push_str(&" ".repeat(pad));
        }
        out_lines.push(line.trim_end().to_string());
        if ri == 0 {
            // subtle header underline (not a full Apple table, but readable)
            let mut rule = String::new();
            for (i, w) in widths.iter().enumerate() {
                if i > 0 {
                    rule.push_str("  ");
                }
                rule.push_str(&"─".repeat((*w).max(1)));
            }
            out_lines.push(rule);
        }
    }
    Some(out_lines.join("\n"))
}

fn is_table_separator(cell: &str) -> bool {
    let t = cell.trim();
    if t.is_empty() {
        return false;
    }
    t.chars().all(|c| c == '-' || c == ':' || c == ' ')
}

fn clean_title(title: &str) -> String {
    let t = title.replace('\n', " ").replace('\r', " ");
    let t = clean_inline(t.trim());
    // Strip leading markdown heading markers from title
    let t = t.trim_start_matches('#').trim().to_string();
    // Prefer a concise title (Notes list truncates anyway)
    if t.chars().count() > 80 {
        let mut s: String = t.chars().take(77).collect();
        s.push('…');
        s
    } else {
        t
    }
}

fn clean_inline(s: &str) -> String {
    let mut out = s.to_string();
    // **bold** / __bold__ / *italic* / _italic_ / ~~strike~~ / `code`
    // (Apple supports bold/italic/highlight in-app; plain TopoText cannot)
    out = strip_wrapping_markers(&out, "**");
    out = strip_wrapping_markers(&out, "__");
    out = strip_wrapping_markers(&out, "~~");
    out = strip_wrapping_markers(&out, "`");
    out = strip_wrapping_markers(&out, "*");
    out = strip_wrapping_markers(&out, "_");
    // ==highlight== → plain (Notes highlight is color-only)
    out = strip_wrapping_markers(&out, "==");
    out = rewrite_md_links(&out);
    let parts: Vec<_> = out.split_whitespace().collect();
    parts.join(" ")
}

fn strip_wrapping_markers(s: &str, marker: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    let mlen = marker.len();
    while let Some(start) = rest.find(marker) {
        out.push_str(&rest[..start]);
        let after = &rest[start + mlen..];
        if let Some(end) = after.find(marker) {
            out.push_str(&after[..end]);
            rest = &after[end + mlen..];
        } else {
            out.push_str(marker);
            rest = after;
        }
    }
    out.push_str(rest);
    out
}

fn rewrite_md_links(s: &str) -> String {
    let mut out = String::with_capacity(s.len());
    let mut rest = s;
    while let Some(start) = rest.find('[') {
        out.push_str(&rest[..start]);
        let after = &rest[start + 1..];
        if let Some(mid) = after.find("](") {
            let label = &after[..mid];
            let after_url = &after[mid + 2..];
            if let Some(end) = after_url.find(')') {
                let url = &after_url[..end];
                if label == url || label.is_empty() {
                    out.push_str(url);
                } else {
                    out.push_str(label);
                    out.push(' ');
                    out.push('(');
                    out.push_str(url);
                    out.push(')');
                }
                rest = &after_url[end + 1..];
                continue;
            }
        }
        out.push('[');
        rest = after;
    }
    out.push_str(rest);
    out
}

fn strip_outer_fence(body: &str) -> String {
    let t = body.trim();
    if t.starts_with("```") && t.ends_with("```") {
        let mut lines: Vec<&str> = t.lines().collect();
        if lines.len() >= 2 {
            lines.remove(0);
            if lines.last().map(|l| l.trim() == "```").unwrap_or(false) {
                lines.pop();
            }
            return lines.join("\n");
        }
    }
    body.to_string()
}

fn titles_equal(a: &str, b: &str) -> bool {
    a.trim().eq_ignore_ascii_case(b.trim())
}

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

    #[test]
    fn title_and_body_spacing() {
        let s = format_apple_note("Grocery list", "Milk and eggs for the week.");
        assert_eq!(s, "Grocery list\n\nMilk and eggs for the week.");
    }

    #[test]
    fn apple_heading_and_dashed_list() {
        // Apple: hyphen + space → dashed list
        let body = "## Details\n\n- First item\n- Second item\n\nMore text here.";
        let s = format_apple_note("Project", body);
        assert!(s.starts_with("Project\n\n"));
        assert!(s.contains("Details\n\n"));
        assert!(s.contains("– First item\n– Second item"));
        assert!(s.contains("\n\nMore text here."));
        assert!(!s.contains("## "));
        assert!(!s.contains("- First"));
    }

    #[test]
    fn apple_asterisk_bulleted_list() {
        let s = format_apple_note("Shop", "* Milk\n* Eggs");
        assert!(s.contains("• Milk\n• Eggs"));
    }

    #[test]
    fn strips_bold_and_links() {
        let s = format_apple_note(
            "Hello",
            "This is **bold** and a [link](https://example.com).",
        );
        assert!(s.contains("This is bold and a link (https://example.com)."));
        assert!(!s.contains("**"));
    }

    #[test]
    fn checklist_and_numbered() {
        let body = "- [ ] Todo one\n- [x] Done two\n1. Alpha\n2. Beta";
        let s = format_apple_note("Tasks", body);
        assert!(s.contains("☐ Todo one"));
        assert!(s.contains("☑ Done two"));
        assert!(s.contains("1. Alpha"));
        assert!(s.contains("2. Beta"));
    }

    #[test]
    fn divider_and_block_quote() {
        let body = "Before\n\n---\n\n> A short quote\n\nAfter";
        let s = format_apple_note("Quote", body);
        assert!(s.contains("────────────────"));
        assert!(s.contains("│ A short quote"));
        assert!(s.contains("Before"));
        assert!(s.contains("After"));
        assert!(!s.contains("---"));
        assert!(!s.contains("> "));
    }

    #[test]
    fn markdown_table_aligned() {
        let body = "| Item | Qty |\n| --- | --- |\n| Apples | 3 |\n| Milk | 1 |";
        let s = format_apple_note("List", body);
        assert!(s.contains("Item"));
        assert!(s.contains("Apples"));
        assert!(s.contains("Milk"));
        assert!(!s.contains("| ---"));
    }

    #[test]
    fn does_not_duplicate_title_in_body() {
        let s = format_apple_note("Same", "Same\n\nActual body.");
        assert_eq!(s.matches("Same").count(), 1);
        assert!(s.contains("Actual body."));
    }

    #[test]
    fn code_block_preserved() {
        let body = "Intro\n\n```\nlet x = 1;\n```\n\nOutro";
        let s = format_apple_note("Code", body);
        assert!(s.contains("let x = 1;"));
        assert!(s.contains("Intro"));
        assert!(s.contains("Outro"));
        assert!(!s.contains("```"));
    }

    #[test]
    fn structured_styles() {
        let ps = build_paragraphs("T", "## H\n\nbody para\n\n* a\n- b\n> q\n\n---");
        assert_eq!(ps[0].style, ParagraphStyle::Title);
        assert_eq!(ps[1].style, ParagraphStyle::Heading);
        assert_eq!(ps[2].style, ParagraphStyle::Body);
        assert_eq!(ps[3].style, ParagraphStyle::Bullet);
        assert_eq!(ps[4].style, ParagraphStyle::Dashed);
        assert_eq!(ps[5].style, ParagraphStyle::BlockQuote);
        assert_eq!(ps[6].style, ParagraphStyle::Divider);
    }
}