= Vec::with_capacity(children.len());
for (child_ix, child) in children.iter().enumerate() {
match child {
BlockNode::Paragraph { .. } => {
let last_not_list = child_ix > 0
&& !matches!(children[child_ix - 1], BlockNode::List { .. });
let text = child.render_block(
NodeRenderOptions {
depth: options.depth + 1,
todo: checked.is_some(),
is_last: true,
..options
},
node_cx,
window,
cx,
);
// Continuation paragraph — stack vertically below
// the previous row, indented to align with the text
// column (past bullet/number prefix).
if last_not_list {
if let Some(preceding_row) = items.pop() {
items.push(
div().child(preceding_row).child(
div()
.w_full()
.pl(rems(1.))
.overflow_hidden()
.child(text),
),
);
continue;
}
}
items.push(Self::render_list_item_row(
text,
ix,
options,
*checked,
&node_cx.style,
window.line_height(),
));
}
BlockNode::List { .. } => {
items.push(div().ml(rems(1.)).child(child.render_block(
NodeRenderOptions {
depth: options.depth + 1,
todo: checked.is_some(),
is_last: true,
..options
},
node_cx,
window,
cx,
)));
}
BlockNode::Root { .. }
| BlockNode::Heading { .. }
| BlockNode::Blockquote { .. }
| BlockNode::CodeBlock(_)
| BlockNode::Custom(_)
| BlockNode::Table(_)
| BlockNode::HorizontalRule { .. } => {
let block = child.render_block(
NodeRenderOptions {
depth: options.depth + 1,
todo: checked.is_some(),
is_last: true,
..options
},
node_cx,
window,
cx,
);
if child_ix == 0 {
items.push(Self::render_list_item_row(
block,
ix,
options,
*checked,
&node_cx.style,
window.line_height(),
));
} else {
// Indent continuation blocks to align with a
// nested sub-list (`ml(rems(1.))`) and with
// continuation paragraphs.
items.push(
div()
.w_full()
.min_w_0()
.pl(rems(1.))
.overflow_hidden()
.child(block),
);
}
}
BlockNode::ListItem { .. }
| BlockNode::Break { .. }
| BlockNode::Definition { .. }
| BlockNode::Unknown => {}
}
}
items
})
.into_any_element(),
_ => div().into_any_element(),
}
}
/// Render a Markdown table. Dispatches to a horizontally scrollable layout
/// when `style.table` opts in with overflow-x: scroll, otherwise to the
/// default layout that fits the container width and wraps cell content.
fn render_table(
item: &BlockNode,
options: &NodeRenderOptions,
node_cx: &NodeContext,
window: &mut Window,
cx: &mut App,
) -> impl IntoElement {
const DEFAULT_LENGTH: usize = 5;
let table = match item {
BlockNode::Table(table) => table,
_ => return div().into_any_element(),
};
// Scroll mode is opted in via `style.table` overflow-x: scroll.
if matches!(node_cx.style.table().overflow.x, Some(Overflow::Scroll)) {
let col_count = table
.children
.iter()
.map(|row| row.children.len())
.max()
.unwrap_or(0);
return Self::render_scroll_table(table, col_count, options, node_cx, window, cx);
}
// Per-column max text length (in chars), used to proportion the columns
// in the default (wrap) layout.
let mut col_lens: Vec
= vec![];
for row in table.children.iter() {
for (ix, cell) in row.children.iter().enumerate() {
if col_lens.len() <= ix {
col_lens.push(DEFAULT_LENGTH);
}
col_lens[ix] = col_lens[ix].max(cell.children.text_len());
}
}
Self::render_wrap_table(table, &col_lens, options, node_cx, window, cx)
}
/// Horizontally scrollable table layout (opt-in via `style.table`
/// overflow-x: scroll).
///
/// Column widths come from the **measured** shaped text of each cell (the
/// widest per column across all rows), so columns line up and fit their
/// content exactly — char-count heuristics are inaccurate on proportional
/// fonts. The layout adapts to the frame like CSS auto table layout:
///
/// - Wider than the content: cells `flex_grow` proportionally to fill.
/// - Narrower: columns shrink and their text wraps, but not below a
/// per-column floor.
/// - Narrower than the floors: the table keeps the floor widths and
/// scrolls horizontally, so no content ever becomes unreachable.
///
/// `white_space: nowrap` on `style.table_cell` composes like in CSS: the
/// refinement keeps cell text on a single line, and the floors are raised
/// to the full content widths so the single-line columns never shrink —
/// the table scrolls as soon as the content is wider than the frame.
fn render_scroll_table(
table: &Table,
col_count: usize,
options: &NodeRenderOptions,
node_cx: &NodeContext,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
// Shrinking columns stop (and the table starts to scroll) at a floor
// scaled to their content: roughly the width at which the text wraps
// to `CELL_WRAP_MAX_LINES` lines, clamped between the two bounds so
// moderate columns can still wrap meaningfully while one huge column
// cannot push the scroll threshold arbitrarily high.
const CELL_WRAP_MAX_LINES: f32 = 2.0;
const CELL_WRAP_MIN_PX: f32 = 160.0;
const CELL_WRAP_MAX_PX: f32 = 480.0;
const TABLE_BORDER_PX: f32 = 2.0; // the track's border_1, left + right
let col_w = measure_table_columns(table, col_count, node_cx, window, cx);
let style = &node_cx.style;
// Nowrap cells (via the `table_cell` refinement, which cascades to
// the cell text) must never shrink below their single-line content,
// so their floor is the content width itself.
let nowrap = style.table_cell().text.white_space == Some(WhiteSpace::Nowrap);
let col_min_w: Vec = if nowrap {
col_w.clone()
} else {
col_w
.iter()
.map(|w| {
(w / CELL_WRAP_MAX_LINES)
.clamp(CELL_WRAP_MIN_PX, CELL_WRAP_MAX_PX)
.min(*w)
})
.collect()
};
let min_total_w: f32 = col_min_w.iter().sum::() + TABLE_BORDER_PX;
let scroll_handle = window
.use_keyed_state(
block_element_id("table-scroll", table.span, options.ix),
cx,
|_, _| ScrollHandle::default(),
)
.read(cx)
.clone();
let row_count = table.children.len();
let mut rows = Vec::with_capacity(row_count);
let mut cell_ordinal = 0;
for (row_ix, row) in table.children.iter().enumerate() {
let mut cells = Vec::with_capacity(row.children.len());
for (ix, cell) in row.children.iter().enumerate() {
let fade_key = table
.span
.map(|span| TextLeafKey::table_cell(span.start, cell_ordinal));
cell_ordinal += 1;
let align = table.column_align(ix);
let is_last_col = ix == row.children.len() - 1;
let width = col_w.get(ix).copied().unwrap_or(CELL_MIN_PX);
let min_width = col_min_w.get(ix).copied().unwrap_or(CELL_MIN_PX);
cells.push(
div()
// Measured max-content width is the flex-basis;
// `flex_grow` (proportional to it) distributes extra
// space so a narrow table still fills the frame, while
// shrinking is clamped at `min_w` — the flex engine
// squeezes columns (their text wraps) down to the
// floors before the track starts to scroll.
.flex_basis(px(width))
.flex_grow(width)
.flex_shrink(1.)
.min_w(px(min_width))
.overflow_hidden()
.when(align == ColumnumnAlign::Center, |this| this.text_center())
.when(align == ColumnumnAlign::Right, |this| this.text_right())
.px_2()
.py_1()
.when(!is_last_col, |this| {
this.border_r_1().border_color(style.border())
})
.refine_style(&style.table_cell())
.child(cell.children.render(fade_key, node_cx, window, cx)),
);
}
rows.push(
div()
.w_full()
.when(row_ix < row_count - 1, |this| this.border_b_1())
.border_color(style.border())
.flex()
.flex_row()
// The first row is the header, as everywhere else that
// reads a table (`table_data`, `to_markdown`). The
// refinement comes last so it can override the defaults.
.when(row_ix == 0, |this| {
this.bg(style.code_background())
.text_color(style.foreground())
.refine_style(&style.table_head())
})
.children(cells),
);
}
div()
.pb(rems(1.))
.w_full()
.child(
// Scroll viewport owns the visible frame, including any
// caller-provided radius. Keeping the border here makes the
// rounded frame stable while the wider row track moves below it.
//
// `horizontal_scroll_area` clips with `overflow_hidden` and
// delegates the wheel to a sibling `ScrollableMask`, so the
// gesture is locked to its starting axis and a horizontal swipe
// is consumed before an ancestor scroller (`gpui::list` under
// `TextView::scrollable`) can take its vertical component.
horizontal_scroll_area(
block_element_id("table", table.span, options.ix),
&scroll_handle,
&StyleRefinement::default()
.bg(style
.table_background()
.unwrap_or(cx.theme().tokens.colors.surface))
.border_1()
.border_color(style.border())
.refine_style(style.table()),
// Row track sized to `max(viewport, column floors)`:
// `min_w_full` fills the frame while the columns can still
// shrink-to-fit (their text wrapping), the definite
// `w(min_total_w)` keeps the floors once they are reached,
// letting the track exceed the viewport and scroll.
div().min_w_full().w(px(min_total_w)).children(rows),
),
)
// Custom actions row (e.g. copy / download) rendered below the
// table. The hook's element spans full width; alignment is up to
// the caller (e.g. `h_flex().justify_end()`). The gap keeps hover
// backgrounds of the action buttons off the table border, and the
// id scopes the caller's element ids per table, so plain ids like
// `"copy"` don't collide across tables (same as code blocks).
.children(node_cx.table_actions.clone().map(|f| {
div()
.id(block_element_id("table-actions", table.span, options.ix))
.mt_1()
.child(f(&table.cached_table_data(), window, cx))
}))
.into_any_element()
}
/// Default table layout: a flex grid whose columns are proportioned by
/// content length and shrink to fit the container width (cell text wraps).
fn render_wrap_table(
table: &Table,
col_lens: &[usize],
options: &NodeRenderOptions,
node_cx: &NodeContext,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
const MAX_LENGTH: usize = 150;
let style = &node_cx.style;
let row_count = table.children.len();
let mut rows = Vec::with_capacity(row_count);
let mut cell_ordinal = 0;
for (row_ix, row) in table.children.iter().enumerate() {
let mut cells = Vec::with_capacity(row.children.len());
for (ix, cell) in row.children.iter().enumerate() {
let fade_key = table
.span
.map(|span| TextLeafKey::table_cell(span.start, cell_ordinal));
cell_ordinal += 1;
let align = table.column_align(ix);
let is_last_col = ix == row.children.len() - 1;
let len = col_lens
.get(ix)
.copied()
.unwrap_or(MAX_LENGTH)
.min(MAX_LENGTH);
cells.push(
div()
.overflow_hidden()
.when(align == ColumnumnAlign::Center, |this| this.text_center())
.when(align == ColumnumnAlign::Right, |this| this.text_right())
.min_w_16()
.w(Length::Definite(relative(len as f32)))
.px_2()
.py_1()
.when(!is_last_col, |this| {
this.border_r_1().border_color(style.border())
})
.refine_style(&style.table_cell())
.child(cell.children.render(fade_key, node_cx, window, cx)),
);
}
rows.push(
div()
.w_full()
.when(row_ix < row_count - 1, |this| this.border_b_1())
.border_color(style.border())
.flex()
.flex_row()
// The first row is the header, as everywhere else that
// reads a table (`table_data`, `to_markdown`). The
// refinement comes last so it can override the defaults.
.when(row_ix == 0, |this| {
this.bg(style.code_background())
.text_color(style.foreground())
.refine_style(&style.table_head())
})
.children(cells),
);
}
div()
.pb(rems(1.))
.w_full()
.child(
div()
.w_full()
.bg(style
.table_background()
.unwrap_or(cx.theme().tokens.colors.surface))
.border_1()
.border_color(style.border())
.overflow_hidden()
.children(rows)
.refine_style(&style.table()),
)
// Custom actions row (e.g. copy / download) rendered below the
// table. The hook's element spans full width; alignment is up to
// the caller (e.g. `h_flex().justify_end()`). The gap keeps hover
// backgrounds of the action buttons off the table border, and the
// id scopes the caller's element ids per table, so plain ids like
// `"copy"` don't collide across tables (same as code blocks).
.children(node_cx.table_actions.clone().map(|f| {
div()
.id(block_element_id("table-actions", table.span, options.ix))
.mt_1()
.child(f(&table.cached_table_data(), window, cx))
}))
.into_any_element()
}
pub(crate) fn render_block(
&self,
options: NodeRenderOptions,
node_cx: &NodeContext,
window: &mut Window,
cx: &mut App,
) -> AnyElement {
let mb = if options.in_list || options.is_last {
rems(0.)
} else {
node_cx.style.paragraph_gap()
};
match self {
BlockNode::Root { children, .. } => div()
.children(children.into_iter().enumerate().map(move |(ix, node)| {
node.render_block(NodeRenderOptions { ix, ..options }, node_cx, window, cx)
}))
.into_any_element(),
BlockNode::Paragraph(paragraph) => gapped(
paragraph.render(
paragraph.span.map(|span| TextLeafKey::block(span.start)),
node_cx,
window,
cx,
),
mb,
),
BlockNode::Heading {
level,
children,
span,
} => {
let (text_size, font_weight) = match level {
1 => (rems(2.), FontWeight::BOLD),
2 => (rems(1.5), FontWeight::SEMIBOLD),
3 => (rems(1.25), FontWeight::SEMIBOLD),
4 => (rems(1.125), FontWeight::SEMIBOLD),
5 => (rems(1.), FontWeight::SEMIBOLD),
6 => (rems(1.), FontWeight::MEDIUM),
_ => (rems(1.), FontWeight::NORMAL),
};
let text_size = text_size.to_pixels(px(14.));
div()
.pb(rems(0.3))
.whitespace_normal()
.text_size(text_size)
.font_weight(font_weight)
.refine_style(&node_cx.style.heading(*level))
.child(children.render(
span.map(|span| TextLeafKey::block(span.start)),
node_cx,
window,
cx,
))
.into_any_element()
}
BlockNode::Blockquote { children, .. } => gapped(
div()
.w_full()
.text_color(node_cx.style.muted_foreground())
.border_l_3()
.border_color(node_cx.style.border())
.px_4()
.children({
let children_len = children.len();
children.into_iter().enumerate().map(move |(index, c)| {
let is_last = index == children_len - 1;
c.render_block(options.is_last(is_last), node_cx, window, cx)
})
})
.into_any_element(),
mb,
),
BlockNode::List {
children,
ordered,
start,
..
} => div()
.w_full()
.min_w_0()
.pb(mb)
.children({
let mut items = Vec::with_capacity(children.len());
let mut item_index = 0;
for (ix, item) in children.into_iter().enumerate() {
let is_item = item.is_list_item();
items.push(Self::render_list_item(
item,
item_index,
NodeRenderOptions {
ix,
ordered: *ordered,
list_start: *start,
..options
},
node_cx,
window,
cx,
));
if is_item {
item_index += 1;
}
}
items
})
.into_any_element(),
BlockNode::CodeBlock(code_block) => code_block.render(&options, node_cx, window, cx),
BlockNode::Custom(node) => {
let inner = match node_cx.markdown_extensions.render_block(node, window, cx) {
Some(rendered) => rendered,
None => div().child(node.as_text().to_string()).into_any_element(),
};
div().pb(mb).child(inner).into_any_element()
}
BlockNode::Table { .. } => {
Self::render_table(self, &options, node_cx, window, cx).into_any_element()
}
BlockNode::HorizontalRule { .. } => gapped(
div()
.bg(node_cx.style.border())
.h(px(2.))
.into_any_element(),
mb,
),
BlockNode::Break { .. } => div().into_any_element(),
BlockNode::Unknown { .. } | BlockNode::Definition { .. } => div().into_any_element(),
_ => {
if cfg!(debug_assertions) {
tracing::warn!("unknown implementation: {:?}", self);
}
div().into_any_element()
}
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn selected_inline_objects_coalesce_surrounding_emphasis() {
for (object_mark, expected) in [
(TextMark::default().italic(), "*fore $x$ aft*"),
(TextMark::default().italic().bold(), "*fore **$x$** aft*"),
] {
let italic = TextMark::default().italic();
let before = InlineNode::new("before ").marks(vec![(0..7, italic.clone())]);
let formula =
InlineNode::custom(MarkdownNode::new("math", ()).text("x").markdown("$x$"))
.marks(vec![(0..1, object_mark)]);
let after = InlineNode::new(" after").marks(vec![(0..6, italic)]);
{
let mut state = formula.state.lock().unwrap();
state.text = "before ".into();
state.selection = Some((2..7).into());
}
*formula.custom_selection.lock().unwrap() = true;
let paragraph = Paragraph {
children: vec![before, formula, after],
..Default::default()
};
{
let mut state = paragraph.state.lock().unwrap();
state.text = " after".into();
state.selection = Some((0..4).into());
}
assert_eq!(paragraph.selected_source(), expected);
}
}
#[test]
fn consecutive_inline_objects_copy_atomically_without_neighboring_text() {
let first =
InlineNode::custom(MarkdownNode::new("math", ()).text("甲²").markdown("$甲^2$"));
let second = InlineNode::custom(MarkdownNode::new("math", ()).text("b").markdown("$b$"));
*first.custom_selection.lock().unwrap() = true;
*second.custom_selection.lock().unwrap() = true;
let paragraph = Paragraph {
children: vec![first, second],
..Default::default()
};
assert_eq!(paragraph.selected_text(), "甲²b");
assert_eq!(paragraph.selected_source(), "$甲^2$$b$");
assert!(paragraph.has_selection());
paragraph.clear_selection();
assert_eq!(paragraph.selected_text(), "");
assert_eq!(paragraph.selected_source(), "");
assert!(!paragraph.has_selection());
}
#[test]
fn selected_inline_object_interleaves_runs_and_preserves_enclosing_mark() {
let before = InlineNode::new("中文 ");
let formula =
InlineNode::custom(MarkdownNode::new("math", ()).text("x²").markdown("$x^2$"))
.marks(vec![(0..3, TextMark::default().bold())]);
let after = InlineNode::new(" English");
{
let mut preceding = formula.state.lock().unwrap();
preceding.text = "中文 ".into();
preceding.selection = Some((3..7).into());
}
*formula.custom_selection.lock().unwrap() = true;
let paragraph = Paragraph {
children: vec![before, formula, after],
..Default::default()
};
{
let mut trailing = paragraph.state.lock().unwrap();
trailing.text = " English".into();
trailing.selection = Some((0..4).into());
}
assert_eq!(paragraph.selected_text(), "文 x² Eng");
assert_eq!(paragraph.selected_source(), "文 **$x^2$** Eng");
}
#[test]
fn custom_inline_inherits_marks_and_resolves_link_references() {
use gpui::{Empty, TestApp};
let mut app = TestApp::new();
let mut window = app.open_window(|_, _| Empty);
window.update(|_, _, cx| {
cx.set_global(crate::Theme::default());
let mut node_cx = NodeContext::default();
let mut mark = TextMark::default().bold();
mark.italic = true;
mark.strikethrough = true;
mark.link = Some(LinkMark {
identifier: Some("ref".into()),
..Default::default()
});
node_cx.link_refs.insert(
"ref".into(),
LinkMark {
url: "https://example.com".into(),
..Default::default()
},
);
let paragraph = Paragraph {
children: vec![
InlineNode::custom(MarkdownNode::new("test", ()).text("x"))
.marks(vec![(0..1, mark)]),
],
..Default::default()
};
let items = paragraph.inline_flow_items(None, &[], &[], &node_cx, cx);
let InlineFlowItem::Object { style, link, .. } = &items[0] else {
panic!()
};
assert_eq!(style.font_weight, Some(FontWeight::BOLD));
assert_eq!(style.font_style, Some(FontStyle::Italic));
assert!(style.strikethrough.is_some());
assert_eq!(link.as_ref().unwrap().url.as_ref(), "https://example.com");
});
}
#[test]
fn table_column_uses_prepared_inline_metrics_after_resource_update() {
use crate::text::InlineElement;
use crate::text::inline::test_draw::in_prepaint;
use gpui::{Image, ImageFormat, TestApp};
let mut app = TestApp::new();
let width = Arc::new(std::sync::atomic::AtomicUsize::new(400));
let render_width = width.clone();
let mut node_cx = NodeContext::default();
node_cx.markdown_extensions = Arc::new(MarkdownExtensions::default().plugin(
crate::text::markdown_ext::TestInlinePlugin::new("test").render_with(
move |_, _, _, _| {
Some(
InlineElement::new(
gpui::img(Arc::new(Image::from_bytes(
ImageFormat::Svg,
b"".to_vec(),
)))
.w(px(
render_width.load(std::sync::atomic::Ordering::Relaxed) as f32
))
.h(px(20.)),
)
.with_baseline(px(15.)),
)
},
),
));
let table = table_of(
vec![
vec![plain_cell("ordinary text")],
vec![TableCell {
children: Paragraph {
children: vec![InlineNode::custom(MarkdownNode::new("test", ()).text("x"))],
..Default::default()
},
width: None,
}],
],
vec![],
);
in_prepaint(&mut app, move |window, cx| {
let mut cached = None;
for expected in [400, 600, 10, 400] {
width.store(expected, std::sync::atomic::Ordering::Relaxed);
let measured = measure_table_columns(&table, 1, &node_cx, window, cx)[0];
let current = cached_column_widths(&table);
assert_eq!(
measured,
current.widths[0].max(expected as f32 + CELL_PAD_PX)
);
assert_eq!(current.custom_cells, vec![(1, 0)]);
if let Some(cached) = cached.replace(current.clone()) {
assert!(Arc::ptr_eq(&cached, ¤t));
}
}
});
}
fn cached_column_widths(table: &Table) -> Arc {
table.column_widths_cache.0.lock().unwrap().clone().unwrap()
}
#[test]
fn table_columns_cache_preserves_plain_widths_and_clones() {
use crate::text::inline::test_draw::in_prepaint;
use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem, record_shaped_lines};
use gpui::{Refineable as _, TestApp, TextStyle};
let long = "é界".repeat(2048);
let table = table_of(
vec![
vec![plain_cell(&format!(" \t{long} \nshort\n ")), plain_cell("")],
vec![plain_cell("short")],
vec![],
vec![plain_cell(""), plain_cell("a\nabcdefghijklmnop")],
],
vec![],
);
let uncached = table.clone();
let node_cx = NodeContext::default();
let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
let (table, node_cx, cached) = in_prepaint(&mut app, move |window, cx| {
window.set_rem_size(px(20.));
let style = TextStyle {
font_family: BODY.into(),
font_size: rems(1.).into(),
..Default::default()
};
let cached =
window.with_text_style(Some(style.subtract(&Default::default())), |window| {
let (widths, shaped) = record_shaped_lines(|| {
measure_table_columns(&table, 2, &node_cx, window, cx)
});
assert_eq!(widths, vec![40960. + CELL_PAD_PX + CELL_BORDER_PX, 176.]);
assert!(shaped.iter().any(|line| line == &long));
assert_eq!(
table, uncached,
"derived widths do not change table equality"
);
assert!(uncached.column_widths_cache.0.lock().unwrap().is_none());
let cached = cached_column_widths(&table);
let cloned = table.clone();
for same in [&table, &cloned] {
let (again, shaped) = record_shaped_lines(|| {
measure_table_columns(same, 2, &node_cx, window, cx)
});
assert_eq!(again, widths);
assert!(shaped.is_empty());
assert!(Arc::ptr_eq(&cached, &cached_column_widths(same)));
}
// A different column count changes which cells draw borders.
assert_eq!(
measure_table_columns(&cloned, 3, &node_cx, window, cx),
vec![widths[0], widths[1] + CELL_BORDER_PX, CELL_MIN_PX]
);
assert!(!Arc::ptr_eq(&cached, &cached_column_widths(&cloned)));
assert!(Arc::ptr_eq(&cached, &cached_column_widths(&table)));
assert!(
measure_table_columns(&Table::default(), 0, &node_cx, window, cx)
.is_empty()
);
cached
});
(table, node_cx, cached)
});
// A parsed table can be rendered in another window. Do not reuse a
// pixel-width cache from a different window's text system.
in_prepaint(&mut app, move |window, cx| {
window.set_rem_size(cached.rem_size);
window.with_text_style(
Some(cached.text_style.subtract(&Default::default())),
|window| {
measure_table_columns(&table, 2, &node_cx, window, cx);
assert!(!Arc::ptr_eq(&cached, &cached_column_widths(&table)));
},
);
});
}
#[test]
fn table_columns_cache_tracks_typography() {
use crate::text::inline::test_draw::in_prepaint;
use crate::text::inline::test_fonts::{BODY, MONO, WideMonoTextSystem};
use gpui::{Refineable as _, TestApp, TextStyle};
let code = "0123456789";
let mut paragraph = Paragraph::default();
paragraph
.push(InlineNode::new(code).marks(vec![(0..code.len(), TextMark::default().code())]));
let table = table_of(
vec![vec![
plain_cell(code),
TableCell {
children: paragraph,
width: None,
},
]],
vec![],
);
let base = TextStyle {
font_family: BODY.into(),
font_size: rems(1.).into(),
..Default::default()
};
let mut larger = base.clone();
larger.font_size = rems(2.).into();
let mut bold = base.clone();
bold.font_weight = FontWeight::BOLD;
let mut mono = base.clone();
mono.font_family = MONO.into();
let normal_code = HighlightStyle::default();
let bold_code = HighlightStyle {
font_weight: Some(FontWeight::BOLD),
..Default::default()
};
let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
in_prepaint(&mut app, move |window, cx| {
let mut previous = None;
for (style, rem_size, family, inline_code, expected) in [
(base.clone(), 20., MONO, normal_code, [117., 195.]),
(base.clone(), 30., MONO, normal_code, [167., 282.5]),
(larger, 20., MONO, normal_code, [217., 370.]),
(bold, 20., MONO, normal_code, [167., 238.75]),
(mono, 20., MONO, normal_code, [217., 195.]),
(base.clone(), 20., MONO, normal_code, [117., 195.]),
(base.clone(), 20., BODY, normal_code, [117., 107.5]),
(base.clone(), 20., MONO, normal_code, [117., 195.]),
(base, 20., MONO, bold_code, [117., 238.75]),
] {
let mut theme = crate::Theme::default();
theme.tokens.typography.mono = family.into();
cx.set_global(theme);
window.set_rem_size(px(rem_size));
let node_cx = NodeContext {
style: Arc::new(TextViewStyle::default().with_inline_code(inline_code)),
..Default::default()
};
window.with_text_style(Some(style.subtract(&Default::default())), |window| {
let widths = measure_table_columns(&table, 2, &node_cx, window, cx);
for (width, expected) in widths.iter().zip(expected) {
assert!((width - expected).abs() < 0.01, "{width} != {expected}");
}
let cached = cached_column_widths(&table);
if let Some(previous) = previous.replace(cached.clone()) {
assert!(!Arc::ptr_eq(&previous, &cached));
}
assert_eq!(
measure_table_columns(&table, 2, &node_cx, window, cx),
widths
);
assert!(Arc::ptr_eq(&cached, &cached_column_widths(&table)));
});
}
});
}
#[test]
fn table_columns_cache_is_rebuilt_for_reparsed_tables() {
use crate::text::format::markdown;
use crate::text::inline::test_draw::in_prepaint;
use crate::text::inline::test_fonts::{BODY, WideMonoTextSystem};
use gpui::{Refineable as _, TestApp, TextStyle};
let mut node_cx = NodeContext::default();
let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
in_prepaint(&mut app, move |window, cx| {
let style = TextStyle {
font_family: BODY.into(),
font_size: px(20.).into(),
..Default::default()
};
window.with_text_style(Some(style.subtract(&Default::default())), |window| {
let mut previous = None;
for (text, expected) in [("longer cell", 126.), ("x", CELL_MIN_PX)] {
let source = format!("| h |\n| - |\n| {text} |\n");
let document = markdown::parse(&source, &mut node_cx).unwrap();
let BlockNode::Table(table) = &document.blocks[0] else {
panic!("expected a parsed table");
};
assert!(table.column_widths_cache.0.lock().unwrap().is_none());
assert_eq!(
measure_table_columns(table, 1, &node_cx, window, cx),
vec![expected]
);
let cached = cached_column_widths(table);
if let Some(previous) = previous.replace(cached.clone()) {
assert!(!Arc::ptr_eq(&previous, &cached));
}
assert_eq!(document.source.as_ref(), source);
}
});
});
}
/// Table columns are sized from shaped text, so a column of inline code
/// has to be measured in the code family. Measured in the body font, the
/// wide-mono test font makes `col_w` come out at half the rendered width.
#[test]
fn table_column_of_inline_code_cells_fits_the_mono_width() {
use crate::text::inline::test_fonts::{MONO, WideMonoTextSystem};
use gpui::{Empty, TestApp};
let code = "method_name()";
let mut paragraph = Paragraph::default();
paragraph
.push(InlineNode::new(code).marks(vec![(0..code.len(), TextMark::default().code())]));
let table = Table {
children: vec![TableRow {
children: vec![TableCell {
children: paragraph,
width: None,
}],
}],
column_aligns: vec![],
span: None,
table_data_cache: TableDataCache::default(),
column_widths_cache: TableColumnWidthsCache::default(),
};
let node_cx = NodeContext::default();
let mut app = TestApp::with_text_system(Arc::new(WideMonoTextSystem));
let mut window = app.open_window(|_, _| Empty);
let (col_w, font_size) = window.update(|_, window, cx| {
let mut theme = crate::Theme::default();
theme.tokens.typography.mono = MONO.into();
cx.set_global(theme);
let font_size = window.text_style().font_size.to_pixels(window.rem_size());
(
measure_table_columns(&table, 1, &node_cx, window, cx),
font_size,
)
});
let mono_w = f32::from(WideMonoTextSystem::width_of(code, MONO, font_size * 0.875));
assert!(
(col_w[0]
- (mono_w + CELL_PAD_PX + crate::text::inline_flow::INLINE_CODE_PADDING * 2.))
.abs()
< 0.01,
"col_w {} must fit the mono width {} plus padding {}",
col_w[0],
mono_w,
CELL_PAD_PX
);
}
#[test]
fn code_block_highlights_are_cached_by_highlighter_identity() {
use std::sync::atomic::{AtomicUsize, Ordering};
let calls = Arc::new(AtomicUsize::new(0));
let calls_for_highlighter = calls.clone();
let highlighter: Arc = Arc::new(move |_| {
calls_for_highlighter.fetch_add(1, Ordering::Relaxed);
Vec::new()
});
let block = CodeBlock::new("fn main() {}".into(), Some("rust".into()), None::);
block.highlighted_styles(&highlighter);
block.highlighted_styles(&highlighter);
assert_eq!(calls.load(Ordering::Relaxed), 1);
let replacement: Arc = Arc::new(|_| Vec::new());
block.highlighted_styles(&replacement);
assert!(Arc::ptr_eq(
&block
.highlight_cache
.lock()
.unwrap()
.as_ref()
.unwrap()
.highlighter,
&replacement
));
}
#[test]
fn a_new_highlighter_replaces_styles_instead_of_reusing_the_cache() {
// Swapping the highlighter is how a theme change reaches a code block:
// the parsed document is untouched, so the styles must come from the
// new highlighter rather than from the styles cached for the old one.
let light: Arc = Arc::new(|_| {
vec![(
0..2,
HighlightStyle {
color: Some(gpui::rgb(0x0000ff).into()),
..Default::default()
},
)]
});
let dark: Arc = Arc::new(|_| {
vec![(
0..2,
HighlightStyle {
color: Some(gpui::rgb(0xffff00).into()),
..Default::default()
},
)]
});
let block = CodeBlock::from_code("42", Some("json"));
let light_styles = block.highlighted_styles(&light);
let dark_styles = block.highlighted_styles(&dark);
assert_eq!(light_styles[0].1.color, Some(gpui::rgb(0x0000ff).into()));
assert_eq!(dark_styles[0].1.color, Some(gpui::rgb(0xffff00).into()));
assert_eq!(block.code(), "42", "the document must survive the swap");
}
#[test]
fn reconstruct_markdown_wraps_marked_runs() {
// "bold" fully covered by a bold mark.
let marks = vec![(0..4, TextMark::default().bold())];
assert_eq!(reconstruct_markdown("bold", &marks, 0..4), "**bold**");
// Partial selection inside the bold run still wraps the slice.
assert_eq!(reconstruct_markdown("bold", &marks, 1..3), "**ol**");
}
#[test]
fn reconstruct_markdown_emits_unmarked_text_verbatim() {
// "a b c": plain, code, plain across three runs concatenated.
let text = "a b c";
let marks = vec![(2..3, TextMark::default().code())];
assert_eq!(reconstruct_markdown(text, &marks, 0..5), "a `b` c");
// Selecting only the plain tail.
assert_eq!(reconstruct_markdown(text, &marks, 3..5), " c");
}
#[test]
fn reconstruct_markdown_handles_code_italic_strike_link() {
assert_eq!(
reconstruct_markdown("x", &[(0..1, TextMark::default().code())], 0..1),
"`x`"
);
assert_eq!(
reconstruct_markdown("x", &[(0..1, TextMark::default().italic())], 0..1),
"*x*"
);
assert_eq!(
reconstruct_markdown("x", &[(0..1, TextMark::default().strikethrough())], 0..1),
"~~x~~"
);
let link = TextMark::default().link(LinkMark {
url: "https://example.com".into(),
..Default::default()
});
assert_eq!(
reconstruct_markdown("x", &[(0..1, link)], 0..1),
"[x](https://example.com)"
);
}
#[test]
fn reconstruct_markdown_nested_bold_italic() {
// A single run marked both bold and italic (as produced by `**_x_**`).
let mark = TextMark::default().bold().italic();
// Inner (italic) is applied first, then bold: `***x***`.
assert_eq!(reconstruct_markdown("x", &[(0..1, mark)], 0..1), "***x***");
}
/// Build a paragraph whose combined `state.text` is the concatenation of
/// its children (mirroring `Paragraph::render`), then set the paragraph
/// selection so `selected_source` can be exercised without a real paint.
fn paragraph_with_children(children: Vec) -> Paragraph {
let combined: String = children.iter().map(|c| c.text.to_string()).collect();
let paragraph = Paragraph {
span: None,
children,
link_refs: HashMap::new(),
state: Arc::new(Mutex::new(InlineState::default())),
render_cache: ParagraphRenderCache::default(),
};
if let Ok(mut state) = paragraph.state.lock() {
state.set_text(combined.into());
}
paragraph
}
fn set_paragraph_selection(paragraph: &Paragraph, range: Range) {
if let Ok(mut state) = paragraph.state.lock() {
state.selection = Some(range.into());
}
}
#[test]
fn paragraph_selected_source_maps_partial_selection_across_runs() {
// "This has **bold** text." rendered as ["This has ", "bold", " text."].
let children = vec![
InlineNode::new("This has ").marks(vec![(0..9, TextMark::default())]),
InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
InlineNode::new(" text.").marks(vec![(0..6, TextMark::default())]),
];
let paragraph = paragraph_with_children(children);
// Select the whole paragraph: "This has bold text." -> source with **.
set_paragraph_selection(¶graph, 0..(9 + 4 + 6));
assert_eq!(paragraph.selected_source(), "This has **bold** text.");
// Select only across the boundary "has **bold** te".
// Rendered offsets: "has " starts at 5, "bold" at 9..13, " te" 13..16.
set_paragraph_selection(¶graph, 5..16);
assert_eq!(paragraph.selected_source(), "has **bold** te");
// Select entirely inside the bold run -> still wrapped.
set_paragraph_selection(¶graph, 10..12);
assert_eq!(paragraph.selected_source(), "**ol**");
}
#[test]
fn paragraph_selected_source_matches_text_when_no_marks() {
let children =
vec![InlineNode::new("plain words").marks(vec![(0..11, TextMark::default())])];
let paragraph = paragraph_with_children(children);
set_paragraph_selection(¶graph, 0..11);
assert_eq!(paragraph.selected_source(), "plain words");
assert_eq!(paragraph.selected_text(), "plain words");
}
fn selected_paragraph(text: &str) -> Paragraph {
let len = text.len();
let paragraph = paragraph_with_children(vec![
InlineNode::new(text).marks(vec![(0..len, TextMark::default())]),
]);
set_paragraph_selection(¶graph, 0..len);
paragraph
}
#[test]
fn heading_selected_source_prefixes_hashes() {
let heading = BlockNode::Heading {
level: 2,
children: selected_paragraph("Title"),
span: None,
};
assert_eq!(heading.selected_text(SelectionFormat::Source), "## Title\n");
// Rendered text keeps no marker.
assert_eq!(heading.selected_text(SelectionFormat::Plain), "Title\n");
}
#[test]
fn unordered_list_selected_source_prefixes_dash() {
let list = BlockNode::List {
ordered: false,
start: None,
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
spread: false,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
spread: false,
checked: None,
span: None,
},
],
};
assert_eq!(
list.selected_text(SelectionFormat::Source),
"- one\n- two\n"
);
}
#[test]
fn ordered_list_selected_source_preserves_start() {
let list = BlockNode::List {
ordered: true,
start: Some(3),
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("three"))],
spread: false,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
spread: false,
checked: None,
span: None,
},
],
};
assert_eq!(list.to_markdown(), "3. three\n4. four");
assert_eq!(
list.selected_text(SelectionFormat::Source),
"3. three\n4. four\n"
);
}
#[test]
fn ordered_list_selected_source_preserves_nested_starts_and_continuations() {
let nested = BlockNode::List {
ordered: true,
start: Some(4),
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
spread: false,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("again"))],
spread: false,
checked: None,
span: None,
},
],
};
let nested_list = BlockNode::List {
ordered: true,
start: Some(3),
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("three")), nested],
spread: false,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
spread: false,
checked: None,
span: None,
},
],
};
assert_eq!(
nested_list.selected_text(SelectionFormat::Source),
"3. three\n 4. nested\n 5. again\n4. four\n"
);
let loose_list = BlockNode::List {
ordered: true,
start: Some(3),
span: None,
children: vec![
BlockNode::ListItem {
children: vec![
BlockNode::Paragraph(selected_paragraph("loose")),
BlockNode::Paragraph(selected_paragraph("continuation")),
],
spread: true,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("four"))],
spread: false,
checked: None,
span: None,
},
],
};
assert_eq!(
loose_list.selected_text(SelectionFormat::Source),
"3. loose\n continuation\n4. four\n"
);
}
#[test]
fn nested_list_selected_source_indents_sublists() {
// - one
// - nested
// - two
let nested = BlockNode::List {
ordered: false,
start: None,
span: None,
children: vec![BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("nested"))],
spread: false,
checked: None,
span: None,
}],
};
let list = BlockNode::List {
ordered: false,
start: None,
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("one")), nested],
spread: false,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
spread: false,
checked: None,
span: None,
},
],
};
assert_eq!(
list.selected_text(SelectionFormat::Source),
"- one\n - nested\n- two\n"
);
}
#[test]
fn task_list_selected_source_restores_checkboxes() {
let list = BlockNode::List {
ordered: false,
start: None,
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("done"))],
spread: false,
checked: Some(true),
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("todo"))],
spread: false,
checked: Some(false),
span: None,
},
],
};
assert_eq!(
list.selected_text(SelectionFormat::Source),
"- [x] done\n- [ ] todo\n"
);
}
#[test]
fn blockquote_selected_source_prefixes_gt() {
let quote = BlockNode::Blockquote {
span: None,
children: vec![BlockNode::Paragraph(selected_paragraph("quoted text"))],
};
assert_eq!(
quote.selected_text(SelectionFormat::Source),
"> quoted text\n"
);
}
#[test]
fn table_selected_source_pipes_cells_with_alignment_row() {
let cell = |text: &str| TableCell {
children: selected_paragraph(text),
width: None,
};
let table = Table {
children: vec![
TableRow {
children: vec![cell("Name"), cell("Age")],
},
TableRow {
children: vec![cell("Alice"), cell("30")],
},
],
column_aligns: vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
span: None,
table_data_cache: TableDataCache::default(),
column_widths_cache: TableColumnWidthsCache::default(),
};
let block = BlockNode::Table(table);
assert_eq!(
block.selected_text(SelectionFormat::Source),
"| Name | Age |\n| :-- | --: |\n| Alice | 30 |\n"
);
}
/// A cell holding plain text, as `Table::to_markdown` and
/// `Table::table_data` see it (neither needs a selection).
fn plain_cell(text: &str) -> TableCell {
TableCell {
children: Paragraph::new(text.to_string()),
width: None,
}
}
fn table_of(rows: Vec>, column_aligns: Vec) -> Table {
Table {
children: rows
.into_iter()
.map(|children| TableRow { children })
.collect(),
column_aligns,
span: None,
table_data_cache: TableDataCache::default(),
column_widths_cache: TableColumnWidthsCache::default(),
}
}
#[test]
fn table_to_markdown_pipes_cells_with_alignment_row() {
let table = table_of(
vec![
vec![plain_cell("Name"), plain_cell("Age"), plain_cell("Score")],
vec![plain_cell("Alice"), plain_cell("30"), plain_cell("9.5")],
],
vec![
ColumnumnAlign::Left,
ColumnumnAlign::Center,
ColumnumnAlign::Right,
],
);
assert_eq!(
table.to_markdown(),
"| Name | Age | Score |\n| :-- | :-: | --: |\n| Alice | 30 | 9.5 |"
);
// The block arm delegates to it.
assert_eq!(
BlockNode::Table(table.clone()).to_markdown(),
table.to_markdown()
);
}
#[test]
fn table_to_markdown_keeps_outer_pipes_for_a_single_column() {
let table = table_of(
vec![vec![plain_cell("Symbol")], vec![plain_cell("TSLA.US")]],
vec![ColumnumnAlign::Left],
);
assert_eq!(table.to_markdown(), "| Symbol |\n| :-- |\n| TSLA.US |");
}
#[test]
fn table_to_markdown_escapes_pipes_and_keeps_inline_marks() {
let bold = TableCell {
children: paragraph_with_children(vec![
InlineNode::new("bold").marks(vec![(0..4, TextMark::default().bold())]),
]),
width: None,
};
let table = table_of(
vec![
vec![plain_cell("a | b"), plain_cell("plain")],
vec![plain_cell("c"), bold],
],
vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
);
assert_eq!(
table.to_markdown(),
"| a \\| b | plain |\n| :-- | :-- |\n| c | **bold** |"
);
}
#[test]
fn table_data_snapshots_plain_cells_and_markdown() {
let mut table = table_of(
vec![
vec![plain_cell(" Name "), plain_cell("Age")],
vec![plain_cell("Alice"), plain_cell("30")],
],
vec![ColumnumnAlign::Left, ColumnumnAlign::Right],
);
table.span = Some(Span { start: 4, end: 42 });
let data = table.table_data();
assert_eq!(data.headers, vec!["Name", "Age"]);
assert_eq!(data.rows, vec![vec!["Alice", "30"]]);
assert_eq!(data.markdown, table.to_markdown());
assert_eq!(data.span, Some(4..42));
}
#[test]
fn cloned_table_keeps_cached_table_data() {
// Streaming appends deep-clone every block; the clone must reuse the
// cached snapshot instead of rebuilding it.
let table = table_of(
vec![vec![plain_cell("Name")], vec![plain_cell("Alice")]],
vec![ColumnumnAlign::Left],
);
let data = table.cached_table_data();
let cloned = table.clone();
assert!(Arc::ptr_eq(&data, &cloned.cached_table_data()));
}
#[test]
fn table_data_handles_tables_without_rows() {
// Header only: still a valid table, with no data rows.
let header_only = table_of(
vec![vec![plain_cell("Name"), plain_cell("Age")]],
vec![ColumnumnAlign::Left, ColumnumnAlign::Left],
);
let data = header_only.table_data();
assert_eq!(data.headers, vec!["Name", "Age"]);
assert!(data.rows.is_empty());
assert_eq!(data.markdown, "| Name | Age |\n| :-- | :-- |");
// No rows at all (a table still streaming in): an empty snapshot.
assert_eq!(Table::default().table_data(), TableData::default());
}
#[test]
fn test_image_node_source() {
use gpui::{ImageFormat, ImageSource, Resource};
fn image_node(url: &str) -> ImageNode {
ImageNode {
url: url.into(),
..Default::default()
}
}
// Document-provided values stay URI-backed, including `file://` and
// scheme-less strings, so the document never gets implicit
// filesystem access through `Resource::Embedded`.
fn assert_uri(url: &str) {
match image_node(url).source() {
ImageSource::Resource(Resource::Uri(uri)) => assert_eq!(uri.as_ref(), url),
_ => panic!("expected Uri for {url:?}"),
}
}
assert_uri("https://example.com/logo.png");
assert_uri("http://example.com/logo.png");
assert_uri("website/public/logo.svg");
assert_uri("./images/a.png");
assert_uri("../images/a.png");
assert_uri("/absolute/path/logo.svg");
assert_uri("file:///absolute/path/logo.svg");
assert_uri(r"C:\images\logo.png");
assert_uri("docs/a:b.png");
assert_uri("data:text/plain;base64,aGVsbG8=");
// A `data:` image is decoded once and the same decoded image is
// handed to every render.
let node = image_node("data:image/png;base64,iVBORw0KGgo=");
let ImageSource::Image(first) = node.source() else {
panic!("expected an embedded image");
};
assert_eq!(first.format(), ImageFormat::Png);
assert_eq!(first.bytes(), b"\x89PNG\r\n\x1a\n");
let ImageSource::Image(second) = node.source() else {
panic!("expected an embedded image");
};
assert!(Arc::ptr_eq(&first, &second));
}
fn image_paragraph(alt: &str, url: &str) -> Paragraph {
let image = ImageNode {
url: url.into(),
alt: Some(alt.into()),
..Default::default()
};
Paragraph {
span: None,
children: vec![InlineNode::image(image)],
link_refs: HashMap::new(),
state: Arc::new(Mutex::new(InlineState::default())),
render_cache: ParagraphRenderCache::default(),
}
}
/// Every mark round-trips, including the two Markdown has no plain syntax
/// for.
#[test]
fn marks_round_trip_through_reconstruction() {
let wrap = |mark: TextMark| reconstruct_markdown("x", &[(0..1, mark)], 0..1);
assert_eq!(wrap(TextMark::default().bold()), "**x**");
assert_eq!(wrap(TextMark::default().italic()), "*x*");
assert_eq!(wrap(TextMark::default().code()), "`x`");
assert_eq!(wrap(TextMark::default().strikethrough()), "~~x~~");
assert_eq!(
wrap(TextMark::default().highlight(gpui::rgb(0xfef08a).into())),
"==x=="
);
// No Markdown syntax for underline, so it keeps the tag it came from.
assert_eq!(wrap(TextMark::default().underline()), "x");
// A link keeps its title, which Markdown carries after the URL.
assert_eq!(
wrap(TextMark::default().link(LinkMark {
url: "https://example.com".into(),
title: Some("Tip".into()),
..Default::default()
})),
"[x](https://example.com \"Tip\")"
);
}
/// A block the selection covers whole comes straight from the source, so it
/// keeps what the author wrote instead of a normalized reconstruction.
#[test]
fn document_selected_source_slices_covered_blocks_from_the_source() {
use crate::text::document::ParsedDocument;
// `_italic_`, the `3.` start and the column padding all survive only
// because the block is copied, not rebuilt.
let source = "start\n\n3. _one_\n4. two\n\n---\n\nend";
let list = "3. _one_\n4. two";
let list_start = source.find(list).unwrap();
let rule_start = source.find("---").unwrap();
let document = ParsedDocument {
source: source.into(),
blocks: vec![
BlockNode::Paragraph(selected_paragraph("start")),
BlockNode::List {
ordered: true,
start: Some(3),
children: vec![],
span: Some(Span {
start: list_start,
end: list_start + list.len(),
}),
},
BlockNode::HorizontalRule {
span: Some(Span {
start: rule_start,
end: rule_start + 3,
}),
},
BlockNode::Paragraph(selected_paragraph("end")),
]
.into(),
};
assert_eq!(
document.selected_text(SelectionFormat::Source, None),
"start\n\n3. _one_\n4. two\n\n---\n\nend"
);
}
#[test]
fn document_selected_source_includes_enclosed_image() {
use crate::text::document::ParsedDocument;
// A standalone image between two selected paragraphs is covered by the
// selection, so it is copied whole even though it holds no selection of
// its own — straight out of the source the parser located it in.
let source = "before\n\n\n\nafter";
let image_markdown = "";
let start = source.find(image_markdown).unwrap();
let mut image = image_paragraph("alt", "https://example.com/i.png");
image.span = Some(Span {
start,
end: start + image_markdown.len(),
});
let document = ParsedDocument {
source: source.into(),
blocks: vec![
BlockNode::Paragraph(selected_paragraph("before")),
BlockNode::Paragraph(image),
BlockNode::Paragraph(selected_paragraph("after")),
]
.into(),
};
assert_eq!(
document.selected_text(SelectionFormat::Source, None),
"before\n\n\n\nafter"
);
}
#[test]
fn document_selected_source_drops_unenclosed_image() {
use crate::text::document::ParsedDocument;
// An image after the only selected block, with nothing selected after
// it, is not enclosed and is dropped.
let document = ParsedDocument {
source: String::new().into(),
blocks: vec![
BlockNode::Paragraph(selected_paragraph("before")),
BlockNode::Paragraph(image_paragraph("alt", "u")),
]
.into(),
};
assert_eq!(
document.selected_text(SelectionFormat::Source, None),
"before"
);
}
fn selected_code_block(code: &str, lang: Option<&str>) -> BlockNode {
let block = CodeBlock::new(
code.to_string().into(),
lang.map(|l| l.to_string().into()),
None::,
);
if let Ok(mut state) = block.state.lock() {
let len = state.text.len();
state.selection = Some((0..len).into());
}
BlockNode::CodeBlock(block)
}
#[test]
fn code_block_selected_source_wraps_in_fence_with_lang() {
let block = selected_code_block("let x = 1;\n", Some("rust"));
let code = block.selected_text(SelectionFormat::Plain);
let code_trimmed = code.trim_end_matches('\n');
// The source wraps the (trailing-newline-trimmed) selected code in a
// fenced block carrying the language; the block arm adds one trailing
// newline.
assert_eq!(
block.selected_text(SelectionFormat::Source),
format!("```rust\n{}\n```\n", code_trimmed)
);
assert!(
block
.selected_text(SelectionFormat::Source)
.starts_with("```rust\n")
);
assert!(
block
.selected_text(SelectionFormat::Source)
.trim_end()
.ends_with("\n```")
);
}
#[test]
fn code_block_selected_source_without_lang() {
let block = selected_code_block("plain\n", None);
let code_trimmed = block.selected_text(SelectionFormat::Plain);
let code_trimmed = code_trimmed.trim_end_matches('\n');
assert_eq!(
block.selected_text(SelectionFormat::Source),
format!("```\n{}\n```\n", code_trimmed)
);
}
#[test]
fn document_selected_source_joins_blocks_with_blank_line() {
use crate::text::document::ParsedDocument;
// A heading, a paragraph, and a two-item ordered list, each fully
// selected. Top-level blocks must be separated by a blank line so the
// copied Markdown re-renders with the same structure.
let document = ParsedDocument {
source: String::new().into(),
blocks: vec![
BlockNode::Heading {
level: 1,
children: selected_paragraph("Title"),
span: None,
},
BlockNode::Paragraph(selected_paragraph("A paragraph.")),
selected_code_block("let x = 1;\n", Some("rust")),
BlockNode::List {
ordered: true,
start: Some(1),
span: None,
children: vec![
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("one"))],
spread: false,
checked: None,
span: None,
},
BlockNode::ListItem {
children: vec![BlockNode::Paragraph(selected_paragraph("two"))],
spread: false,
checked: None,
span: None,
},
],
},
]
.into(),
};
assert_eq!(
document.selected_text(SelectionFormat::Source, None),
"# Title\n\nA paragraph.\n\n```rust\nlet x = 1;\n```\n\n1. one\n2. two"
);
}
#[test]
fn code_block_equality_includes_code_content() {
let first = CodeBlock::new("let value = 1;".into(), Some("rust".into()), None::);
let second = CodeBlock::new("let value = 2;".into(), Some("rust".into()), None::);
assert_ne!(first, second);
}
}