Skip to content
Merged
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
81 changes: 79 additions & 2 deletions src/diff.rs
Original file line number Diff line number Diff line change
Expand Up @@ -137,8 +137,9 @@ fn process_replace(old_range: &[Block], new_range: &[Block], results: &mut Vec<D
/// individual single-character token.
///
/// Typst code expressions (`#func[...]`, `#func(...)`), references (`@label`),
/// and labels (`<label>`) are treated as atomic tokens so the diff never
/// fragments valid Typst syntax.
/// labels (`<label>`), inline equations (`$...$`), and escape sequences
/// (`\x`) are treated as atomic tokens so the diff never fragments valid
/// Typst syntax.
///
/// This gives word-level granularity for Latin text while allowing
/// character-level precision for CJK text (which has no whitespace boundaries).
Expand Down Expand Up @@ -180,6 +181,21 @@ fn tokenize_mixed(s: &str) -> Vec<&str> {
// Standalone '#'
tokens.push(&s[start..i]);
}
} else if c == '$' {
// Inline equation: keep `$...$` as one atomic token. An unclosed
// `$` falls back to a single-character token, like `<label>`.
let start = i;
i += find_closing_dollar(&s[start..]).unwrap_or(c_len);
Comment thread
Yuan-Ru-Lin marked this conversation as resolved.
Resolved
tokens.push(&s[start..i]);
} else if c == '\\' {
// Escape sequence: keep `\x` as one token so an escaped `$` in
// markup never opens an equation.
let start = i;
i += c_len;
if let Some(next) = s[i..].chars().next() {
i += next.len_utf8();
}
Comment thread
sou1118 marked this conversation as resolved.
Resolved
tokens.push(&s[start..i]);
} else if c == '@' {
// Typst reference: @label (alphanumeric, hyphens, underscores, colons, periods)
let start = i;
Expand Down Expand Up @@ -253,6 +269,27 @@ fn skip_balanced(s: &str, start: usize, open: char, close: char) -> usize {
i
}

/// Byte length of the inline equation at the start of `s`, if it is closed.
///
/// `s` must start with `$`. Scans forward for the matching `$`, skipping
/// escaped characters (`\$`) and quoted strings (`"a $ b"`), since a `$`
/// inside either does not end the equation. Returns `None` when unclosed.
fn find_closing_dollar(s: &str) -> Option<usize> {
let mut in_string = false;
let mut chars = s.char_indices().skip(1);
while let Some((i, c)) = chars.next() {
match c {
'\\' => {
chars.next();
}
'"' => in_string = !in_string,
'$' if !in_string => return Some(i + c.len_utf8()),
_ => {}
Comment thread
Yuan-Ru-Lin marked this conversation as resolved.
Resolved
}
}
None
}

/// Perform mixed-granularity diff and return coalesced spans.
///
/// Uses a custom tokenizer that splits CJK characters individually while
Expand Down Expand Up @@ -543,6 +580,46 @@ mod tests {
assert_eq!(tokens, vec!["<sample-widget_anchor>"]);
}

#[test]
fn test_tokenize_inline_equation_is_atomic() {
let tokens = tokenize_mixed("is $t = 12.4 \"hour\"$ for");
assert_eq!(tokens, vec!["is", " ", "$t = 12.4 \"hour\"$", " ", "for"]);
}

#[test]
fn test_tokenize_escaped_dollar_in_markup_is_not_an_equation() {
let tokens = tokenize_mixed("\\$5 and $x$");
assert_eq!(tokens, vec!["\\$", "5", " ", "and", " ", "$x$"]);
}

#[test]
fn test_tokenize_escaped_dollar_inside_equation() {
let tokens = tokenize_mixed("$x \\$ y$");
assert_eq!(tokens, vec!["$x \\$ y$"]);
}

#[test]
fn test_tokenize_quoted_dollar_inside_equation() {
let tokens = tokenize_mixed("Text $\"a $ b\"$ end");
assert_eq!(tokens, vec!["Text", " ", "$\"a $ b\"$", " ", "end"]);
}

#[test]
fn test_tokenize_unclosed_dollar_is_single_token() {
let tokens = tokenize_mixed("Use `$HOME` now");
assert_eq!(tokens, vec!["Use", " ", "`", "$", "HOME", "`", " ", "now"]);
}

#[test]
fn test_find_closing_dollar() {
assert_eq!(find_closing_dollar("$x$ y"), Some(3));
assert_eq!(find_closing_dollar("$a \\$ b$"), Some(8));
assert_eq!(find_closing_dollar("$\"a $ b\"$"), Some(9));
assert_eq!(find_closing_dollar("$\"a \\\" $ b\"$"), Some(12));
assert_eq!(find_closing_dollar("$x"), None);
assert_eq!(find_closing_dollar("$\"a $ b"), None);
}

#[test]
fn test_tokenize_cjk_char_level() {
// CJK characters should be tokenized individually (no whitespace boundaries).
Expand Down
19 changes: 19 additions & 0 deletions tests/integration.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@ use typdiff::diff::diff;
use typdiff::parse::parse;
use typdiff::render::render;

/// True when the rendered output is syntactically valid Typst.
fn parses(rendered: &str) -> bool {
!typst_syntax::parse(rendered).erroneous()
}

fn run_diff(old: &str, new: &str) -> String {
let old_blocks: Vec<_> = parse(old)
.into_iter()
Expand Down Expand Up @@ -123,6 +128,20 @@ fn test_inline_footnote_ref_to_funccall() {
);
}

#[test]
fn test_inline_equation_is_deleted_whole() {
// Issue #25: the spaces inside the equation used to align with spaces in
// the new sentence, leaving `$t` and `"hour"$` in separate deletion blocks.
let old = "The half-life is $t = 12.4 \"hour\"$ for this isotope, which is short.\n";
let new = "The half-life for this isotope is quite short, as we discuss below.\n";
let output = run_diff(old, new);
assert!(
output.contains("#diff-deleted[is $t = 12.4 \"hour\"$ ]"),
"equation should be deleted as one unit: {output}"
);
assert!(parses(&output), "output must compile: {output}");
}

#[test]
fn test_markup_reference_paragraph() {
let old = std::fs::read_to_string("tests/fixtures/markup-ref-start-old.typ").unwrap();
Expand Down
Loading