Initial public release

Luxe 0.1.0: a coding agent harness for the terminal. See README.md to get started and CHANGELOG.md for releases.
This commit is contained in:
Evan Whittaker
2026-10-17 12:08:30 -05:00
commit 09a7de2520
1730 changed files with 412952 additions and 0 deletions

View File

@@ -0,0 +1,143 @@
//! Markdown fences — a code block's lines and the frame drawn around them.
use super::line::{FenceRule, MarkdownLine};
use super::voice::{build_code_style, build_fence_border_style, MarkdownVoice};
use crate::glyphs::Icon;
use crate::theme::styles::ThemeStyles;
use ratatui::text::{Line, Span};
use unicode_width::UnicodeWidthStr;
/// A code block being collected: whether the walk is inside one, what it declared, its text.
#[derive(Default)]
pub(super) struct FenceBuilder {
active: bool,
lang: Option<String>,
lines: Vec<String>,
}
impl FenceBuilder {
/// Opens a block; an indented one declares no language.
pub(super) fn begin(&mut self, lang: Option<String>) {
self.active = true;
self.lang = lang;
}
/// Whether the walk is inside a code block, where everything inline is source.
pub(super) fn active(&self) -> bool {
self.active
}
pub(super) fn push(&mut self, text: String) {
self.lines.push(text);
}
/// Closes the block: its framed lines when it held any code, nothing when it was empty.
pub(super) fn finish(
&mut self,
theme: &ThemeStyles,
voice: MarkdownVoice,
) -> Vec<MarkdownLine> {
let lines = match self.lines.is_empty() {
true => Vec::new(),
false => {
framed_fence(&std::mem::take(&mut self.lines), self.lang.as_deref(), theme, voice)
}
};
self.active = false;
self.lang = None;
lines
}
}
/// A code block's lines between its two rules: the language and the copy affordance on the top
/// one, nothing on the bottom, both the width of the widest row.
fn framed_fence(
code_lines: &[String],
code_lang: Option<&str>,
theme: &ThemeStyles,
voice: MarkdownVoice,
) -> Vec<MarkdownLine> {
let mut lines = Vec::new();
let code_str = code_lines.join("\n");
let rendered = fence_lines(&code_str, code_lang, theme, voice);
let caption = theme.muted.add_modifier(voice.modifier());
let border = build_fence_border_style(theme, voice);
let ends_at = rendered.iter().map(Line::width).max().unwrap_or(0);
// The language the fence declared, if it declared one worth naming. An
// unlabeled fence gets a rule with nothing on its left rather than the word
// "text", which would be Luxe guessing on the author's behalf.
let lead = fence_language(code_lang)
.map(|language| {
// The language's own mark where the terminal can draw one, and the bare
// word where it cannot — `icon_label` drops the glyph *and* its
// clearance, so the label does not sit one column in from the rule.
let icon = crate::widgets::language_icon(&language).glyph();
vec![Span::styled(crate::glyphs::icon_label(icon, &language), caption)]
})
.unwrap_or_default();
let tail = vec![Span::styled(crate::glyphs::icon_label(Icon::Copy.glyph(), "copy"), caption)];
// The frame may be wider than the code it frames. A box around three words is
// still a box, and clamping to the block's own width instead collapsed the
// rule out of existence on exactly the short snippets answers are full of.
// Both rules take the same width, or they would not line up.
let frame = ends_at.max(fence_frame_minimum(&lead, &tail));
lines.push(MarkdownLine::fence_top(
FenceRule { lead, tail, ends_at: frame, style: border },
code_str,
));
lines.extend(rendered.into_iter().map(MarkdownLine::wide));
lines.push(MarkdownLine::fence_bottom(FenceRule {
lead: Vec::new(),
tail: Vec::new(),
ends_at: frame,
style: border,
}));
lines
}
/// The lines of a fenced code block.
///
/// Syntax highlighting is an answer's; a reasoning fence takes the voice's own code style, because
/// a syntect palette inside a muted italic block reads as a different message entirely.
fn fence_lines(
code: &str,
lang: Option<&str>,
theme: &ThemeStyles,
voice: MarkdownVoice,
) -> Vec<Line<'static>> {
match voice {
MarkdownVoice::Answer => crate::highlight::highlight_code(code, lang, theme),
MarkdownVoice::Reasoning => {
let style = build_code_style(theme, voice);
code.lines().map(|line| Line::from(Span::styled(line.to_string(), style))).collect()
}
}
}
/// The narrowest frame that still seats both labels with a cell of rule at each end.
///
/// Mirrors what [`crate::view::wrapping`] spends laying one out; the two have to agree, or the top
/// rule falls back to bare labels while the bottom one draws at a width nothing matches.
fn fence_frame_minimum(lead: &[Span<'static>], tail: &[Span<'static>]) -> usize {
let width = |spans: &[Span<'static>]| -> usize {
spans.iter().map(|span| UnicodeWidthStr::width(span.content.as_ref())).sum()
};
let label = |spans: &[Span<'static>]| match width(spans) {
0 => 0,
cells => cells + crate::view::wrapping::LABEL_FRAME,
};
label(lead) + label(tail) + crate::view::wrapping::MIN_FENCE_FILL
}
/// The language a fence's rule announces, normalized, or `None` when it named nothing useful.
///
/// Trimmed and lowercased because a fence is written by hand and `Rust`, `RUST` and `rust ` are the
/// same language. Only the first token survives: rustdoc writes `rust,ignore` and mdBook writes
/// `rust no_run`, and neither suffix is the name of anything. `text` and `plain` are dropped
/// outright — they say a fence is a fence.
pub(super) fn fence_language(lang: Option<&str>) -> Option<String> {
let lang = lang?.trim().to_lowercase();
let lang = lang.split([',', ' ', '\t', '{']).next()?.to_string();
(!lang.is_empty() && !matches!(lang.as_str(), "text" | "plain" | "plaintext" | "txt"))
.then_some(lang)
}

View File

@@ -0,0 +1,380 @@
//! Markdown layout — the walk over pulldown-cmark's events that turns source into lines.
//!
//! One forward walk, with each independent piece of state owned by what it describes: the inline
//! run being built, the list nesting, the fence being collected, the table being collected. The
//! dispatcher only routes; each arm moves one of those owners or calls a builder.
use super::fence::FenceBuilder;
use super::line::MarkdownLine;
use super::table::TableBuilder;
use super::voice::{
alert_icon, alert_label, build_alert_style, build_code_style, build_heading_style,
build_hr_style, build_link_style, build_link_url_style, build_quote_style, build_style,
build_text_style, MarkdownVoice,
};
use crate::theme::styles::ThemeStyles;
use pulldown_cmark::TagEnd;
use pulldown_cmark::{BlockQuoteKind, CodeBlockKind, Event, HeadingLevel, Options, Parser, Tag};
use ratatui::style::Modifier;
use ratatui::text::{Line, Span};
/// True when a rendered line carries no visible content (guards against double blanks).
fn is_blank_md_line(line: &MarkdownLine) -> bool {
// A fence's frame carries its content in `fence_rule` and leaves `line` empty, so the span
// check alone called a rule blank — and the gap after a code block went missing, running the
// closing rule straight into the next paragraph.
line.fence_rule.is_none()
&& line.table.is_none()
&& line.line.spans.iter().all(|span| span.content.trim().is_empty())
}
/// Inserts a single blank line between top-level blocks so paragraphs, lists, headings, code, and
/// tables read as distinct blocks instead of running together. No-op at the start of the output or
/// right after an existing blank.
fn push_block_gap(lines: &mut Vec<MarkdownLine>) {
if lines.last().is_some_and(|last| !is_blank_md_line(last)) {
lines.push(MarkdownLine::prose(Line::default()));
}
}
/// Renders markdown in `voice`, preserving the structural block kinds conversation layout needs.
pub(crate) fn layout_markdown_in(
src: &str,
theme: &ThemeStyles,
voice: MarkdownVoice,
) -> Vec<MarkdownLine> {
let mut opts = Options::empty();
opts.insert(Options::ENABLE_STRIKETHROUGH);
opts.insert(Options::ENABLE_TABLES);
// Alerts (`> [!WARNING]`) are the GitHub dialect models were trained on and write unprompted.
// Without this the tag is body text, and the quote opens with a literal `[!WARNING]`.
opts.insert(Options::ENABLE_GFM);
let mut renderer = MarkdownRenderer::new(theme, voice);
for event in Parser::new_ext(src, opts) {
renderer.event(event);
}
// Flush any remaining spans
renderer.flush_prose();
renderer.lines
}
/// The inline run being built: its spans, the modifiers open around them, and the link they sit in.
#[derive(Default)]
struct InlineState {
line: Vec<Span<'static>>,
style_stack: Vec<Modifier>,
/// The url while inside a link
link_url: Option<String>,
/// What the link says, to leave out a url that repeats it
link_text: String,
}
/// List nesting: how deep, whether each level is ordered, and each level's count so far.
#[derive(Default)]
struct ListState {
depth: usize,
/// Right after an item opens, so its first paragraph does not flush the prefix away
item_just_started: bool,
ordered: Vec<bool>,
counters: Vec<usize>,
}
impl ListState {
fn begin(&mut self, ordered: bool) {
self.depth += 1;
self.ordered.push(ordered);
self.counters.push(0);
}
fn end(&mut self) {
self.depth = self.depth.saturating_sub(1);
self.ordered.pop();
self.counters.pop();
}
/// The next item's prefix at the current depth: its number, or a bullet.
fn next_prefix(&mut self) -> String {
// depth is already incremented by Start(List), so top-level items have depth 1
let indent = " ".repeat(self.depth.saturating_sub(1));
let counter = self
.counters
.last_mut()
.expect("an item opens inside a list, and every list pushes its counter");
*counter += 1;
if self.ordered.last().copied().unwrap_or(false) {
format!("{indent}{counter}. ")
} else {
format!("{indent}• ")
}
}
}
/// One walk's state, and the lines it has laid out so far.
struct MarkdownRenderer<'a> {
theme: &'a ThemeStyles,
voice: MarkdownVoice,
lines: Vec<MarkdownLine>,
inline: InlineState,
list: ListState,
fence: FenceBuilder,
table: TableBuilder,
heading_level: Option<HeadingLevel>,
in_blockquote: bool,
/// Right after an alert's word, so its gap is suppressed
alert_just_labeled: bool,
}
impl<'a> MarkdownRenderer<'a> {
fn new(theme: &'a ThemeStyles, voice: MarkdownVoice) -> Self {
Self {
theme,
voice,
lines: Vec::new(),
inline: InlineState::default(),
list: ListState::default(),
fence: FenceBuilder::default(),
table: TableBuilder::default(),
heading_level: None,
in_blockquote: false,
alert_just_labeled: false,
}
}
fn event(&mut self, event: Event<'_>) {
match event {
Event::Start(tag) => self.start(tag),
Event::End(tag) => self.end(tag),
Event::Code(text) => self.code(&text),
Event::Html(html) => {
let span = Span::styled(html.to_string(), build_text_style(self.theme, self.voice));
self.quote_prefix();
self.append_inline(span, false);
}
Event::Text(text) => self.text(&text),
Event::SoftBreak | Event::HardBreak => {
let style =
build_style(&self.inline.style_stack, build_text_style(self.theme, self.voice));
let hard = matches!(event, Event::HardBreak) || self.voice.breaks_on_soft_break();
self.append_inline(Span::styled(if hard { "\n" } else { " " }, style), false);
}
Event::Rule => {
// Horizontal rule — flush pending, add themed styled line
self.flush_prose();
push_block_gap(&mut self.lines);
let hr_style = build_hr_style(self.theme, self.voice);
let hr_span =
Span::styled("━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━", hr_style);
self.lines.push(MarkdownLine::prose(Line::from(vec![hr_span])));
}
Event::TaskListMarker(_) => {
// Checkbox — treat as plain text for now
let span = Span::styled("[ ] ", build_text_style(self.theme, self.voice));
self.append_inline(span, false);
}
// Ignore other events (InlineHtml, FootnoteReference, etc.)
_ => {}
}
}
fn start(&mut self, tag: Tag<'_>) {
match tag {
Tag::Paragraph => {
// Flush any pending inline spans as a completed line.
if !self.list.item_just_started {
self.flush_prose();
}
// Blank line between top-level blocks; keep list-item paragraphs tight, and an
// alert's word against the sentence it introduces.
if self.list.depth == 0 && !self.list.item_just_started && !self.alert_just_labeled
{
push_block_gap(&mut self.lines);
}
self.alert_just_labeled = false;
}
Tag::BlockQuote(kind) => self.begin_quote(kind),
Tag::List(ordered) => {
if self.list.depth == 0 {
push_block_gap(&mut self.lines);
}
self.list.begin(ordered.is_some());
}
Tag::Heading { level, .. } => {
// Flush pending inline spans before heading
self.flush_prose();
push_block_gap(&mut self.lines);
self.heading_level = Some(level);
}
Tag::Strong => self.inline.style_stack.push(Modifier::BOLD),
Tag::Emphasis => self.inline.style_stack.push(Modifier::ITALIC),
Tag::Strikethrough => self.inline.style_stack.push(Modifier::CROSSED_OUT),
Tag::Link { dest_url, .. } => {
self.inline.link_url = Some(dest_url.to_string());
self.inline.link_text.clear();
}
Tag::Table(alignments) => {
self.flush_prose();
push_block_gap(&mut self.lines);
self.table.begin(alignments);
}
// Flush any pending cell content from the previous row
Tag::TableRow if self.table.has_cell() => self.table.end_cell(),
Tag::TableCell => self.table.begin_cell(),
Tag::CodeBlock(CodeBlockKind::Fenced(lang)) => {
// Flush any pending inline spans before entering code block
self.flush_prose();
push_block_gap(&mut self.lines);
self.fence.begin(Some(lang.to_string()));
}
Tag::Item => self.begin_item(),
Tag::CodeBlock(CodeBlockKind::Indented) => {
self.flush_prose();
push_block_gap(&mut self.lines);
self.fence.begin(None);
}
_ => {}
}
}
fn end(&mut self, tag: TagEnd) {
match tag {
TagEnd::Paragraph if !self.inline.line.is_empty() => self.flush_prose(),
TagEnd::BlockQuote(_) => {
if !self.inline.line.is_empty() {
self.flush_prose();
}
self.in_blockquote = false;
}
TagEnd::List(_) => self.list.end(),
TagEnd::Heading { .. } => {
// Flush pending inline spans before clearing heading state
self.flush_prose();
self.heading_level = None;
}
TagEnd::CodeBlock => {
self.lines.extend(self.fence.finish(self.theme, self.voice));
}
TagEnd::Strong | TagEnd::Emphasis | TagEnd::Strikethrough => {
self.inline.style_stack.pop();
}
TagEnd::Link => self.finish_link(),
TagEnd::Table => {
self.lines.extend(self.table.finish(self.theme, self.voice));
}
// pulldown-cmark puts header cells directly under TableHead (no TableRow wrapper).
TagEnd::TableHead if self.table.has_row() => self.table.end_head(),
// Buffer the completed body row
TagEnd::TableRow if self.table.has_row() => self.table.end_row(),
TagEnd::TableCell => self.table.end_cell(),
_ => {}
}
}
/// Opens a quote, writing out an alert's word on a line of its own.
fn begin_quote(&mut self, kind: Option<BlockQuoteKind>) {
let opens_an_item = self.list.item_just_started && !self.inline.line.is_empty();
if !self.list.item_just_started {
self.flush_prose();
}
push_block_gap(&mut self.lines);
self.in_blockquote = true;
// the item's bullet is already on the line, which is where the marker normally goes
if opens_an_item && kind.is_none() {
let style = build_quote_style(self.theme, self.voice);
self.inline.line.push(Span::styled("> ".to_string(), style));
}
// An alert carries its severity in the tag rather than in its prose, so dropping
// the kind renders `> [!CAUTION]` as an ordinary quote and loses the only thing
// that made it one. The word is written out — the color is the polish.
if let Some(kind) = kind {
self.lines.push(MarkdownLine::prose(Line::from(vec![
Span::styled("> ".to_string(), build_quote_style(self.theme, self.voice)),
Span::styled(
crate::glyphs::icon_label(alert_icon(kind).glyph(), alert_label(kind)),
build_alert_style(self.theme, self.voice, kind),
),
])));
self.alert_just_labeled = true;
}
}
/// Flushes what is pending, then starts the item's line with its number or bullet.
fn begin_item(&mut self) {
self.flush_prose();
let prefix = self.list.next_prefix();
self.quote_prefix();
self.inline.line.push(Span::styled(prefix, build_text_style(self.theme, self.voice)));
self.list.item_just_started = true;
}
/// The address follows the words, once, however many spans the words took — and not at all
/// when the words are the address.
fn finish_link(&mut self) {
if let Some(url) = self.inline.link_url.take() {
let repeats = url.trim_start_matches("mailto:") == self.inline.link_text.trim();
if !url.is_empty() && !repeats && !self.fence.active() && !self.table.active() {
self.inline.line.push(Span::styled(
format!(" ({url})"),
build_link_url_style(self.theme, self.voice),
));
}
}
}
fn code(&mut self, text: &str) {
if self.inline.link_url.is_some() {
self.inline.link_text.push_str(text);
}
let mut style = build_code_style(self.theme, self.voice);
if let Some(level) = self.heading_level {
style = build_heading_style(self.theme, level, self.voice);
}
self.quote_prefix();
// a table cell holds its code too, or the identifier leaks out as prose later
self.append_inline(Span::styled(text.to_string(), style), true);
}
fn text(&mut self, text: &str) {
// First text in a list item clears the "just started" flag
self.list.item_just_started = false;
// One-time blockquote prefix at start of line (before any styled spans)
self.quote_prefix();
let mut style =
build_style(&self.inline.style_stack, build_text_style(self.theme, self.voice));
if let Some(level) = self.heading_level {
style = build_heading_style(self.theme, level, self.voice);
}
if self.inline.link_url.is_some() {
style = build_link_style(self.theme, self.voice);
self.inline.link_text.push_str(text);
}
self.append_inline(Span::styled(text.to_string(), style), true);
}
/// The one-time `> ` that opens a line inside a quote.
fn quote_prefix(&mut self) {
if self.in_blockquote && self.inline.line.is_empty() {
let style = build_quote_style(self.theme, self.voice);
self.inline.line.push(Span::styled("> ".to_string(), style));
}
}
/// Routes inline content to where it belongs: a fence collects its text, a table cell its
/// words when `cells` says this kind of content goes there, and everything else the line.
fn append_inline(&mut self, span: Span<'static>, cells: bool) {
if self.fence.active() {
self.fence.push(span.content.to_string());
} else if cells && self.table.active() {
self.table.push_cell(&span.content);
} else {
self.inline.line.push(span);
}
}
/// Ends the pending inline run as a prose line, if there is one.
fn flush_prose(&mut self) {
if !self.inline.line.is_empty() {
let line = Line::from(std::mem::take(&mut self.inline.line));
self.lines.push(MarkdownLine::prose(line));
}
}
}

View File

@@ -0,0 +1,152 @@
//! Markdown lines — one laid-out row and what the transcript needs to know about it beyond its
//! text: its width class, a fence's rule, an image row, a table, a copy or open affordance.
use super::table::TableBlock;
use ratatui::style::Style;
use ratatui::text::{Line, Span};
/// Structural kind used by the conversation width policy.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MarkdownBlockKind {
/// Normal prose, headings, lists, quotes, and rules.
Prose,
/// Fenced code and tables which may use the wide canvas.
Wide,
}
/// One styled Markdown line with its structural layout kind.
#[derive(Debug, Clone)]
pub(crate) struct MarkdownLine {
/// Structural kind retained through layout.
pub(crate) kind: MarkdownBlockKind,
/// Styled terminal content.
pub(crate) line: Line<'static>,
/// When set, this line is a clickable "copy" affordance carrying its code block's source text.
pub(crate) code_copy: Option<String>,
/// When set, the line is pushed right until it ends at this column, clamped to the canvas.
///
/// Carried rather than padded at layout time because the column a line should end at is a
/// property of the block it belongs to — a code block's own widest row — while the canvas that
/// can overrule it is only known once the transcript is being drawn.
pub(crate) ends_at: Option<usize>,
/// When set, this line is one row of an inline image rather than text.
pub(crate) image: Option<ImageRow>,
/// When set, clicking this line opens that image in the desktop's image viewer.
///
/// The affordance a terminal that cannot draw images gets instead — the picture is still right
/// there on disk, so the honest answer is to hand it over rather than to approximate it.
pub(crate) opens_image: Option<crate::graphics::ImageKey>,
/// Whether a click on this line opens or closes the block it belongs to.
///
/// A handle, not the whole block: a card's header and the footer offering the expand are things
/// to click, while a card's *body* is text to select — collapsing the card out from under a
/// double-click is how you make a path in it impossible to grab.
pub(crate) expands: bool,
/// When set, this line is a code fence's frame rather than text; see [`FenceRule`].
pub(crate) fence_rule: Option<FenceRule>,
/// When set, the column this line's wrapped rows start at, whatever its kind.
///
/// For a line that knows where its own text begins, like a tool card's header, whose subject
/// sits after the tool's name: wrapped back to the margin, a long command or question runs
/// under the name and stops reading as one block.
pub(crate) hang: Option<usize>,
/// When set, this line is a whole table, laid out once the width it lands in is known; see
/// [`TableBlock`].
pub(crate) table: Option<std::sync::Arc<TableBlock>>,
}
/// A fenced code block's frame line: a rule, with labels sitting on its ends.
///
/// Expanded at wrap time rather than built here, for the same reason [`MarkdownLine::ends_at`] is
/// deferred: the rule runs the width of the block's own widest row, and only the canvas being drawn
/// into knows whether that width survives.
#[derive(Debug, Clone)]
pub(crate) struct FenceRule {
/// Spans that open the rule — the language label on a top rule, nothing on a bottom one.
pub(crate) lead: Vec<Span<'static>>,
/// Spans that close it — the copy affordance on a top rule.
pub(crate) tail: Vec<Span<'static>>,
/// The block's widest row: where the rule wants to stop, before the canvas clamps it.
pub(crate) ends_at: usize,
/// The rule glyphs' own style.
pub(crate) style: Style,
}
/// One row of an inline image: which image, how big it is, and which of its rows this is.
#[derive(Debug, Clone)]
pub(crate) struct ImageRow {
pub(crate) key: crate::graphics::ImageKey,
/// The size the whole image was laid out at.
pub(crate) fit: crate::graphics::Fit,
/// Which of the image's rows this line reserves.
pub(crate) row: u16,
}
impl MarkdownLine {
/// A line of `kind` with nothing else set: the one place every field gets its default, so a
/// field added later cannot be forgotten by one constructor and not another.
fn of(kind: MarkdownBlockKind, line: Line<'static>) -> Self {
Self {
kind,
line,
code_copy: None,
ends_at: None,
image: None,
opens_image: None,
expands: false,
fence_rule: None,
hang: None,
table: None,
}
}
/// Tags a styled line as readable prose.
pub(crate) fn prose(line: Line<'static>) -> Self {
Self::of(MarkdownBlockKind::Prose, line)
}
/// Tags a styled line as wide content.
pub(crate) fn wide(line: Line<'static>) -> Self {
Self::of(MarkdownBlockKind::Wide, line)
}
/// Reserves one blank wide row for a row of an inline image.
///
/// Blank rather than a placeholder glyph: the pixels are painted over it once the transcript
/// has rendered, and anything drawn here would show through an image with transparency in it.
pub(crate) fn image_row(image: ImageRow) -> Self {
Self { image: Some(image), ..Self::wide(Line::default()) }
}
/// The rule that opens a code block: the language on the left, the copy affordance on the
/// right, and the block's own width between them.
///
/// One line doing both jobs, so the copy caption cannot read as a stray word and the rule says
/// where the code begins. Clicking anywhere along the rule copies, which is what a block header
/// does everywhere else.
pub(crate) fn fence_top(rule: FenceRule, code: String) -> Self {
Self { code_copy: Some(code), fence_rule: Some(rule), ..Self::wide(Line::default()) }
}
/// The rule that closes a code block — no labels, and nothing to click.
pub(crate) fn fence_bottom(rule: FenceRule) -> Self {
Self { fence_rule: Some(rule), ..Self::wide(Line::default()) }
}
/// A whole table, as one line the transcript lays out at the width it is drawn in.
pub(crate) fn table(table: TableBlock) -> Self {
Self { table: Some(std::sync::Arc::new(table)), ..Self::wide(Line::default()) }
}
/// Marks this line as the handle a click uses to open or close its block.
pub(crate) fn expandable(mut self) -> Self {
self.expands = true;
self
}
/// Marks this line as the affordance that opens `key` outside the terminal.
pub(crate) fn opens_image(mut self, key: crate::graphics::ImageKey) -> Self {
self.opens_image = Some(key);
self
}
}

View File

@@ -0,0 +1,157 @@
//! A mixed-block document, pinned line for line in both voices.
//!
//! The parser's state machines (fences, lists, quotes, tables, inline runs) interleave in one walk,
//! so a restructure that moves a flush or a gap shows up here as a changed row before it shows up
//! anywhere a reader would notice.
use super::line::MarkdownBlockKind;
use super::voice::{build_code_style, build_heading_style, build_link_style};
use super::*;
use crate::theme::styles::ThemeStyles;
use pulldown_cmark::HeadingLevel;
use ratatui::style::Modifier;
use ratatui::text::Span;
const DOCUMENT: &str = "# Plan
Some **bold**, *italic*, `code` and a [link](https://example.com) here,
with a soft break. \nAnd a hard one.
1. First
2. Second
- nested *point*
- [ ] task
- > a quote opening an item
> A quote with `code`.
> `code` first in a quote
> [!WARNING]
> Mind the gap.
```rust
fn main() {}
```
indented code
<div>raw html</div>
| Name | Value |
|:-----|------:|
| `key` | 42 |
| [site](https://example.com) | x |
---
Trailing paragraph.
> - a list in a quote
after the list in a quote
> ```
> fenced in a quote
> ```
after the fence in a quote
";
fn styles() -> ThemeStyles {
let resolved = luxe_core::theme::ThemeRegistry::new().resolve("luxe").expect("a bundled theme");
ThemeStyles::from_resolved(&resolved, "luxe")
}
/// Each laid-out line as `kind width | text`, with a fence's rule and a table spelled out.
fn rows(lines: &[MarkdownLine]) -> Vec<String> {
// A hard break is a newline inside a span; spelled out, so one row stays one line here
let text = |spans: &[Span]| {
spans.iter().map(|span| span.content.replace('\n', "⏎")).collect::<String>()
};
lines
.iter()
.map(|line| {
let kind = match line.kind {
MarkdownBlockKind::Prose => "P",
MarkdownBlockKind::Wide => "W",
};
if let Some(rule) = &line.fence_rule {
return format!(
"{kind} rule {} | {} … {}",
rule.ends_at,
text(&rule.lead),
text(&rule.tail)
);
}
if let Some(table) = &line.table {
let drawn = table.lines_at(usize::MAX);
let body = drawn.iter().map(|row| text(&row.spans)).collect::<Vec<_>>().join(" / ");
return format!("{kind} table | {body}");
}
format!("{kind} {} | {}", line.line.width(), text(&line.line.spans))
})
.collect()
}
fn digest(lines: &[MarkdownLine]) -> u64 {
let mut hash: u64 = 0xcbf2_9ce4_8422_2325;
for byte in format!("{lines:?}").bytes() {
hash ^= u64::from(byte);
hash = hash.wrapping_mul(0x0100_0000_01b3);
}
hash
}
/// The mixed document's rows, widths and every span's style, in both voices, as recorded.
///
/// The break this catches: a block gap, a list prefix, a quote marker, a fence rule or a table
/// cell moving, or a span changing style, while the parser is restructured.
#[test]
fn a_mixed_document_lays_out_as_recorded_in_both_voices() {
crate::glyphs::set_tier(crate::glyphs::GlyphTier::Nerd);
let theme = styles();
let answer = layout_markdown_in(DOCUMENT, &theme, MarkdownVoice::Answer);
let reasoning = layout_markdown_in(DOCUMENT, &theme, MarkdownVoice::Reasoning);
let recorded = include_str!("mixed_tests.txt");
let actual = format!(
"{}\n--- reasoning\n{}\nanswer {:016x} reasoning {:016x}\n",
rows(&answer).join("\n"),
rows(&reasoning).join("\n"),
digest(&answer),
digest(&reasoning),
);
if let Ok(path) = std::env::var("LUXE_MARKDOWN_PINS") {
std::fs::write(path, &actual).expect("write the record");
}
assert_eq!(actual, recorded);
}
/// The two voices differ in style, not in shape: same rows, and the heading, inline code and link
/// each take their own voice's ink.
#[test]
fn the_voices_share_a_shape_and_differ_in_ink() {
let theme = styles();
let answer = layout_markdown_in(DOCUMENT, &theme, MarkdownVoice::Answer);
let reasoning = layout_markdown_in(DOCUMENT, &theme, MarkdownVoice::Reasoning);
assert_eq!(answer.len(), reasoning.len());
let span = |lines: &[MarkdownLine], needle: &str| {
lines
.iter()
.flat_map(|line| line.line.spans.iter())
.find(|span| span.content.contains(needle))
.map(|span| span.style)
.unwrap_or_else(|| panic!("no span carrying {needle:?}"))
};
let heading = |voice| build_heading_style(&theme, HeadingLevel::H1, voice);
assert_eq!(span(&answer, "Plan"), heading(MarkdownVoice::Answer));
assert_eq!(span(&reasoning, "Plan"), heading(MarkdownVoice::Reasoning));
assert_ne!(heading(MarkdownVoice::Answer), heading(MarkdownVoice::Reasoning));
assert_eq!(span(&answer, "code"), build_code_style(&theme, MarkdownVoice::Answer));
assert_eq!(span(&reasoning, "code"), build_code_style(&theme, MarkdownVoice::Reasoning));
assert_eq!(span(&answer, "link"), build_link_style(&theme, MarkdownVoice::Answer));
assert_eq!(span(&reasoning, "link"), build_link_style(&theme, MarkdownVoice::Reasoning));
assert!(span(&reasoning, "Trailing").add_modifier.contains(Modifier::ITALIC));
assert!(!span(&answer, "Trailing").add_modifier.contains(Modifier::ITALIC));
}

View File

@@ -0,0 +1,90 @@
P 4 | Plan
P 0 |
P 97 | Some bold, italic, code and a link (https://example.com) here, with a soft break.⏎And a hard one.
P 0 |
P 8 | 1. First
P 9 | 2. Second
P 16 | • nested point
P 0 |
P 12 | • [ ] task
P 0 |
P 27 | • > a quote opening an item
P 0 |
P 20 | > A quote with code.
P 0 |
P 23 | > code first in a quote
P 0 |
P 11 | > 󰀦 Warning
P 15 | > Mind the gap.
P 0 |
W rule 22 |  rust …  copy
W 12 | fn main() {}
W rule 22 | …
P 0 |
W rule 13 | …  copy
W 13 | indented code
W rule 13 | …
P 20 | <div>raw html</div>⏎
P 0 |
W table | ┌──────┬───────┐ / │ Name │ Value │ / ├──────┼───────┤ / │ key │ 42 │ / │ site │ x │ / └──────┴───────┘
P 0 |
P 44 | ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
P 0 |
P 19 | Trailing paragraph.
P 0 |
P 21 | > • a list in a quote
P 0 |
P 25 | after the list in a quote
P 0 |
W rule 17 | …  copy
W 17 | fenced in a quote
W rule 17 | …
P 2 | >
P 0 |
P 26 | after the fence in a quote
--- reasoning
P 4 | Plan
P 0 |
P 97 | Some bold, italic, code and a link (https://example.com) here,⏎with a soft break.⏎And a hard one.
P 0 |
P 8 | 1. First
P 9 | 2. Second
P 16 | • nested point
P 0 |
P 12 | • [ ] task
P 0 |
P 27 | • > a quote opening an item
P 0 |
P 20 | > A quote with code.
P 0 |
P 23 | > code first in a quote
P 0 |
P 11 | > 󰀦 Warning
P 15 | > Mind the gap.
P 0 |
W rule 22 |  rust …  copy
W 12 | fn main() {}
W rule 22 | …
P 0 |
W rule 13 | …  copy
W 13 | indented code
W rule 13 | …
P 20 | <div>raw html</div>⏎
P 0 |
W table | ┌──────┬───────┐ / │ Name │ Value │ / ├──────┼───────┤ / │ key │ 42 │ / │ site │ x │ / └──────┴───────┘
P 0 |
P 44 | ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━
P 0 |
P 19 | Trailing paragraph.
P 0 |
P 21 | > • a list in a quote
P 0 |
P 25 | after the list in a quote
P 0 |
W rule 17 | …  copy
W 17 | fenced in a quote
W rule 17 | …
P 2 | >
P 0 |
P 26 | after the fence in a quote
answer 93cc658e386d2a8e reasoning d8ea1ef67f372c7e

View File

@@ -0,0 +1,438 @@
//! Markdown tables — a box-drawn grid laid out for the width it is drawn at.
//!
//! A table is built once, when the markdown is walked, and laid out every time the canvas it lands
//! in is measured, the same way a fence's frame is ([`super::FenceRule`]). Laying it out up front
//! at its natural width would break it: a grid wider than the column handed to the transcript's
//! word wrapper splits each row across two lines and scatters the borders, the header and every
//! cell. Opening the preview beside the conversation is enough to do it.
//!
//! So the width is the table's own problem. Columns shrink toward their longest word and cells
//! wrap inside them, row separators appear once a row needs more than one line, and a table too
//! narrow for even that is drawn as records — one `Header: value` line per cell — rather than a
//! grid nobody can read.
use ratatui::style::{Modifier, Style};
use ratatui::text::{Line, Span};
use unicode_width::{UnicodeWidthChar, UnicodeWidthStr};
/// Widest a column asks to be once the table has to shrink, so one long cell does not keep the rest
/// of the grid narrow.
const MAX_COLUMN_WIDTH: usize = 48;
/// Narrowest a column is squeezed to while the grid still fits.
const MIN_COLUMN_WIDTH: usize = 3;
/// Longest word a column tries to keep whole when it has to shrink. Past this a word is split
/// anyway: a URL in one cell must not starve every other column.
const MAX_KEPT_WORD: usize = 16;
/// Cells a column needs for its content to be readable, below which the grid gives way to records.
const RECORD_FALLBACK_WIDTH: usize = 6;
/// Column alignment, as pulldown-cmark reports it.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum Alignment {
Left,
Center,
Right,
}
impl From<pulldown_cmark::Alignment> for Alignment {
fn from(alignment: pulldown_cmark::Alignment) -> Self {
match alignment {
pulldown_cmark::Alignment::Center => Self::Center,
pulldown_cmark::Alignment::Right => Self::Right,
pulldown_cmark::Alignment::None | pulldown_cmark::Alignment::Left => Self::Left,
}
}
}
/// A whole table: its cells, how each column aligns, and the styles it is drawn in.
#[derive(Debug, Clone)]
pub(crate) struct TableBlock {
header: Vec<String>,
body: Vec<Vec<String>>,
alignments: Vec<Alignment>,
border: Style,
cell: Style,
}
impl TableBlock {
/// A table of `header` over `body`.
///
/// Args: `(header, body, alignments, border style, cell style)`.
pub(crate) fn new(
header: Vec<String>,
body: Vec<Vec<String>>,
alignments: &[pulldown_cmark::Alignment],
border: Style,
cell: Style,
) -> Option<Self> {
let trim = |cells: Vec<String>| -> Vec<String> {
cells.into_iter().map(|cell| cell.trim().to_string()).collect()
};
let table = Self {
header: trim(header),
body: body.into_iter().map(trim).collect(),
alignments: alignments.iter().copied().map(Alignment::from).collect(),
border,
cell,
};
(table.columns() > 0).then_some(table)
}
fn columns(&self) -> usize {
self.header
.len()
.max(self.body.iter().map(Vec::len).max().unwrap_or(0))
.max(self.alignments.len())
}
fn rows(&self) -> impl Iterator<Item = &Vec<String>> {
std::iter::once(&self.header).filter(|header| !header.is_empty()).chain(&self.body)
}
fn cell_text(cells: &[String], column: usize) -> &str {
cells.get(column).map_or("", String::as_str)
}
/// The table laid out to fit `width` cells: a grid when one fits, records when none does.
pub(crate) fn lines_at(&self, width: usize) -> Vec<Line<'static>> {
match self.column_widths(width) {
Some(widths) => self.grid(&widths),
None => self.records(width.max(1)),
}
}
/// Each column's width in a grid at most `width` cells wide, or `None` when no grid fits.
///
/// Every column first asks for all of its content, which is the grid whenever it fits. Short of
/// that, a column asks for at most [`MAX_COLUMN_WIDTH`]. When those do not fit either,
/// each keeps its longest word (up to [`MAX_KEPT_WORD`]) and the room left goes to the columns
/// still short of what they want ([`share`]). When even the words do not fit, the widest
/// columns give way first ([`fit`]), and with less than [`RECORD_FALLBACK_WIDTH`] a column the
/// grid is given up.
fn column_widths(&self, width: usize) -> Option<Vec<usize>> {
let columns = self.columns();
// `│` before each column and after the last, and a space either side of every cell
let budget = width.checked_sub(3 * columns + 1)?;
let natural: Vec<usize> = (0..columns)
.map(|column| {
self.rows()
.map(|row| UnicodeWidthStr::width(Self::cell_text(row, column)))
.max()
.unwrap_or(0)
.max(MIN_COLUMN_WIDTH)
})
.collect();
if natural.iter().sum::<usize>() <= budget {
return Some(natural);
}
let wants: Vec<usize> = natural.iter().map(|&width| width.min(MAX_COLUMN_WIDTH)).collect();
if wants.iter().sum::<usize>() <= budget {
return Some(wants);
}
let words: Vec<usize> = (0..columns)
.map(|column| {
let longest = self
.rows()
.flat_map(|row| Self::cell_text(row, column).split_whitespace())
.map(UnicodeWidthStr::width)
.max()
.unwrap_or(0);
longest.clamp(MIN_COLUMN_WIDTH, MAX_KEPT_WORD).min(wants[column])
})
.collect();
let floor: usize = words.iter().sum();
if floor <= budget {
return Some(share(&words, &wants, budget - floor));
}
// Not even every column's longest word fits: take from the widest until it does, which
// splits the fewest words, down to a floor below which a grid is not worth drawing
if budget < columns * RECORD_FALLBACK_WIDTH {
return None;
}
Some(fit(words, budget))
}
/// The grid: borders, the bold header, and each row, wrapped inside its columns.
fn grid(&self, widths: &[usize]) -> Vec<Line<'static>> {
let wrapped_body: Vec<Vec<Vec<String>>> =
self.body.iter().map(|row| self.wrap_row(row, widths)).collect();
// Rules between rows only once a row takes more than one line; a one-line row is its own
// separator, and a ruled grid of short rows is twice as tall for nothing
let tall = wrapped_body.iter().any(|row| row.len() > 1);
let mut lines = vec![self.rule(widths, '┌', '┬', '┐')];
if !self.header.is_empty() {
let header = self.wrap_row(&self.header, widths);
let style = self.cell.add_modifier(Modifier::BOLD);
lines.extend(header.iter().map(|line| self.content_line(line, widths, style)));
lines.push(self.rule(widths, '├', '┼', '┤'));
}
for (index, row) in wrapped_body.iter().enumerate() {
if tall && index > 0 {
lines.push(self.rule(widths, '├', '┼', '┤'));
}
lines.extend(row.iter().map(|line| self.content_line(line, widths, self.cell)));
}
lines.push(self.rule(widths, '└', '┴', '┘'));
lines
}
/// One row's cells wrapped to their columns, as the lines it takes: each line holds every
/// column's text for that line, empty where a shorter cell has run out.
fn wrap_row(&self, cells: &[String], widths: &[usize]) -> Vec<Vec<String>> {
let wrapped: Vec<Vec<String>> = widths
.iter()
.enumerate()
.map(|(column, &width)| wrap(Self::cell_text(cells, column), width))
.collect();
let height = wrapped.iter().map(Vec::len).max().unwrap_or(1).max(1);
(0..height)
.map(|line| {
wrapped.iter().map(|cell| cell.get(line).cloned().unwrap_or_default()).collect()
})
.collect()
}
fn content_line(&self, cells: &[String], widths: &[usize], style: Style) -> Line<'static> {
let mut spans = Vec::with_capacity(widths.len() * 2 + 1);
spans.push(Span::styled("│", self.border));
for (column, &width) in widths.iter().enumerate() {
let alignment = self.alignments.get(column).copied().unwrap_or(Alignment::Left);
let text = cells.get(column).map_or("", String::as_str);
spans.push(Span::styled(format!(" {} ", pad(text, width, alignment)), style));
spans.push(Span::styled("│", self.border));
}
Line::from(spans)
}
fn rule(&self, widths: &[usize], left: char, middle: char, right: char) -> Line<'static> {
let mut rule = String::new();
rule.push(left);
for (index, width) in widths.iter().enumerate() {
if index > 0 {
rule.push(middle);
}
rule.extend(std::iter::repeat_n('─', width + 2));
}
rule.push(right);
Line::from(Span::styled(rule, self.border))
}
/// The table as records, for a column too narrow for any grid: each row's cells as
/// `Header: value`, the value wrapped under itself, a rule between rows.
fn records(&self, width: usize) -> Vec<Line<'static>> {
let label_style = self.cell.add_modifier(Modifier::BOLD);
let mut lines = Vec::new();
for (index, row) in self.body.iter().enumerate() {
if index > 0 {
lines.push(Line::from(Span::styled("─".repeat(width), self.border)));
}
for column in 0..self.columns() {
let label = Self::cell_text(&self.header, column);
let value = Self::cell_text(row, column);
let lead = match label.is_empty() {
true => String::new(),
false => format!("{label}: "),
};
let lead_width = UnicodeWidthStr::width(lead.as_str());
let indented = |text: String, indent: usize| {
Line::from(vec![Span::raw(" ".repeat(indent)), Span::styled(text, self.cell)])
};
if lead_width * 2 <= width {
let mut value_lines = wrap(value, width - lead_width).into_iter();
let head = value_lines.next().unwrap_or_default();
lines.push(Line::from(vec![
Span::styled(lead, label_style),
Span::styled(head, self.cell),
]));
lines.extend(value_lines.map(|line| indented(line, lead_width)));
} else {
// A label wider than half the row takes a line of its own, the value under it
let label_lines = wrap(lead.trim_end(), width);
lines.extend(
label_lines
.into_iter()
.map(|line| Line::from(Span::styled(line, label_style))),
);
let indent = usize::from(width > 2) * 2;
lines.extend(
wrap(value, width - indent)
.into_iter()
.filter(|line| !line.is_empty())
.map(|line| indented(line, indent)),
);
}
}
}
lines
}
}
/// Spreads `spare` cells over columns already at `floor`, one at a time, each to the column still
/// furthest from what it `wants`; a column never gets more than it wants.
///
/// Filling from the most wanting evens out what each column is short of, so a column of long
/// sentences grows before a column of short labels, and both stop at what their content needs.
fn share(floor: &[usize], wants: &[usize], spare: usize) -> Vec<usize> {
let mut widths = floor.to_vec();
for _ in 0..spare {
let neediest = widths
.iter()
.zip(wants)
.enumerate()
.filter(|(_, (have, want))| have < want)
.max_by_key(|(index, (have, want))| (*want - *have, std::cmp::Reverse(*index)));
let Some((column, _)) = neediest else {
break;
};
widths[column] += 1;
}
widths
}
/// Trims `widths` until their sum is at most `budget`, taking from the widest first.
fn fit(mut widths: Vec<usize>, budget: usize) -> Vec<usize> {
while widths.iter().sum::<usize>() > budget {
let Some(widest) = widths.iter_mut().filter(|width| **width > 1).max_by_key(|w| **w) else {
break;
};
*widest -= 1;
}
widths
}
/// `text` broken into lines of at most `width` cells: at spaces where it can be, through a word
/// where one is longer than the line.
fn wrap(text: &str, width: usize) -> Vec<String> {
let width = width.max(1);
let mut lines = Vec::new();
let mut line = String::new();
let mut used = 0;
for word in text.split_whitespace() {
let word_width = UnicodeWidthStr::width(word);
let gap = usize::from(!line.is_empty());
if used + gap + word_width <= width {
if gap == 1 {
line.push(' ');
}
line.push_str(word);
used += gap + word_width;
continue;
}
if !line.is_empty() {
lines.push(std::mem::take(&mut line));
used = 0;
}
// Too long for any line: split it at the width, carrying the tail on
for character in word.chars() {
let cells = character.width().unwrap_or(0);
if used + cells > width && !line.is_empty() {
lines.push(std::mem::take(&mut line));
used = 0;
}
line.push(character);
used += cells;
}
}
if !line.is_empty() || lines.is_empty() {
lines.push(line);
}
lines
}
/// `text`, already no wider than `width`, padded to exactly `width` cells.
fn pad(text: &str, width: usize, alignment: Alignment) -> String {
let room = width.saturating_sub(UnicodeWidthStr::width(text));
match alignment {
Alignment::Left => format!("{text}{}", " ".repeat(room)),
Alignment::Right => format!("{}{text}", " ".repeat(room)),
Alignment::Center => {
let left = room / 2;
format!("{}{text}{}", " ".repeat(left), " ".repeat(room - left))
}
}
}
/// A table being collected as the walk passes over it: its alignments, the header, the body
/// rows, and the row and cell in progress.
#[derive(Default)]
pub(super) struct TableBuilder {
active: bool,
alignments: Vec<pulldown_cmark::Alignment>,
cell: String,
row: Vec<String>,
header: Vec<String>,
body: Vec<Vec<String>>,
}
impl TableBuilder {
pub(super) fn begin(&mut self, alignments: Vec<pulldown_cmark::Alignment>) {
self.alignments = alignments;
self.active = true;
self.header.clear();
self.body.clear();
}
/// Whether the walk is inside a table, where text and code go to the cell in progress.
pub(super) fn active(&self) -> bool {
self.active
}
pub(super) fn has_cell(&self) -> bool {
!self.cell.is_empty()
}
pub(super) fn has_row(&self) -> bool {
!self.row.is_empty()
}
pub(super) fn begin_cell(&mut self) {
self.cell.clear();
}
pub(super) fn push_cell(&mut self, text: &str) {
self.cell.push_str(text);
}
pub(super) fn end_cell(&mut self) {
self.row.push(std::mem::take(&mut self.cell));
}
pub(super) fn end_head(&mut self) {
self.header = std::mem::take(&mut self.row);
}
pub(super) fn end_row(&mut self) {
self.body.push(std::mem::take(&mut self.row));
}
/// Closes the table, buffering any trailing cell or row, and emits it whole so column widths
/// and borders can be computed across every row.
pub(super) fn finish(
&mut self,
theme: &crate::theme::styles::ThemeStyles,
voice: super::MarkdownVoice,
) -> Option<super::MarkdownLine> {
if !self.cell.is_empty() {
self.end_cell();
}
if !self.row.is_empty() {
self.end_row();
}
let table = TableBlock::new(
std::mem::take(&mut self.header),
std::mem::take(&mut self.body),
&self.alignments,
super::voice::build_table_border_style(theme, voice),
super::voice::build_table_style(theme, voice),
);
self.active = false;
self.alignments.clear();
table.map(super::MarkdownLine::table)
}
}
#[cfg(test)]
mod tests;

View File

@@ -0,0 +1,192 @@
use super::*;
fn table(header: &[&str], body: &[&[&str]]) -> TableBlock {
let cells = |row: &[&str]| row.iter().map(|cell| cell.to_string()).collect::<Vec<_>>();
TableBlock::new(
cells(header),
body.iter().map(|row| cells(row)).collect(),
&[],
Style::default(),
Style::default(),
)
.expect("columns")
}
fn text(lines: &[Line<'static>]) -> Vec<String> {
lines.iter().map(Line::to_string).collect()
}
fn widths(lines: &[Line<'static>]) -> Vec<usize> {
lines.iter().map(Line::width).collect()
}
const SAMPLE: [[&str; 3]; 3] = [
["Item", "Status", "Notes"],
["Notifications", "done", "permission, question and review prompts notify"],
["Peek width", "planned", "cap the diff at code width so the transcript keeps room"],
];
fn source() -> Vec<String> {
SAMPLE.iter().map(|row| row.join(" ")).collect()
}
/// Every letter and digit in `rows`, sorted: the content, whatever the layout did to it.
fn letters(rows: &[String]) -> Vec<char> {
let mut letters: Vec<char> =
rows.iter().flat_map(|row| row.chars()).filter(|c| c.is_alphanumeric()).collect();
letters.sort_unstable();
letters
}
fn sample() -> TableBlock {
table(
&["Item", "Status", "Notes"],
&[
&["Notifications", "done", "permission, question and review prompts notify"],
&["Peek width", "planned", "cap the diff at code width so the transcript keeps room"],
],
)
}
/// With room, the grid is what it always was: one line a row, no rules between rows.
#[test]
fn a_table_with_room_keeps_its_natural_grid() {
let lines = sample().lines_at(200);
let rows = text(&lines);
assert_eq!(rows.len(), 6, "{rows:#?}");
assert!(rows[1].contains("Item") && rows[3].contains("Notifications"));
let first = lines[0].width();
assert!(widths(&lines).iter().all(|&width| width == first), "{rows:#?}");
}
/// The bug this exists for: narrower than its natural width, every line of the table still fits
/// and every border still lines up, the cells wrapping inside their own columns.
#[test]
fn a_narrow_table_wraps_inside_its_columns_and_stays_a_grid() {
for width in [40usize, 56, 72, 90] {
let lines = sample().lines_at(width);
let rows = text(&lines);
let first = lines[0].width();
assert!(first <= width, "{width}: {rows:#?}");
assert!(widths(&lines).iter().all(|&w| w == first), "{width}: aligned {rows:#?}");
assert!(rows.iter().all(|row| row.starts_with(['┌', '│', '├', '└'])), "{rows:#?}");
assert_eq!(letters(&rows), letters(&source()), "{width}: nothing is cut {rows:#?}");
}
}
/// Once a row takes more than one line, rules between rows say where one ends.
#[test]
fn wrapped_rows_are_ruled_apart() {
let rows = text(&sample().lines_at(50));
let separators = rows.iter().filter(|row| row.starts_with('├')).count();
assert_eq!(separators, 2, "under the header, and between the two rows: {rows:#?}");
}
/// A column too narrow for any grid gives the table up for records, still nothing cut.
#[test]
fn too_narrow_for_a_grid_reads_as_records() {
let rows = text(&sample().lines_at(20));
assert!(rows.iter().all(|row| UnicodeWidthStr::width(row.as_str()) <= 20), "{rows:#?}");
assert!(rows[0].starts_with("Item: Notifications"), "{rows:#?}");
assert!(rows.iter().any(|row| row.starts_with("Status: done")));
assert!(rows.iter().any(|row| row.starts_with('─')), "rows ruled apart: {rows:#?}");
// Each record names its header again, so that is the content to account for
let records: Vec<String> = SAMPLE[1..]
.iter()
.flat_map(|row| SAMPLE[0].iter().zip(row).map(|(label, value)| format!("{label}{value}")))
.collect();
assert_eq!(letters(&rows), letters(&records), "{rows:#?}");
}
#[test]
fn a_word_longer_than_its_column_is_split_not_dropped() {
assert_eq!(wrap("abcdefghij", 4), ["abcd", "efgh", "ij"]);
assert_eq!(wrap("a bb ccc", 4), ["a bb", "ccc"]);
assert_eq!(wrap("", 4), [""]);
}
#[test]
fn alignment_pads_each_line() {
assert_eq!(pad("ab", 5, Alignment::Right), " ab");
assert_eq!(pad("ab", 5, Alignment::Center), " ab ");
assert_eq!(pad("ab", 5, Alignment::Left), "ab ");
assert_eq!(Alignment::from(pulldown_cmark::Alignment::Right), Alignment::Right);
assert_eq!(Alignment::from(pulldown_cmark::Alignment::Center), Alignment::Center);
assert_eq!(Alignment::from(pulldown_cmark::Alignment::None), Alignment::Left);
}
/// The room left after every column's word goes to whoever is shortest of what they want, and
/// nobody gets more than they asked for.
#[test]
fn spare_room_goes_where_it_is_wanted() {
assert_eq!(share(&[3, 3], &[10, 3], 4), [7, 3]);
assert_eq!(share(&[3, 3], &[5, 5], 100), [5, 5], "never past what is wanted");
assert_eq!(share(&[4, 4, 4], &[20, 10, 4], 9), [13, 4, 4], "the neediest first");
assert_eq!(share(&[4, 4, 4], &[20, 10, 4], 18), [18, 8, 4], "until the shortfalls even out");
assert_eq!(share(&[4, 4], &[9, 9], 3), [6, 5], "a tie goes to the first");
}
fn widths_of(table: &TableBlock, width: usize) -> Option<Vec<usize>> {
table.column_widths(width)
}
/// Short of every column's longest word, the columns shrink together, each in proportion to its
/// word; below six cells a column, the grid is given up for records.
#[test]
fn too_narrow_for_every_word_the_columns_shrink_together() {
let long = table(
&["Identifier", "Kind", "Description"],
&[&["abcdefghijklmnopqrst", "status", "verylongwordhere"]],
);
// Words 16 (capped), 6 and 16: 38 cells, against a budget of 30
assert_eq!(widths_of(&long, 30 + 10), Some(vec![12, 6, 12]));
assert_eq!(widths_of(&long, 18 + 10), Some(vec![6, 6, 6]), "the narrowest grid there is");
// The widest gives way first, so two columns keep their words whole and one splits
let uneven = table(&["a", "b", "c"], &[&["abcdefghijklmnopqrst", "abcdefgh", "abcdefgh"]]);
assert_eq!(widths_of(&uneven, 24 + 10), Some(vec![8, 8, 8]));
assert_eq!(widths_of(&long, 17 + 10), None, "one cell short: records");
let rows = text(&long.lines_at(28));
let first = long.lines_at(28)[0].width();
assert_eq!(first, 28, "the grid fills the width exactly: {rows:#?}");
}
/// With every word in, the room left over grows the columns that want it.
#[test]
fn with_every_word_in_the_rest_goes_to_who_wants_it() {
let wide = table(&["Name", "Notes"], &[&["alpha", &"word ".repeat(20)]]);
// Words 5 and 4; wants 5 and 48; budget 40 leaves 31 to share, all of it wanted by Notes
assert_eq!(widths_of(&wide, 40 + 7), Some(vec![5, 35]));
}
/// A record whose header is wider than half the row puts its value under it, indented.
#[test]
fn a_long_header_puts_its_record_value_underneath() {
let narrow =
table(&["A rather long header", "Status", "B"], &[&["value here and more", "", "x"]]);
assert!(widths_of(&narrow, 12).is_none(), "too narrow for a grid");
let rows = text(&narrow.lines_at(12));
assert_eq!(
rows,
["A rather", "long header:", " value here", " and more", "Status:", "B: x"],
"an empty value adds no blank line"
);
// So narrow there is no room for an indent, the value takes the whole row
let rows = text(&table(&["Header", "B"], &[&["ab", "c"]]).lines_at(2));
assert!(rows.contains(&"ab".to_string()), "{rows:#?}");
}
#[test]
fn trimming_never_takes_a_column_below_one_cell() {
assert_eq!(fit(vec![1, 1], 1), [1, 1]);
assert_eq!(fit(vec![9, 4, 9], 18), [7, 4, 7]);
}
/// The rules between rows sit between rows: not doubled under the header, not missing below.
#[test]
fn a_rule_separates_each_pair_of_wrapped_rows() {
let rows = text(&sample().lines_at(50));
let peek = rows.iter().position(|row| row.contains("Peek width")).expect("the row");
assert!(rows[peek - 1].starts_with('├'), "{rows:#?}");
let header_rule = rows.iter().position(|row| row.starts_with('├')).expect("a rule");
assert!(rows[header_rule + 1].starts_with('│'), "one rule under the header: {rows:#?}");
}

View File

@@ -0,0 +1,509 @@
use super::fence::fence_language;
use super::*;
use crate::theme::styles::ThemeStyles;
use luxe_core::theme::{Theme as CoreTheme, ThemeRegistry};
use ratatui::style::Modifier;
use ratatui::text::Line;
use std::collections::HashMap;
/// A fence's rule announces the language, normalized, and says nothing where there is nothing
/// to say. `text` is not a language, it is a way of writing "this is a code block".
#[test]
fn a_fence_names_its_language_or_names_nothing() {
assert_eq!(fence_language(Some("rust")).as_deref(), Some("rust"));
assert_eq!(fence_language(Some(" Rust ")).as_deref(), Some("rust"), "hand-written");
assert_eq!(fence_language(Some("rust,ignore")).as_deref(), Some("rust"), "rustdoc");
assert_eq!(fence_language(Some("rust no_run")).as_deref(), Some("rust"), "mdBook");
assert_eq!(fence_language(Some("rust,ignore")).as_deref(), Some("rust"));
for empty in ["", " ", "text", "TEXT", "plain", "plaintext", "txt"] {
assert_eq!(fence_language(Some(empty)), None, "{empty:?} names no language");
}
assert_eq!(fence_language(None), None);
}
/// Helper: convert a CoreTheme to ThemeStyles for testing.
fn theme_to_styles(theme: &CoreTheme) -> ThemeStyles {
let _registry = ThemeRegistry::new();
let resolved: HashMap<String, luxe_core::theme::ColorValue> = theme.resolve_aliases();
ThemeStyles::from_resolved(&resolved, &theme.name)
}
#[test]
fn test_bold_and_code() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "**bold** and `code`";
let lines = render_markdown(input, &theme);
assert!(!lines.is_empty(), "should produce at least one line");
// Should have at least one span with BOLD modifier
let has_bold = lines.iter().any(|line| {
line.spans.iter().any(|span| span.style.add_modifier(Modifier::BOLD) == span.style)
});
assert!(has_bold, "expected BOLD modifier on some span");
// Inline code should be rendered (text "code" should appear)
let has_code = lines.iter().any(|line| line.spans.iter().any(|span| span.content == "code"));
assert!(has_code, "expected inline code 'code' to be rendered");
}
#[test]
fn test_heading() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "# Heading\nSome text";
let lines = render_markdown(input, &theme);
assert!(lines.len() >= 2, "heading + text should produce at least 2 lines");
// Heading text should have BOLD modifier (from md_heading token)
let heading_line = &lines[0];
let has_bold =
heading_line.spans.iter().any(|span| span.style.add_modifier(Modifier::BOLD) == span.style);
assert!(has_bold, "heading text should have BOLD modifier from md_heading token");
}
#[test]
fn test_heading_no_leak() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "# Heading\n\nSome text";
let lines = render_markdown(input, &theme);
assert!(lines.len() >= 2, "heading + blank line + text should produce at least 2 lines");
// Body text must NOT carry the heading BOLD style
let body = lines.last().unwrap();
let body_bold = body.spans.iter().any(|s| s.style.add_modifier(Modifier::BOLD) == s.style);
assert!(!body_bold, "heading style leaked into body text");
}
#[test]
fn test_unordered_list() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "- item 1\n- item 2\n- item 3";
let lines = render_markdown(input, &theme);
assert_eq!(lines.len(), 3, "should produce 3 list items");
// Each line should start with a bullet prefix
for (i, line) in lines.iter().enumerate() {
let content = line.spans.iter().map(|s| s.content.as_ref()).collect::<String>();
assert!(content.starts_with("• "), "line {} should start with bullet: {:?}", i, content);
}
}
#[test]
fn test_nested_list() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "- item a\n - nested b\n - nested c";
let lines = render_markdown(input, &theme);
assert_eq!(lines.len(), 3, "should produce 3 list items");
// Top-level item: no indent
let content0 = lines[0].spans.iter().map(|s| s.content.as_ref()).collect::<String>();
assert_eq!(content0, "• item a", "top-level should have no indent");
// Nested items: 2-space indent + bullet
for i in [1, 2] {
let content = lines[i].spans.iter().map(|s| s.content.as_ref()).collect::<String>();
assert!(
content.starts_with(" • "),
"line {} should have 2-space indent + bullet: {:?}",
i,
content
);
}
}
#[test]
fn test_ordered_list() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
// Ordered list: 1., 2., 3.
let input = "1. first\n2. second\n3. third";
let lines = render_markdown(input, &theme);
assert_eq!(lines.len(), 3, "should produce 3 list items");
// Each line should start with a numbered prefix
for (i, line) in lines.iter().enumerate() {
let content = line.spans.iter().map(|s| s.content.as_ref()).collect::<String>();
assert!(
content.starts_with(&format!("{}. ", i + 1)),
"line {} should start with numbered prefix: {:?}",
i,
content
);
}
}
#[test]
fn test_blockquote() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
// Blockquote (pulldown-cmark treats "\n> " as SoftBreak within one Paragraph)
let input = "> This is a quote\n> with multiple lines";
let lines = render_markdown(input, &theme);
assert_eq!(lines.len(), 1, "should produce 1 quoted line (SoftBreak -> space)");
// Line should start with "> " prefix with md_quote styling (non-default fg)
let spans = &lines[0].spans;
assert!(spans.len() >= 2, "line should have prefix span + text span: {:?}", spans);
assert_eq!(spans[0].content.as_ref(), "> ", "first span is the prefix");
let quote_fg = spans[0].style.fg;
assert!(quote_fg.is_some(), "prefix span should carry md_quote fg (not default)");
// Body text after prefix
let body: String = spans.iter().skip(1).map(|s| s.content.as_ref()).collect();
assert_eq!(body, "This is a quote with multiple lines");
}
/// A quote that opens with a list, and a list item that opens with a quote, each keep the quote's
/// `> ` marker.
///
/// The break this catches: the marker is written before a line's first text, and an item's bullet
/// had already made the line non-empty by then, so the quote read as plain list text.
#[test]
fn a_quote_and_a_list_keep_the_quote_marker_when_one_opens_the_other() {
let theme = theme_to_styles(&luxe_core::theme::builtin_themes()[0].clone());
let text = |input: &str| -> Vec<String> {
render_markdown(input, &theme)
.iter()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect::<String>())
.filter(|row| !row.is_empty())
.collect()
};
assert_eq!(text("> - one\n> - two"), ["> • one", "> • two"], "a list in a quote");
assert_eq!(text("- > quoted"), ["• > quoted"], "a quote in an item");
assert_eq!(text("> 1. first"), ["> 1. first"], "an ordered list in a quote");
}
/// An alert carries its severity in a tag rather than in its prose, so the tag has to become
/// something the reader sees. It becomes the word: the mark beside it is polish, and a reader
/// whose font draws none of them still reads "Caution".
#[test]
fn an_alert_writes_its_kind_out_above_the_quote() {
let theme = theme_to_styles(&luxe_core::theme::builtin_themes()[0].clone());
for (tag, word) in [
("NOTE", "Note"),
("TIP", "Tip"),
("IMPORTANT", "Important"),
("WARNING", "Warning"),
("CAUTION", "Caution"),
] {
let rendered: Vec<String> = render_markdown(&format!("> [!{tag}]\n> mind this"), &theme)
.iter()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect())
.collect();
let labeled = rendered
.iter()
.position(|line| line.ends_with(word))
.unwrap_or_else(|| panic!("no line says {word:?}: {rendered:?}"));
assert_eq!(
rendered.get(labeled + 1).map(String::as_str),
Some("> mind this"),
"the quote follows its own word without a gap: {rendered:?}"
);
assert!(
!rendered.iter().any(|line| line.contains("[!")),
"the raw tag never reaches the reader: {rendered:?}"
);
}
}
/// The word takes the severity's color for an answer and weight alone for reasoning, which
/// spends structure rather than color everywhere else in that voice too.
#[test]
fn an_alerts_word_is_colored_by_severity_except_in_the_reasoning_voice() {
let theme = theme_to_styles(&luxe_core::theme::builtin_themes()[0].clone());
let word_style = |voice| {
layout_markdown_in("> [!CAUTION]\n> careful", &theme, voice)
.iter()
.flat_map(|layout| layout.line.spans.clone())
.find(|span| span.content.ends_with("Caution"))
.expect("the alert's word")
.style
};
let answer = word_style(MarkdownVoice::Answer);
assert_eq!(answer.fg, theme.error.fg, "caution is the theme's error color");
assert!(answer.add_modifier.contains(Modifier::BOLD));
let reasoning = word_style(MarkdownVoice::Reasoning);
assert_eq!(reasoning.fg, theme.thinking_text.fg, "reasoning keeps its muted voice");
assert!(reasoning.add_modifier.contains(Modifier::BOLD | Modifier::ITALIC));
}
#[test]
fn test_blockquote_inline_formatting() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
// Inline bold inside blockquote: one prefix, BOLD modifier preserved
let input = "> **bold** and normal";
let lines = render_markdown(input, &theme);
assert_eq!(lines.len(), 1, "should produce 1 quoted line");
let spans = &lines[0].spans;
// First span is the prefix (exactly one)
assert_eq!(spans[0].content.as_ref(), "> ", "single prefix span");
assert!(
spans[0].style.fg.is_some(),
"prefix should have a foreground color (DarkGray fallback or md_quote token)"
);
// Find the "bold" text and verify BOLD modifier
let bold_span =
spans.iter().find(|s| s.content.as_ref() == "bold").expect("'bold' span missing");
assert!(
bold_span.style.add_modifier.contains(Modifier::BOLD),
"'bold' should have BOLD modifier, got {:?}",
bold_span.style
);
}
#[test]
fn test_loose_list() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
// Loose list (blank line between items) wraps each item in a paragraph
let input = "- item 1\n\n- item 2\n\n- item 3";
let lines = render_markdown(input, &theme);
// Each bullet + text should be on the same line (no orphaned bullets)
let bullet_lines: Vec<_> = lines
.iter()
.filter(|line| {
let content: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
content.starts_with("• ")
})
.collect();
assert_eq!(bullet_lines.len(), 3, "should have 3 bullet lines");
// Each bullet line should also contain its text
for (i, line) in bullet_lines.iter().enumerate() {
let content: String = line.spans.iter().map(|s| s.content.as_ref()).collect();
assert!(
content.contains(format!("item {}", i + 1).as_str()),
"bullet line {} should contain text: {:?}",
i,
content
);
}
}
#[test]
fn test_code_block() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "```rust\nlet x = 1;\n```\nText after";
let lines = render_markdown(input, &theme);
assert!(lines.len() >= 2, "code block + text should produce at least 2 lines");
// Syntect should produce multiple colored spans for Rust code
let has_highlighted_line = lines.iter().any(|line| {
line.spans.len() > 1 && line.spans.windows(2).any(|w| w[0].style != w[1].style)
});
assert!(
has_highlighted_line,
"expected syntect to produce multiple colored spans for Rust code"
);
}
#[test]
fn test_empty_input() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "";
let lines = render_markdown(input, &theme);
assert!(lines.is_empty(), "empty input should produce no lines");
}
#[test]
fn blocks_are_separated_by_blank_lines_but_list_items_stay_tight() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "Intro paragraph.\n\n- Item 1\n- Item 2\n\nAfter the list.";
let lines = render_markdown(input, &theme);
let text = |i: usize| -> String {
lines[i].spans.iter().map(|s| s.content.as_ref()).collect::<String>()
};
// Intro / blank / item1 / item2 / blank / after — blanks between blocks, items tight.
assert_eq!(lines.len(), 6, "got: {:?}", (0..lines.len()).map(text).collect::<Vec<_>>());
assert_eq!(text(0), "Intro paragraph.");
assert!(lines[1].spans.is_empty(), "blank before the list");
assert!(text(2).contains("Item 1"));
assert!(text(3).contains("Item 2"));
assert!(lines[4].spans.is_empty(), "blank after the list");
assert_eq!(text(5), "After the list.");
}
#[test]
fn test_horizontal_rule() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "before\n\n---\n\nafter";
let lines = render_markdown(input, &theme);
// Blocks are separated by blank lines: before / _ / HR / _ / after.
assert_eq!(lines.len(), 5, "expected before, blank, HR, blank, after");
assert_eq!(lines[0].spans[0].content.as_ref(), "before");
assert!(lines[1].spans.is_empty(), "blank gap before the rule");
// L2: horizontal rule
assert!(lines[2].spans[0].content.contains('━'), "HR line should contain box-drawing chars");
assert!(
lines[2].spans[0].style.add_modifier.contains(Modifier::BOLD),
"HR span should have BOLD modifier"
);
// HR should use muted token foreground (not hardcoded DarkGray).
assert_eq!(
lines[2].spans[0].style.fg, theme.muted.fg,
"HR span should use muted token foreground"
);
assert!(lines[3].spans.is_empty(), "blank gap after the rule");
assert_eq!(lines[4].spans[0].content.as_ref(), "after");
}
#[test]
fn test_link() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "Check [this link](https://example.com) out";
let lines = render_markdown(input, &theme);
assert_eq!(lines.len(), 1, "single paragraph");
let content: String = lines[0].spans.iter().map(|s| s.content.as_ref()).collect();
assert!(content.contains("this link"), "should contain link text: {}", content);
assert_eq!(content, "Check this link (https://example.com) out", "the address follows");
let autolink: String = render_markdown("See <https://example.com>.", &theme)[0]
.spans
.iter()
.map(|s| s.content.as_ref())
.collect();
assert_eq!(autolink, "See https://example.com.", "an address is not said twice");
let styled: String = render_markdown("[**bold** words](https://x.dev)", &theme)[0]
.spans
.iter()
.map(|s| s.content.as_ref())
.collect();
assert_eq!(styled, "bold words (https://x.dev)", "once, after every span");
// The text span should have UNDERLINED modifier (from link style)
let text_span = lines[0]
.spans
.iter()
.find(|s| s.content.contains("this link"))
.expect("text span should exist");
assert!(
text_span.style.add_modifier.contains(Modifier::UNDERLINED),
"text span should have UNDERLINED modifier"
);
}
#[test]
fn test_table() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let input = "| Header 1 | Header 2 |\n|--------|--------|\n| Cell 1 | Cell 2 |";
let lines = render_markdown(input, &theme);
let text = |line: &Line| -> String {
line.spans.iter().map(|s| s.content.as_ref()).collect::<String>()
};
// top border, header, header separator, one body row, bottom border
assert_eq!(lines.len(), 5, "expected a bordered 5-line table");
assert!(text(&lines[0]).starts_with('┌') && text(&lines[0]).contains('┬'));
let header = text(&lines[1]);
assert!(header.contains("Header 1") && header.contains("Header 2"), "header row: {header}");
assert!(header.starts_with('│') && header.ends_with('│'));
assert!(
lines[1].spans.iter().any(|s| s.style.add_modifier.contains(Modifier::BOLD)),
"header row should be bold"
);
assert!(text(&lines[2]).contains('┼'), "expected a header separator row");
let body = text(&lines[3]);
assert!(body.contains("Cell 1") && body.contains("Cell 2"), "body row: {body}");
assert!(text(&lines[4]).starts_with('└') && text(&lines[4]).ends_with('┘'));
// Cell text stays readable; only the box uses the muted border color.
let cell = lines[3].spans.iter().find(|s| s.content.contains("Cell 1")).unwrap();
assert_eq!(cell.style.fg, theme.text.fg, "cell text must use readable foreground");
}
#[test]
fn test_table_columns_align_across_rows() {
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
// Uneven natural widths must be padded to one shared grid width.
let input = "| A | Name |\n|---|---|\n| longvalue | x |";
let lines = render_markdown(input, &theme);
let width = |line: &Line| -> usize {
line.spans.iter().map(|s| unicode_width::UnicodeWidthStr::width(s.content.as_ref())).sum()
};
let first = width(&lines[0]);
assert!(first > 0);
assert!(
lines.iter().all(|line| width(line) == first),
"every border and row must share one width for an aligned grid"
);
}
/// pulldown-cmark numbers its alignments None, Left, Center, Right; reading them off by one
/// drew every centered column right-aligned and every right-aligned one centered.
#[test]
fn a_column_aligns_the_way_its_separator_says() {
let theme = theme_to_styles(&luxe_core::theme::builtin_themes()[0].clone());
let input = "| left | middle | right |\n|:-----|:------:|------:|\n| a | b | c |";
let lines = render_markdown(input, &theme);
let body: String = lines[3].spans.iter().map(|s| s.content.as_ref()).collect();
assert_eq!(body, "│ a │ b │ c │");
}
#[test]
fn test_streaming_safety() {
// Malformed/partial markdown must never panic render_markdown —
// these are exactly the inputs a streaming model produces mid-token.
let theme = luxe_core::theme::builtin_themes()[0].clone();
let theme = theme_to_styles(&theme);
let partial_inputs = [
"# H1",
"## H2\n", // unclosed heading (no text yet)
"**bold", // unclosed bold
"*italic", // unclosed italic
"`code", // unclosed inline code
"[link](url", // unclosed link
"| a | b |\n|---|---|\n| c |", // partial table (no closing row)
"```
code", // unclosed fence (no closing ```)
"> quote", // unclosed blockquote
"- item", // unclosed list item
"---", // bare HR with no surrounding paragraphs
"",
];
for input in partial_inputs {
let lines = render_markdown(input, &theme);
// Just verifying it doesn't panic; output shape is allowed to vary.
let _ = lines;
}
}
/// A backticked identifier in a table cell stays in that cell.
///
/// The break this catches: inline code always went to the prose line, so it vanished from the
/// grid and was flushed after the table, glued to whatever paragraph came next.
#[test]
fn table_inline_code_stays_in_its_cell() {
let theme = theme_to_styles(&luxe_core::theme::builtin_themes()[0].clone());
let input = "| `key` | Meaning |\n|---|---|\n| `retries` | how many times, `n` max |\n\nAfter.";
let lines = render_markdown(input, &theme);
let text = |line: &Line| line.spans.iter().map(|s| s.content.as_ref()).collect::<String>();
let all: Vec<String> = lines.iter().map(text).collect();
assert!(all[1].contains("key") && all[1].contains("Meaning"), "code-only header: {all:?}");
assert!(all[3].contains("retries"), "code-only body cell: {all:?}");
assert!(all[3].contains("how many times, n max"), "mixed cell: {all:?}");
let after = all.iter().find(|line| line.contains("After")).expect("the paragraph");
assert!(!after.contains("retries") && !after.contains("key"), "nothing leaked: {after}");
}
/// A quote ends where its block ends: the paragraph after it is not quoted, however the quote's
/// last block finished.
///
/// The break this catches: a quote that ended with a line still pending flushed it and never
/// closed, so everything after a quoted list or fence was drawn with `> ` in front of it.
#[test]
fn text_after_a_quote_is_not_quoted() {
let theme = theme_to_styles(&luxe_core::theme::builtin_themes()[0].clone());
for source in ["> - a list in a quote\n\nafter\n", "> ```\n> fenced\n> ```\n\nafter\n"] {
let lines = render_markdown(source, &theme);
let last: String = lines
.iter()
.rev()
.map(|line| line.spans.iter().map(|span| span.content.as_ref()).collect::<String>())
.find(|text| !text.trim().is_empty())
.expect("something drawn");
assert_eq!(last, "after", "{source:?}");
}
}

View File

@@ -0,0 +1,183 @@
//! Markdown voices — the two readers a block is styled for, and every style each one spends.
use crate::glyphs::Icon;
use crate::theme::styles::ThemeStyles;
use pulldown_cmark::{BlockQuoteKind, HeadingLevel};
use ratatui::style::{Color as RatatuiColor, Modifier, Style};
/// Which reader a markdown block is being rendered for.
///
/// Reasoning has to stay recognizable as reasoning while still being *formatted*, so the two
/// voices differ in what they spend on structure rather than in what they parse.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub(crate) enum MarkdownVoice {
/// Assistant prose: the theme's markdown tokens, syntax-highlighted fences.
Answer,
/// Model reasoning: muted italic throughout, headings and `**strong**` earning weight instead
/// of a color, `code` keeping the theme's code hue, and fences left unhighlighted.
Reasoning,
}
impl MarkdownVoice {
/// The modifier every span in this voice carries.
pub(super) fn modifier(self) -> Modifier {
match self {
Self::Answer => Modifier::empty(),
Self::Reasoning => Modifier::ITALIC,
}
}
/// Whether a soft break ends the line. Reasoning is the model's own notes rather than authored
/// prose, so its line breaks are kept instead of reflowed into one paragraph.
pub(super) fn breaks_on_soft_break(self) -> bool {
matches!(self, Self::Reasoning)
}
}
/// Build a Style from the current style stack.
pub(super) fn build_style(stack: &[Modifier], base: Style) -> Style {
let mut style = base;
for modifier in stack {
style = style.add_modifier(*modifier);
}
style
}
/// The voice's base prose style — what unadorned text, list bullets, and table cells take.
pub(super) fn build_text_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
let base = match voice {
MarkdownVoice::Answer => theme.text,
MarkdownVoice::Reasoning => theme.thinking_text,
};
base.add_modifier(voice.modifier())
}
/// Build a distinct Style for inline code spans using the md_code token.
///
/// Reasoning keeps the hue: a backtick in a model's notes almost always names a symbol, a path or a
/// command, and that is worth finding at a glance even in a block meant to recede.
pub(super) fn build_code_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
theme.md_code.add_modifier(voice.modifier())
}
/// Build a heading style using the md_heading token with BOLD modifier.
///
/// A reasoning heading spends weight instead of color, so the section titles GPT models lead with
/// read as titles without breaking the muted voice the rest of the block keeps.
pub(super) fn build_heading_style(
theme: &ThemeStyles,
_level: HeadingLevel,
voice: MarkdownVoice,
) -> Style {
let base = match voice {
MarkdownVoice::Answer => theme.md_heading,
MarkdownVoice::Reasoning => theme.thinking_text,
};
base.add_modifier(Modifier::BOLD).add_modifier(voice.modifier())
}
/// Build a blockquote prefix style using the md_quote token.
pub(super) fn build_quote_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
if voice == MarkdownVoice::Reasoning {
return build_text_style(theme, voice);
}
if theme.md_quote.fg.is_some() {
theme.md_quote
} else {
Style::new().fg(RatatuiColor::DarkGray) // fallback: dim gray
}
}
/// The mark a GFM alert wears beside its word, where the terminal can draw one.
pub(super) fn alert_icon(kind: BlockQuoteKind) -> Icon {
match kind {
BlockQuoteKind::Note => Icon::AlertNote,
BlockQuoteKind::Tip => Icon::AlertTip,
BlockQuoteKind::Important => Icon::AlertImportant,
BlockQuoteKind::Warning => Icon::AlertWarning,
BlockQuoteKind::Caution => Icon::AlertCaution,
}
}
/// The word a GFM alert announces itself with.
pub(super) fn alert_label(kind: BlockQuoteKind) -> &'static str {
match kind {
BlockQuoteKind::Note => "Note",
BlockQuoteKind::Tip => "Tip",
BlockQuoteKind::Important => "Important",
BlockQuoteKind::Warning => "Warning",
BlockQuoteKind::Caution => "Caution",
}
}
/// How an alert's word is drawn: the severity's own color for an answer, and weight alone for
/// reasoning, which spends structure rather than color everywhere else too.
pub(super) fn build_alert_style(
theme: &ThemeStyles,
voice: MarkdownVoice,
kind: BlockQuoteKind,
) -> Style {
if voice == MarkdownVoice::Reasoning {
return build_text_style(theme, voice).add_modifier(Modifier::BOLD);
}
let base = match kind {
BlockQuoteKind::Note => theme.info,
BlockQuoteKind::Tip => theme.success,
BlockQuoteKind::Important => theme.accent,
BlockQuoteKind::Warning => theme.warning,
BlockQuoteKind::Caution => theme.error,
};
base.add_modifier(Modifier::BOLD)
}
/// Build a link style using the md_link theme token with UNDERLINED modifier.
pub(super) fn build_link_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
if voice == MarkdownVoice::Reasoning {
return build_text_style(theme, voice).add_modifier(Modifier::UNDERLINED);
}
let mut style = theme.md_link;
style = style.add_modifier(Modifier::UNDERLINED);
if style.fg.is_none() {
style = style.fg(RatatuiColor::Blue); // fallback: blue for links
}
style
}
/// Build a link URL style using the md_link_url theme token.
pub(super) fn build_link_url_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
if voice == MarkdownVoice::Reasoning {
return build_text_style(theme, voice);
}
if theme.md_link_url.fg.is_some() {
theme.md_link_url
} else {
Style::new().fg(RatatuiColor::DarkGray) // fallback: dim gray for URLs
}
}
/// Build a readable table-cell style.
pub(super) fn build_table_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
build_text_style(theme, voice)
}
/// The style a code fence's frame is drawn in — the table border's, for the same reason: two
/// framed blocks in one answer should look like one idea.
pub(super) fn build_fence_border_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
build_table_border_style(theme, voice)
}
/// Border color for the box-drawing frame — subtle, distinct from cell text.
pub(super) fn build_table_border_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
if voice == MarkdownVoice::Reasoning {
return build_text_style(theme, voice);
}
Style::new().fg(theme.border.fg.or(theme.muted.fg).unwrap_or(RatatuiColor::DarkGray))
}
/// Build a horizontal rule style using the md_rule token with BOLD modifier.
pub(super) fn build_hr_style(theme: &ThemeStyles, voice: MarkdownVoice) -> Style {
let mut style = Style::new().add_modifier(Modifier::BOLD).add_modifier(voice.modifier());
// Use muted token for horizontal rules — distinct from code but subtle.
style = style.fg(theme.muted.fg.unwrap_or(RatatuiColor::DarkGray));
style
}