aboutsummaryrefslogtreecommitdiff
path: root/src/adapter/mod.rs
blob: 8f56b9b2bc371bd0a1012ffff4a259fcc55ee9f9 (plain)
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
//! Format adapters.  Each adapter turns the text of a file into notes.

pub mod org;
pub mod txt;

use crate::note::{Link, Note};
use std::path::Path;

/// Parse the file at `path`, whose content is `text`.  Returns `None`
/// when no adapter handles the extension.
pub fn parse_file(path: &Path, text: &str) -> Option<Vec<Note>> {
    let p = path.to_string_lossy().to_string();
    match path.extension().and_then(|e| e.to_str()) {
        Some("org") => Some(org::parse(&p, text)),
        Some("txt") => Some(txt::parse(&p, text)),
        _ => None,
    }
}

/// The fields every adapter collects before building a note.
#[derive(Default)]
pub struct Fields {
    pub id: Option<String>,
    pub title: String,
    pub date: Option<String>,
    pub kind: Option<String>,
    pub tags: Vec<String>,
    pub parent: Option<String>,
    pub links: Option<String>,
    pub context: Option<String>,
    pub summary: Option<String>,
}

impl Fields {
    /// Store the value of a metadata key.  Returns false for unknown keys.
    pub fn set(&mut self, key: &str, value: &str) -> bool {
        let value = value.trim();
        let some = |v: &str| {
            if v.is_empty() {
                None
            } else {
                Some(v.to_string())
            }
        };
        match key.to_ascii_lowercase().as_str() {
            "id" => self.id = some(value),
            "title" => self.title = value.to_string(),
            "date" => self.date = some(value),
            "kind" => self.kind = some(value),
            "tags" => {
                for t in split_list(value) {
                    if !self.tags.contains(&t) {
                        self.tags.push(t);
                    }
                }
            }
            "parent" => self.parent = some(value),
            "links" => self.links = some(value),
            "context" => self.context = some(value),
            "summary" => self.summary = some(value),
            _ => return false,
        }
        true
    }
}

/// Assemble a note from its fields, its body, and its place in the file.
#[allow(clippy::too_many_arguments)]
pub fn build(
    path: &str,
    text: &str,
    start: usize,
    end: usize,
    line: usize,
    fields: Fields,
    body: String,
) -> Note {
    let mut links = fields
        .links
        .as_deref()
        .map(parse_links_prop)
        .unwrap_or_default();
    for l in body_links(&body) {
        if !links.iter().any(|x| x.dst == l.dst) {
            links.push(l);
        }
    }
    Note {
        id: fields.id,
        path: path.to_string(),
        start,
        end,
        line,
        hash: blake3::hash(text[start..end].as_bytes()).to_hex().to_string(),
        title: fields.title,
        date: fields.date,
        kind: fields.kind,
        tags: fields.tags,
        parent: fields.parent,
        links,
        context: fields.context,
        summary: fields.summary,
        body,
    }
}

/// Split on whitespace, commas and colons.
pub fn split_list(s: &str) -> Vec<String> {
    s.split(|c: char| c.is_whitespace() || c == ',' || c == ':')
        .filter(|t| !t.is_empty())
        .map(|t| t.to_string())
        .collect()
}

fn is_kind(s: &str) -> bool {
    !s.is_empty()
        && s
            .chars()
            .all(|c| c.is_ascii_alphabetic() || c == '-' || c == '_')
}

/// Parse the value of a LINKS property: tokens `ID` or `kind:ID`.
pub fn parse_links_prop(s: &str) -> Vec<Link> {
    let mut out = Vec::new();
    for tok in s.split_whitespace() {
        let link = match tok.split_once(':') {
            Some(("notes" | "note", rest)) if !rest.is_empty() => Link {
                dst: rest.to_string(),
                kind: None,
            },
            Some((k, rest)) if is_kind(k) && !rest.is_empty() => Link {
                dst: rest.to_string(),
                kind: Some(k.to_string()),
            },
            _ => Link {
                dst: tok.to_string(),
                kind: None,
            },
        };
        out.push(link);
    }
    out
}

/// Split the path of a `note:` link into its kind and its ID.
///
/// The path is `ID` for an untyped link and `:KIND:ID` for a typed one,
/// so `[[note:ID]]` and `[[note::KIND:ID]]` are the two forms.
fn split_note_path(p: &str) -> Option<(Option<String>, String)> {
    if p.is_empty() || p.contains(char::is_whitespace) {
        return None;
    }
    match p.strip_prefix(':') {
        Some(rest) => {
            let (k, id) = rest.split_once(':')?;
            let ok = !k.is_empty()
                && k.chars()
                    .all(|c| c.is_ascii_alphanumeric() || c == '-' || c == '_');
            (ok && !id.is_empty()).then(|| (Some(k.to_string()), id.to_string()))
        }
        None => Some((None, p.to_string())),
    }
}

/// Find the `[[note:ID][description]]` links in a body, and their kinds.
/// The description is for humans (usually the title of the note); only
/// the ID is used to locate the note.
pub fn body_links(body: &str) -> Vec<Link> {
    let mut out: Vec<Link> = Vec::new();
    let mut pos = 0;
    while let Some(i) = body[pos..].find("[[note:") {
        let start = pos + i + "[[note:".len();
        let rest = &body[start..];
        match rest.find(']') {
            Some(j) if !rest[..j].contains('\n') => {
                let closes = rest[j..].starts_with("]]") || rest[j..].starts_with("][");
                if closes {
                    if let Some((kind, dst)) = split_note_path(&rest[..j]) {
                        match out.iter_mut().find(|l| l.dst == dst) {
                            // A typed link is more informative than an untyped one.
                            Some(l) => l.kind = l.kind.take().or(kind),
                            None => out.push(Link { dst, kind }),
                        }
                    }
                }
                pos = start + j;
            }
            _ => pos = start,
        }
    }
    out
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn body_links_read_the_id_and_ignore_the_description() {
        let l = body_links(
            "see [[note:abc-1][A title: with colon]] and [[note:<x.y@z>][d]] or [[note:q]] twice [[note:q][again]]",
        );
        let got: Vec<(&str, Option<&str>)> =
            l.iter().map(|x| (x.dst.as_str(), x.kind.as_deref())).collect();
        assert_eq!(got, vec![("abc-1", None), ("<x.y@z>", None), ("q", None)]);
    }

    #[test]
    fn body_links_may_be_typed() {
        let l = body_links("[[note::supports:a1][A]] [[note::contra:<b@c>]] [[note:d]] [[note:d2][x]]");
        let got: Vec<(&str, Option<&str>)> =
            l.iter().map(|x| (x.dst.as_str(), x.kind.as_deref())).collect();
        assert_eq!(
            got,
            vec![("a1", Some("supports")), ("<b@c>", Some("contra")), ("d", None), ("d2", None)]
        );
        // The typed form wins when the same note is linked twice.
        let l = body_links("[[note:a]] and [[note::cites:a]]");
        assert_eq!(l.len(), 1);
        assert_eq!(l[0].kind.as_deref(), Some("cites"));
    }

    #[test]
    fn body_links_ignore_other_links() {
        let body = "[[https://a.b][web]] [[file:x.org]] [[*heading]] [[#custom]] [[./rel][r]] \\
                    [[two words]] [[n1][fuzzy]] [[note:]] [[note:two words]] [[note::bad]] \\
                    [[notes:x]] [[note:a\nb]]";
        assert!(body_links(body).is_empty(), "{:?}", body_links(body));
    }

    #[test]
    fn links_property_has_typed_and_plain_tokens() {
        let l = parse_links_prop("a1 supports:b2 notes:c3 <d@e>");
        let got: Vec<(&str, Option<&str>)> =
            l.iter().map(|x| (x.dst.as_str(), x.kind.as_deref())).collect();
        assert_eq!(
            got,
            vec![("a1", None), ("b2", Some("supports")), ("c3", None), ("<d@e>", None)]
        );
    }

    #[test]
    fn org_notes_are_top_level_headings_only() {
        let text = "intro\n* One :a:b:\n:PROPERTIES:\n:ID: 1\n:PARENT: 0\n:END:\nbody\n** sub\nmore\n* Two\ntext\n";
        let notes = org::parse("/x.org", text);
        assert_eq!(notes.len(), 2);
        assert_eq!(notes[0].id.as_deref(), Some("1"));
        assert_eq!(notes[0].title, "One");
        assert_eq!(notes[0].tags, vec!["a", "b"]);
        assert_eq!(notes[0].parent.as_deref(), Some("0"));
        assert!(notes[0].body.contains("** sub"));
        assert_eq!(notes[0].line, 2);
        assert_eq!(&text[notes[0].start..notes[0].end].lines().next(), &Some("* One :a:b:"));
        assert_eq!(notes[1].id, None);
    }

    #[test]
    fn txt_notes_are_split_at_form_feeds() {
        let text = "ID: 1\nTitle: A\nTags: x y\n\nbody a\n\x0c\nID: 2\nTitle: B\n\nbody b\n\x0c\n\n";
        let notes = txt::parse("/x.txt", text);
        assert_eq!(notes.len(), 2);
        assert_eq!(notes[0].tags, vec!["x", "y"]);
        assert_eq!(notes[0].body, "body a");
        assert_eq!(notes[1].id.as_deref(), Some("2"));
        assert_eq!(notes[1].line, 7);
    }

    #[test]
    fn txt_note_without_header_takes_its_title_from_the_text() {
        let notes = txt::parse("/x.txt", "just a thought\nmore\n");
        assert_eq!(notes.len(), 1);
        assert_eq!(notes[0].title, "just a thought");
        assert_eq!(notes[0].id, None);
    }
}