//! Plain text adapter. Notes are separated by a form-feed line. A //! note starts with `Key: value` lines, then a blank line, then the //! body. use super::{Fields, build}; use crate::note::Note; const KEYS: [&str; 9] = [ "id", "title", "date", "kind", "tags", "parent", "links", "context", "summary", ]; /// Parse `Key: value` if the key is a known one. fn header_line(line: &str) -> Option<(&str, &str)> { let (k, v) = line.split_once(':')?; let lk = k.trim().to_ascii_lowercase(); if KEYS.contains(&lk.as_str()) && k.trim().len() == k.len() { Some((k, v)) } else { None } } pub fn parse(path: &str, text: &str) -> Vec { // Split into chunks at the form-feed lines. let mut chunks: Vec<(usize, usize, usize)> = Vec::new(); // start, end, line let mut off = 0; let mut cur_start = 0; let mut cur_line = 1; for (ln, line) in text.split_inclusive('\n').enumerate() { if line.trim_end_matches(['\r', '\n']) == "\x0c" { chunks.push((cur_start, off, cur_line)); cur_start = off + line.len(); cur_line = ln + 2; } off += line.len(); } chunks.push((cur_start, text.len(), cur_line)); let mut notes = Vec::new(); for (start, end, line_no) in chunks { let chunk = &text[start..end]; if chunk.trim().is_empty() { continue; } let mut fields = Fields::default(); let mut body_lines: Vec<&str> = Vec::new(); let mut in_header = true; let mut seen = 0; for l in chunk.lines() { if in_header { if seen == 0 && l.trim().is_empty() { continue; } if let Some((k, v)) = header_line(l) { fields.set(k, v); seen += 1; continue; } in_header = false; // The blank line that ends the header is not part of the body. if seen > 0 && l.trim().is_empty() { continue; } } body_lines.push(l); } if fields.title.is_empty() { fields.title = body_lines .iter() .find(|l| !l.trim().is_empty()) .map(|l| l.trim().chars().take(80).collect()) .unwrap_or_default(); } notes.push(build( path, text, start, end, line_no, fields, body_lines.join("\n"), )); } notes }