mod syntax;
#[cfg(test)]
mod tests;
use ratatui::style::{Color, Style};
use ratatui::text::{Line, Span, Text};
use unicode_width::UnicodeWidthStr as _;
pub(crate) use syntax::Syntax;
use syntax::{Container, Kind, Part};
use crate::srcmap::LineOffsets;
use crate::theme::palette;
use crate::wrap::Hang;
const BULLETS: [char; 3] = ['∙', '◦', '▪'];
const TASK_OPEN: char = '☐';
const TASK_DONE: char = '☑';
const QUOTE_BAR: char = '╎';
pub(crate) const RULE: char = '╌';
type StyledChar = (char, Style, Option<usize>);
pub(crate) struct Decorated {
pub(crate) text: Text<'static>,
pub(crate) offsets: Vec<LineOffsets>,
pub(crate) hangs: Vec<Hang>,
}
pub(crate) fn decorate(
syntax: &Syntax,
source: &str,
base: usize,
text: Text<'static>,
offsets: Vec<LineOffsets>,
) -> Decorated {
let mut started = vec![false; syntax.containers.len()];
let mut context = None;
let mut out =
Decorated { text: Text::default().style(text.style), offsets: Vec::new(), hangs: Vec::new() };
for (line, offsets) in text.lines.into_iter().zip(offsets) {
let chars = styled_chars(&line, &offsets);
let (line, offsets, hang) =
match decorate_line(syntax, source, base, &chars, &mut started, &mut context) {
Some((chars, hang)) => {
let (line, offsets) = rebuild(chars, line.style);
(line, offsets, hang)
}
None => (line, offsets, Hang::default()),
};
out.text.lines.push(line);
out.offsets.push(offsets);
out.hangs.push(hang);
}
out
}
fn decorate_line(
syntax: &Syntax,
source: &str,
base: usize,
chars: &[StyledChar],
started: &mut [bool],
context: &mut Option<usize>,
) -> Option<(Vec<StyledChar>, Hang)> {
let offsets = || chars.iter().filter_map(|&(_, _, offset)| offset);
let here = offsets().find(|&o| syntax.is_leaf(o)).or_else(|| offsets().next_back());
*context = here.or(*context);
let chain = syntax.chain((*context)?);
if chain.is_empty() {
return None;
}
let quotes = chain.iter().filter(|&&i| syntax.containers.get(i).is_some_and(Container::is_quote)).count();
let leading = leading_syntax(syntax, source, base, chars, quotes);
let body = chars.get(leading.len..).unwrap_or_default();
let bars = if body.is_empty() { leading.quote_marks } else { quotes };
let mut lead: Vec<(char, Style)> = Vec::new();
let mut rest: Vec<(char, Style)> = Vec::new();
let mut intact = true;
let mut drawn = 0;
for index in chain {
let Some(container) = syntax.containers.get(index) else { continue };
let Some(mark) = mark(container) else {
if drawn == bars {
break;
}
drawn += 1;
let bar = [(QUOTE_BAR, Style::new().fg(palette().idle_fg)), (' ', Style::new())];
lead.extend(bar);
rest.extend(bar);
continue;
};
let blank = std::iter::repeat_n((' ', Style::new()), mark.0.width() + 1);
rest.extend(blank.clone());
match started.get_mut(index) {
Some(started) if !*started => {
*started = true;
intact &= leading.claimed.contains(&index);
lead.extend(mark.0.chars().map(|ch| (ch, mark.1)));
lead.push((' ', Style::new()));
}
_ => lead.extend(blank),
}
}
if !intact {
return None;
}
let hang = Hang {
lead: lead.len(),
rest: rest.into_iter().map(|(ch, style)| Span::styled(ch.to_string(), style)).collect(),
};
let decorated =
lead.into_iter().map(|(ch, style)| (ch, style, None)).chain(body.iter().copied()).collect();
Some((decorated, hang))
}
struct Leading {
len: usize,
claimed: Vec<usize>,
quote_marks: usize,
}
fn leading_syntax(
syntax: &Syntax,
source: &str,
base: usize,
chars: &[StyledChar],
quotes: usize,
) -> Leading {
let prefix = chars
.iter()
.take_while(|&&(ch, _, offset)| {
!ch.is_whitespace() && offset.is_none_or(|o| syntax.part_at(source, base, o) == Some(Part::Quote))
})
.count();
let mut at = if prefix <= quotes { prefix } else { 0 };
let mut quote_marks = at;
let mut claimed = Vec::new();
while let Some(&(ch, _, offset)) = chars.get(at) {
let taken = match offset.map(|o| (o, syntax.part_at(source, base, o))) {
Some((_, Some(Part::Marker(index)))) => {
claimed.push(index);
true
}
Some((_, Some(Part::Quote))) => {
quote_marks += 1;
true
}
Some((o, None)) => ch.is_whitespace() && !syntax.is_leaf(o),
None => ch.is_whitespace(),
};
if !taken {
break;
}
at += 1;
}
Leading { len: at, claimed, quote_marks }
}
fn mark(container: &Container) -> Option<(String, Style)> {
let Kind::Item { shown: number, task, depth, .. } = &container.kind else { return None };
let task = task.as_ref().map(|(_, checked)| if *checked { TASK_DONE } else { TASK_OPEN });
let text = match (number, task) {
(Some(n), Some(task)) => format!("{n}. {task}"),
(Some(n), None) => format!("{n}."),
(None, Some(task)) => task.to_string(),
(None, None) => {
BULLETS.get(depth.saturating_sub(1) % BULLETS.len()).copied().unwrap_or('-').to_string()
}
};
let style = if number.is_some() { Style::new().fg(Color::LightBlue) } else { Style::new() };
Some((text, style))
}
fn styled_chars(line: &Line<'_>, offsets: &[Option<usize>]) -> Vec<StyledChar> {
let mut offsets = offsets.iter();
line.spans
.iter()
.flat_map(|span| span.content.chars().map(move |ch| (ch, span.style)))
.map(|(ch, style)| (ch, style, offsets.next().copied().flatten()))
.collect()
}
fn rebuild(chars: Vec<StyledChar>, line_style: Style) -> (Line<'static>, LineOffsets) {
let mut spans: Vec<Span<'static>> = Vec::new();
let mut offsets = Vec::with_capacity(chars.len());
for (ch, style, offset) in chars {
match spans.last_mut() {
Some(last) if last.style == style => last.content.to_mut().push(ch),
_ => spans.push(Span::styled(ch.to_string(), style)),
}
offsets.push(offset);
}
(Line::from(spans).style(line_style), offsets)
}