use super::Deriver;
use crate::{
grammar::{
Block, Found, Label, Shape, Squashed, Unit, begins_with_key, carries_labels, cut, squash,
task_box,
},
markdown::BlockKind,
};
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub(super) struct Carried {
pub(super) any: bool,
pub(super) key: Option<String>,
pub(super) fails: bool,
}
impl Deriver<'_> {
fn writes_labels(&self, block: &Block, rule: Option<&Unit>) -> bool {
!self.labels.is_empty() && carries_labels(block.kind) && block.label_of(rule).is_some()
}
pub(super) fn unlabel(
&self,
block: &Block,
rule: Option<&Unit>,
text: String,
) -> (String, Carried) {
if !self.writes_labels(block, rule) {
return (text, Carried::default());
}
let (bare, found) = self.cut_label(block, rule, &text);
let shaped = |r: &Unit| {
matches!(r.shape, Some(Shape::Template(_) | Shape::Pattern(_))) || r.format.is_some()
};
if let Some(r) = rule.filter(|r| shaped(r))
&& !r.fits(&self.schema.core.formats, &squash(&bare), |_| None)
{
return (
text,
Carried {
fails: true,
..Carried::default()
},
);
}
let carried = Carried {
any: found.is_some(),
key: found.and_then(|f| self.labels.key_of(&f.words).map(str::to_string)),
fails: false,
};
(bare, carried)
}
pub(super) fn relabel(
&self,
block: &Block,
rule: Option<&Unit>,
text: String,
carried: &Carried,
) -> String {
if !self.writes_labels(block, rule) || carried.fails {
return text;
}
if block.label_of(rule) == Some(Label::Optional) && !carried.any {
return text;
}
let key = self
.named_label
.as_deref()
.or(carried.key.as_deref())
.or_else(|| self.labels.first());
let Some(words) = key.and_then(|k| self.labels.words(k)) else {
return text;
};
let label = format!("[{words}] ");
let item = matches!(block.kind, BlockKind::BulletList | BlockKind::NumberedList);
let base = if item { task_box(&text) } else { 0 };
let formats = &self.schema.core.formats;
let after_key = rule
.filter(|r| self.schema.unit_captures_key(r))
.and_then(|r| r.key_in(formats, &squash(&text)))
.filter(|k| begins_with_key(&text[base..], k));
let at = match after_key {
Some(k) if text.len() == base + k.len() => return text,
Some(k) => base + k.len() + 1,
None => base,
};
format!("{}{label}{}", &text[..at], &text[at..])
}
pub(super) fn read_as(&self, block: &Block, rule: &Unit, text: &str) -> String {
self.cut_label(block, Some(rule), text).0
}
fn cut_label(&self, block: &Block, rule: Option<&Unit>, text: &str) -> (String, Option<Found>) {
if self.labels.is_empty() || !carries_labels(block.kind) {
return (text.to_string(), None);
}
let squashed = Squashed::new(text);
match self
.schema
.label_in(&self.labels, block, rule, &squashed.text)
{
Some(f) => {
let at = squashed.original(f.at.start)..squashed.original(f.at.end);
(cut(text, &at), Some(f))
}
None => (text.to_string(), None),
}
}
}