Cotton code
132 lines · 4.8 KB · RustRaw
//! SEARCH WORDS — what a person types in the list's search, read as terms//! that must all hold: words, `"phrases"`, `-word`, `#tag` (and the tags//! under it), `-#tag`, and the special words `@todo`, `@done`, `@today`,//! `@images`, `@untagged`, `@pinned`, `@assistant`. An unknown `@word` is a//! word. Pure: the core hands each note's [`Facts`].use serde::{Deserialize, Serialize};use super::find;#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]#[serde(rename_all = "snake_case")]pub enum TermKind {    Word,    Phrase,    Tag,    Special,}#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)]pub struct Term {    pub kind: TermKind,    /// Excluded: `-word`.    pub not: bool,    /// As written, for a chip.    pub said: String,    /// What it compares: the words, the tag, or the special word without `@`.    pub value: String,}/// The special words.pub const SPECIALS: [&str; 7] = ["todo", "done", "today", "images", "untagged", "pinned", "assistant"];/// What a note is, for a search.#[derive(Debug, Clone, Default)]pub struct Facts<'a> {    /// Its whole text (the title is its first line).    pub text: &'a str,    /// Its tags as written (`a/b`).    pub tags: &'a [String],    pub open_checks: u32,    pub checks: u32,    pub today: bool,    pub pictures: bool,    pub pinned: bool,    pub by_assistant: bool,}/// The terms of a search, in the order written.pub fn parse(search: &str) -> Vec<Term> {    let mut out = Vec::new();    let chars: Vec<char> = search.chars().collect();    let mut k = 0;    while k < chars.len() {        if chars[k].is_whitespace() {            k += 1;            continue;        }        let start = k;        let not = chars[k] == '-' && k + 1 < chars.len() && !chars[k + 1].is_whitespace();        if not {            k += 1;        }        let said_from = start;        if chars[k] == '"' {            let close = chars[k + 1..].iter().position(|c| *c == '"').map(|n| k + 1 + n);            let end = close.unwrap_or(chars.len());            let value: String = chars[k + 1..end].iter().collect();            k = close.map_or(chars.len(), |c| c + 1);            if !value.trim().is_empty() {                out.push(Term { kind: TermKind::Phrase, not, said: chars[said_from..k].iter().collect(), value: value.trim().to_string() });            }            continue;        }        if chars[k] == '#' {            // `#two words#` when a closing `#` comes before the next `#`-word or the end.            let rest: String = chars[k..].iter().collect();            if let Some((len, name)) = tag_term(&rest) {                let end = k + rest[..len].chars().count();                out.push(Term { kind: TermKind::Tag, not, said: chars[said_from..end].iter().collect(), value: name });                k = end;                continue;            }        }        let end = chars[k..].iter().position(|c| c.is_whitespace()).map_or(chars.len(), |n| k + n);        let word: String = chars[k..end].iter().collect();        let said: String = chars[said_from..end].iter().collect();        k = end;        if let Some(special) = word.strip_prefix('@').map(str::to_lowercase).filter(|w| SPECIALS.contains(&w.as_str())) {            out.push(Term { kind: TermKind::Special, not, said, value: special });        } else if !word.is_empty() {            out.push(Term { kind: TermKind::Word, not, said, value: word });        }    }    out}/// A `#tag` term at the start of `rest`: its byte length and its tag.fn tag_term(rest: &str) -> Option<(usize, String)> {    // The writing rule's own reading of a hashtag, on this one line.    let line = rest.lines().next().unwrap_or_default();    let (end, name) = super::inline::tag_at(line, 0, line.len())?;    Some((end, name))}/// Does the note hold every term?pub fn matches(terms: &[Term], facts: &Facts<'_>) -> bool {    terms.iter().all(|term| holds(term, facts) != term.not)}fn holds(term: &Term, facts: &Facts<'_>) -> bool {    match term.kind {        TermKind::Word | TermKind::Phrase => find::holds(facts.text, &term.value),        TermKind::Tag => {            let wanted = super::derive::tag_key(&term.value);            facts.tags.iter().any(|tag| {                let own = super::derive::tag_key(tag);                own == wanted || own.strip_prefix(wanted.as_str()).is_some_and(|rest| rest.starts_with('/'))            })        }        TermKind::Special => match term.value.as_str() {            "todo" => facts.open_checks > 0,            "done" => facts.checks > 0 && facts.open_checks == 0,            "today" => facts.today,            "images" => facts.pictures,            "untagged" => facts.tags.is_empty(),            "pinned" => facts.pinned,            "assistant" => facts.by_assistant,            _ => false,        },    }}