use crate::config::{CategoryRoot, Config};
use crate::grammar::{self, Grammar};
use crate::types::{Blocker, BookmarkRange, Fragment, Todo};
#[derive(Debug, Default)]
pub struct DecodedSpec {
pub fragment: Option<Fragment>,
pub bookmark: Option<String>,
pub bookmark_range: Option<BookmarkRange>,
}
pub fn decode_specifier(g: &Grammar, text: Option<&str>) -> DecodedSpec {
let Some(text) = text.filter(|t| !t.is_empty()) else {
return DecodedSpec::default();
};
if let Ok(Some(c)) = g.decode_bmr_range.captures(text) {
let start = c.get(1).map(|m| m.as_str().to_string()).filter(|s| !s.is_empty());
let end = c.get(2).map(|m| m.as_str().to_string()).filter(|s| !s.is_empty());
return DecodedSpec {
bookmark_range: Some(BookmarkRange {
start_bookmark: start,
end_bookmark: end,
}),
..DecodedSpec::default()
};
}
if let Ok(Some(c)) = g.decode_bm.captures(text) {
return DecodedSpec {
bookmark: Some(c[1].to_string()),
..DecodedSpec::default()
};
}
if let Ok(Some(c)) = grammar::DECODE_FRAG_RANGE.captures(text) {
let start: u64 = c[1].parse().unwrap_or(0);
let end: u64 = c[2].parse().unwrap_or(0);
return DecodedSpec {
fragment: Some(Fragment {
start,
end,
raw: text.to_string(),
}),
..DecodedSpec::default()
};
}
if let Ok(Some(c)) = grammar::DECODE_FRAG_OFFSET.captures(text) {
let start: u64 = c[1].parse().unwrap_or(0);
let len: u64 = c[2].parse().unwrap_or(0);
return DecodedSpec {
fragment: Some(Fragment {
start,
end: start.saturating_add(len),
raw: text.to_string(),
}),
..DecodedSpec::default()
};
}
if let Ok(Some(c)) = grammar::DECODE_FRAG_SINGLE.captures(text) {
let n: u64 = c[1].parse().unwrap_or(0);
return DecodedSpec {
fragment: Some(Fragment {
start: n,
end: n,
raw: text.to_string(),
}),
..DecodedSpec::default()
};
}
DecodedSpec::default()
}
#[derive(Debug, Clone)]
pub struct SuffixPolicy {
pub categories: bool,
pub tags: bool,
pub root: Option<String>,
}
impl SuffixPolicy {
pub fn from_config(cfg: &Config) -> Self {
SuffixPolicy {
categories: cfg.enabled("parse_categories", true),
tags: cfg.enabled("parse_tags", true),
root: match cfg.category_root() {
CategoryRoot::Root(r) => Some(r),
_ => None,
},
}
}
pub fn cut(&self, g: &Grammar, annot: &str) -> usize {
let mut rest = annot;
let mut kept = 0;
if let Ok(Some(c)) = g.decode_category_prefix.captures(rest) {
let m = c.get(0).unwrap();
if !self.categories {
return 0;
}
if let Some(root) = &self.root {
let first = c[1].split("::").next().unwrap_or("").to_lowercase();
if &first != root {
return 0;
}
}
kept = m.end();
rest = &rest[m.end()..];
}
if !self.tags && rest.starts_with("..") {
return kept;
}
annot.len()
}
}
pub fn decode_annotations(g: &Grammar, text: &str) -> (Option<String>, Vec<String>) {
let mut rest = text;
let mut category = None;
if let Ok(Some(c)) = g.decode_category_prefix.captures(rest) {
let m = c.get(0).unwrap();
category = Some(c[1].to_lowercase());
rest = &rest[m.end()..];
}
let mut tags: Vec<String> = Vec::new();
let mut seen = std::collections::HashSet::new();
while let Ok(Some(c)) = g.decode_tag_prefix.captures(rest) {
let m = c.get(0).unwrap();
let t = c[1].to_lowercase();
if seen.insert(t.clone()) {
tags.push(t);
}
rest = &rest[m.end()..];
}
(category, tags)
}
pub struct TodoError {
pub code: &'static str,
pub message: String,
}
fn todo_err(code: &'static str, message: impl Into<String>) -> TodoError {
TodoError {
code,
message: message.into(),
}
}
pub fn decode_todo_body(
g: &Grammar,
body: &str,
policy: &SuffixPolicy,
) -> Result<Todo, TodoError> {
let trimmed = body.trim_end_matches([' ', '\t']);
let Some(caps) = g.decode_todo_body.captures(trimmed).ok().flatten() else {
if grammar::TODO_WS_BEFORE_PAREN.is_match(trimmed).unwrap_or(false)
|| grammar::TODO_WS_AFTER_PAREN.is_match(trimmed).unwrap_or(false)
{
return Err(todo_err(
"Jots/Parsing/WhitespaceInBlockers",
"whitespace around or inside the blocker slot is not allowed",
));
}
if g.todo_malformed_due.is_match(trimmed).unwrap_or(false) {
return Err(todo_err(
"Jots/Parsing/MalformedDueDate",
"'@' after the action does not introduce a valid ISO 8601 due date",
));
}
return Err(todo_err(
"Jots/Parsing/TodoMissingAction",
"todo '??' is missing an action",
));
};
let done = caps.get(1).is_some();
let imp = caps.get(2).map(|m| m.as_str().len() as u8).unwrap_or(0);
let blockers = decode_blockers(g, caps.get(3).map(|m| m.as_str()))?;
let action = caps[4].to_string();
let due = caps.get(5).map(|m| m.as_str().to_string());
let annot_m = caps.get(6);
let annot = annot_m.map(|m| m.as_str()).unwrap_or("");
let desc_raw = caps.get(7).map(|m| m.as_str()).unwrap_or("");
let cut = policy.cut(g, annot);
let (category, tags, desc_raw) = if cut < annot.len() {
let (c, t) = decode_annotations(g, &annot[..cut]);
let from = annot_m.unwrap().start() + cut;
(c, t, &trimmed[from..])
} else {
let (c, t) = decode_annotations(g, annot);
(c, t, desc_raw)
};
let description = desc_raw.trim_matches([' ', '\t'].as_ref()).to_string();
Ok(Todo {
importance: imp,
blockers,
action,
categories: category.into_iter().collect(),
tags,
due,
completed: None,
description,
references: Vec::new(),
cross_references: Vec::new(),
file_references: Vec::new(),
cross_file_references: Vec::new(),
inter_jot_resources: Vec::new(),
resources: Vec::new(),
urls: Vec::new(),
loc: None,
raw: None,
done,
})
}
fn decode_blockers(g: &Grammar, slot: Option<&str>) -> Result<Vec<Blocker>, TodoError> {
let Some(content) = slot else {
return Ok(Vec::new());
};
if content.contains([' ', '\t']) {
return Err(todo_err(
"Jots/Parsing/WhitespaceInBlockers",
"whitespace inside the blocker parens is not allowed",
));
}
if content.is_empty() {
return Err(todo_err(
"Jots/Parsing/EmptyBlockerList",
"blocker slot '()' has no entries",
));
}
let mut blockers = Vec::new();
for entry in content.split(',') {
if entry.is_empty() {
return Err(todo_err(
"Jots/Parsing/EmptyBlockerEntry",
"empty entry in blocker list",
));
}
if entry.starts_with('*') {
let Ok(Some(c)) = g.blocker_entry_wildcard.captures(entry) else {
return Err(todo_err(
"Jots/Parsing/InvalidWildcardBlocker",
"wildcard blocker entry requires a '::category' constraint",
));
};
blockers.push(Blocker {
action: "*".to_string(),
cat: Some(c[1].trim_start_matches("::").to_lowercase()),
tags: decode_entry_tags(c.get(2).map(|m| m.as_str()).unwrap_or("")),
});
} else {
let Ok(Some(c)) = g.blocker_entry_word.captures(entry) else {
return Err(todo_err(
"Jots/Parsing/InvalidPayloadChars",
"blocker entry contains characters outside the blocker grammar",
));
};
blockers.push(Blocker {
action: c[1].to_string(),
cat: c
.get(2)
.map(|m| m.as_str().trim_start_matches("::").to_lowercase()),
tags: decode_entry_tags(c.get(3).map(|m| m.as_str()).unwrap_or("")),
});
}
}
Ok(blockers)
}
fn decode_entry_tags(tail: &str) -> Vec<String> {
let mut tags = Vec::new();
let mut seen = std::collections::HashSet::new();
for seg in tail.split("..").filter(|s| !s.is_empty()) {
let t = seg.to_lowercase();
if seen.insert(t.clone()) {
tags.push(t);
}
}
tags
}
pub fn is_valid_iso_date(s: &str) -> bool {
let Ok(Some(c)) = grammar::ISO_DATE_VALIDATOR.captures(s) else {
return false;
};
let y: i32 = c[1].parse().unwrap_or(0);
let m: u32 = c[2].parse().unwrap_or(0);
let d: u32 = c[3].parse().unwrap_or(0);
if !(1..=12).contains(&m) {
return false;
}
if !(1..=31).contains(&d) {
return false;
}
let days = [31u32, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31];
let mut max = days[(m - 1) as usize];
if m == 2 {
let leap = (y % 400 == 0) || (y % 4 == 0 && y % 100 != 0);
if leap {
max = 29;
}
}
if d > max {
return false;
}
if let Some(h_match) = c.get(4) {
let h: u32 = h_match.as_str().parse().unwrap_or(0);
let mn: u32 = c[5].parse().unwrap_or(0);
if h > 23 {
return false;
}
if mn > 59 {
return false;
}
if let Some(s_match) = c.get(6) {
let s_val: u32 = s_match.as_str().parse().unwrap_or(0);
if s_val > 60 {
return false;
}
}
}
true
}