//! Org adapter: each top-level heading is a note. Metadata lives in //! the heading (title, tags) and in its property drawer. use super::{Fields, build}; use crate::note::Note; fn is_tag_string(s: &str) -> bool { s.len() > 2 && s.starts_with(':') && s.ends_with(':') && s.chars() .all(|c| c.is_alphanumeric() || "_@#%:.".contains(c)) } /// Split a heading line into its title and its tags. fn parse_heading(line: &str) -> (String, Vec) { let h = line.trim_start_matches('*').trim(); if let Some(idx) = h.rfind(char::is_whitespace) { let last = &h[idx + 1..]; if is_tag_string(last) { let tags = last .split(':') .filter(|t| !t.is_empty()) .map(|t| t.to_string()) .collect(); return (h[..idx].trim().to_string(), tags); } } (h.to_string(), Vec::new()) } fn is_planning(line: &str) -> bool { let t = line.trim_start(); t.starts_with("SCHEDULED:") || t.starts_with("DEADLINE:") || t.starts_with("CLOSED:") } pub fn parse(path: &str, text: &str) -> Vec { // Find the top-level headings: a single star at column 0. let mut heads: Vec<(usize, usize)> = Vec::new(); let mut off = 0; for (ln, line) in text.split_inclusive('\n').enumerate() { let t = line.trim_end(); if line.starts_with("* ") || t == "*" { heads.push((off, ln + 1)); } off += line.len(); } let mut notes = Vec::new(); for (i, &(start, line_no)) in heads.iter().enumerate() { let end = heads.get(i + 1).map(|h| h.0).unwrap_or(text.len()); let chunk = &text[start..end]; let mut lines = chunk.lines(); let heading = lines.next().unwrap_or(""); let (title, tags) = parse_heading(heading); let mut fields = Fields { title, tags, ..Default::default() }; let mut rest: Vec<&str> = lines.collect(); // Skip planning lines, then read the property drawer, if any. let mut k = 0; while k < rest.len() && is_planning(rest[k]) { k += 1; } let mut body_from = 0; if k < rest.len() && rest[k].trim() == ":PROPERTIES:" { let mut j = k + 1; while j < rest.len() && rest[j].trim() != ":END:" { let l = rest[j].trim(); if let Some(r) = l.strip_prefix(':') { if let Some((key, val)) = r.split_once(':') { fields.set(key, val); } } j += 1; } body_from = (j + 1).min(rest.len()); } let body = rest.split_off(body_from).join("\n"); notes.push(build(path, text, start, end, line_no, fields, body)); } notes }