summaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
Diffstat (limited to 'src')
-rw-r--r--src/browser.rs2
-rw-r--r--src/format.rs353
2 files changed, 312 insertions, 43 deletions
diff --git a/src/browser.rs b/src/browser.rs
index 7763ef9..2cecf5a 100644
--- a/src/browser.rs
+++ b/src/browser.rs
@@ -238,6 +238,8 @@ fn paragraphs_json(title: &str, body: &str) -> Result<String> {
ParagraphStyle::Numbered => "numbered",
ParagraphStyle::Checklist => "checklist",
ParagraphStyle::Monospace => "mono",
+ ParagraphStyle::Divider => "divider",
+ ParagraphStyle::BlockQuote => "quote",
},
"text": p.text,
"checked": p.checked,
diff --git a/src/format.rs b/src/format.rs
index 2e7b020..4495638 100644
--- a/src/format.rs
+++ b/src/format.rs
@@ -1,5 +1,13 @@
-//! Format note content the way Apple Notes expects to look:
-//! Title (first line) → optional Heading/Subheading → Body paragraphs → lists.
+//! 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.
@@ -17,6 +25,10 @@ pub enum ParagraphStyle {
Numbered,
Checklist,
Monospace,
+ /// Apple Notes “Insert Divider Line” (plain-text stand-in).
+ Divider,
+ /// Apple Notes Block Quote style.
+ BlockQuote,
}
#[derive(Debug, Clone, PartialEq, Eq)]
@@ -50,6 +62,7 @@ pub fn build_paragraphs(title: &str, body: &str) -> Vec<Paragraph> {
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() {
@@ -76,11 +89,36 @@ pub fn build_paragraphs(title: &str, body: &str) -> Vec<Paragraph> {
});
};
- for raw in body.lines() {
- let line = raw.trim_end();
+ 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();
@@ -97,45 +135,74 @@ pub fn build_paragraphs(title: &str, body: &str) -> Vec<Paragraph> {
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;
}
- // Horizontal rules — visual noise in Notes; skip
- if trimmed.chars().all(|c| c == '-' || c == '*' || c == '_') && trimmed.len() >= 3 {
+ // 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.text.is_empty() {
+ 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 p.style == ParagraphStyle::Heading
- && out
- .first()
- .map(|t| t.style == ParagraphStyle::Title && titles_equal(&t.text, &p.text))
- .unwrap_or(false)
+ 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() {
@@ -149,7 +216,7 @@ pub fn build_paragraphs(title: &str, body: &str) -> Vec<Paragraph> {
}
flush_para(&mut para_buf, &mut out);
- // Ensure we always have a title line for Notes
+ // Apple: first line of the note becomes the title
if out.is_empty() {
out.push(Paragraph {
style: ParagraphStyle::Title,
@@ -184,10 +251,10 @@ pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
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 => {
- // Count consecutive numbered items for display numbers
let n = paragraphs[..=i]
.iter()
.rev()
@@ -203,12 +270,20 @@ pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
}
}
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,
- // Apple Notes: blank under Heading/Subheading before body or lists
(
Some(ParagraphStyle::Heading | ParagraphStyle::Subheading),
ParagraphStyle::Body
@@ -216,12 +291,19 @@ pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
| ParagraphStyle::Dashed
| ParagraphStyle::Numbered
| ParagraphStyle::Checklist
- | ParagraphStyle::Monospace,
+ | 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(
@@ -239,6 +321,28 @@ pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
| 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) {
@@ -246,13 +350,9 @@ pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
}
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
- }
+ for code_line in rendered.lines() {
lines.push(code_line.to_string());
}
- // trailing blank after code block
lines.push(String::new());
} else {
lines.push(rendered);
@@ -266,8 +366,16 @@ pub fn paragraphs_to_plain(paragraphs: &[Paragraph]) -> String {
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
+ // 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,
@@ -290,8 +398,33 @@ fn parse_special_line(trimmed: &str) -> Option<Paragraph> {
});
}
- // Checklist
- for (prefix, checked) in [("* [x] ", true), ("* [X] ", true), ("* [ ] ", false), ("- [x] ", true), ("- [X] ", true), ("- [ ] ", false), ("+ [x] ", true), ("+ [ ] ", 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,
@@ -301,19 +434,52 @@ fn parse_special_line(trimmed: &str) -> Option<Paragraph> {
}
}
- // 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,
- });
- }
+ // 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"
@@ -341,6 +507,75 @@ fn parse_special_line(trimmed: &str) -> Option<Paragraph> {
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());
@@ -359,16 +594,16 @@ fn clean_title(title: &str) -> String {
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, "`");
- // single-asterisk italics (careful with lists — already handled)
out = strip_wrapping_markers(&out, "*");
out = strip_wrapping_markers(&out, "_");
- // [text](url) → text (url)
+ // ==highlight== → plain (Notes highlight is color-only)
+ out = strip_wrapping_markers(&out, "==");
out = rewrite_md_links(&out);
- // collapse whitespace
let parts: Vec<_> = out.split_whitespace().collect();
parts.join(" ")
}
@@ -453,18 +688,25 @@ mod tests {
}
#[test]
- fn markdown_headings_and_bullets() {
+ 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("– 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",
@@ -485,6 +727,28 @@ mod tests {
}
#[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);
@@ -503,10 +767,13 @@ mod tests {
#[test]
fn structured_styles() {
- let ps = build_paragraphs("T", "## H\n\nbody para\n\n- a");
+ 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);
}
}