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
|
//! 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<String>) {
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<Note> {
// 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
}
|