Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
32 changes: 31 additions & 1 deletion src/render.rs
Original file line number Diff line number Diff line change
Expand Up @@ -18,12 +18,29 @@ pub fn render(results: &[DiffResult]) -> String {
out.push_str(PREAMBLE);
out.push('\n');

for result in results {
let mut results = results.iter().peekable();
while let Some(result) = results.next() {
match result {
DiffResult::Unchanged(block) => {
render_block(block, &mut out);
out.push('\n');
}
// A label after the wrapper would label the styled wrapper, which
// cannot be referenced. Keep it inside, next to the equation.
DiffResult::Added(Block::Equation { content, .. })
if results
.peek()
.is_some_and(|next| next_label(next).is_some()) =>
{
let label = results.next().and_then(next_label).unwrap();
write!(
out,
"#diff-added[{} {label}]",
escape_content(content, false)
)
.unwrap();
out.push('\n');
}
DiffResult::Added(block) => {
render_added_or_deleted(block, DiffTag::Added, &mut out);
out.push('\n');
Expand Down Expand Up @@ -95,6 +112,19 @@ fn is_label_only(text: &str) -> bool {
TypstLabel::is_only(text)
}

/// Returns the label if this result is a label that will be output bare.
fn next_label(result: &DiffResult) -> Option<&str> {
match result {
DiffResult::Unchanged(Block::Paragraph { source_text })
| DiffResult::Added(Block::Paragraph { source_text })
if is_label_only(source_text) =>
{
Some(source_text.trim())
}
_ => None,
}
}

/// Render a block wrapped in #diff-added[...] or #diff-deleted[...].
fn render_added_or_deleted(block: &Block, tag: DiffTag, out: &mut String) {
let escape_refs = tag == DiffTag::Deleted;
Expand Down
12 changes: 12 additions & 0 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -209,3 +209,15 @@ fn test_indented_line_comment_does_not_split_paragraph() {
// A whitespace-only line would be treated as a paragraph break by Typst.
assert!(!output.contains("\n \n"));
}

#[test]
fn test_label_after_changed_equation_stays_on_equation() {
let old = "#set math.equation(numbering: \"(1)\")\n\n$ x = 1 $ <eq-main>\n\nSee @eq-main.\n";
let new = "#set math.equation(numbering: \"(1)\")\n\n$ x = 2 $ <eq-main>\n\nSee @eq-main.\n";
let output = run_diff(old, new);

// Outside the wrapper the label would attach to the styled wrapper, and
// `@eq-main` would fail with "cannot reference styled".
assert!(output.contains("#diff-added[$ x = 2 $ <eq-main>]"));
assert!(!output.contains("\n<eq-main>\n"));
}