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
|
//! Format note content the way Apple Notes expects to look:
//! Title (first line) → optional Heading/Subheading → Body paragraphs → lists.
//!
//! 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,
}
#[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 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,
});
};
for raw in body.lines() {
let line = raw.trim_end();
let trimmed = line.trim();
if trimmed.starts_with("```") {
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;
}
continue;
}
if in_code {
code_buf.push(line.to_string());
continue;
}
if trimmed.is_empty() {
flush_para(&mut para_buf, &mut out);
continue;
}
// Horizontal rules — visual noise in Notes; skip
if trimmed.chars().all(|c| c == '-' || c == '*' || c == '_') && trimmed.len() >= 3 {
flush_para(&mut para_buf, &mut out);
continue;
}
if let Some(p) = parse_special_line(trimmed) {
flush_para(&mut para_buf, &mut out);
if p.text.is_empty() {
continue;
}
// Don't re-add title-looking heading if it matches note title
if p.style == ParagraphStyle::Heading
&& out
.first()
.map(|t| t.style == ParagraphStyle::Title && titles_equal(&t.text, &p.text))
.unwrap_or(false)
{
continue;
}
out.push(p);
continue;
}
para_buf.push(clean_inline(trimmed));
}
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);
// Ensure we always have a title line for Notes
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(),
ParagraphStyle::Bullet => format!("• {}", p.text),
ParagraphStyle::Dashed => format!("– {}", p.text),
ParagraphStyle::Numbered => {
// Count consecutive numbered items for display numbers
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(),
};
let need_blank = match (prev, p.style) {
(None, _) => false,
(Some(ParagraphStyle::Title), _) => true,
// Apple Notes: blank under Heading/Subheading before body or lists
(
Some(ParagraphStyle::Heading | ParagraphStyle::Subheading),
ParagraphStyle::Body
| ParagraphStyle::Bullet
| ParagraphStyle::Dashed
| ParagraphStyle::Numbered
| ParagraphStyle::Checklist
| ParagraphStyle::Monospace,
) => 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::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,
_ => false,
};
if need_blank && lines.last().map(|s| !s.is_empty()).unwrap_or(false) {
lines.push(String::new());
}
if p.style == ParagraphStyle::Monospace {
for (j, code_line) in rendered.lines().enumerate() {
if j == 0 && need_blank && lines.last().map(|s| !s.is_empty()).unwrap_or(false) {
// already added blank
}
lines.push(code_line.to_string());
}
// trailing blank after code block
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 parse_special_line(trimmed: &str) -> Option<Paragraph> {
// ATX headings
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,
});
}
// Checklist
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,
});
}
}
// Bullets
for prefix in ["* ", "- ", "+ ", "• ", "– ", "— "] {
if let Some(rest) = trimmed.strip_prefix(prefix) {
// avoid matching --- horizontal rules already handled?
if prefix == "- " && (rest.starts_with("--") || rest.is_empty()) {
break;
}
return Some(Paragraph {
style: ParagraphStyle::Bullet,
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 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`
out = strip_wrapping_markers(&out, "**");
out = strip_wrapping_markers(&out, "__");
out = strip_wrapping_markers(&out, "~~");
out = strip_wrapping_markers(&out, "`");
// single-asterisk italics (careful with lists — already handled)
out = strip_wrapping_markers(&out, "*");
out = strip_wrapping_markers(&out, "_");
// [text](url) → text (url)
out = rewrite_md_links(&out);
// collapse whitespace
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 markdown_headings_and_bullets() {
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 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 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");
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);
}
}
|