aboutsummaryrefslogtreecommitdiff
path: root/src/adapter/txt.rs
blob: ddea799b098d5ab9c491d0434a61668750b3a2f3 (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
//! 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<Note> {
    // 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
}