use crate::analysis::tables::Grid;
use crate::backend::FontInfo;
use crate::model::Line;
use crate::model::*;
use std::collections::{HashMap, HashSet};
use std::ops::Range;
const MAX_SLUG_CHARS: usize = 48;
const MIN_RUN_WIDTH_PT: f32 = 0.1;
const BAR_GLYPHS: [&str; 4] = ["|", "\u{2223}", "\u{2225}", "\u{2016}"];
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct TextConfig {
pub compound_part_min_chars_count: usize,
pub cell_wrap_min_dy_em: f32,
pub math_axis_height_em: f32,
pub tall_glyph_min_height_em: f32,
pub off_axis_min_offset_em: f32,
pub run_size_tolerance_pt: f32,
pub run_baseline_tolerance_pt: f32,
pub run_max_gap_em: f32,
pub fraction_space_min_em: f32,
pub term_script_max_size_ratio: f32,
pub term_script_min_offset_em: f32,
}
impl Default for TextConfig {
fn default() -> Self {
Self {
compound_part_min_chars_count: 4,
fraction_space_min_em: 0.2,
term_script_max_size_ratio: 0.85,
term_script_min_offset_em: 0.05,
cell_wrap_min_dy_em: 0.5,
math_axis_height_em: 0.25,
tall_glyph_min_height_em: 1.3,
off_axis_min_offset_em: 0.6,
run_size_tolerance_pt: 0.1,
run_baseline_tolerance_pt: 0.2,
run_max_gap_em: 0.6,
}
}
}
pub(crate) struct TextBuilder<'a> {
pub(crate) fonts: &'a [FontInfo],
pub(crate) vocab: &'a HashSet<String>,
pub(crate) cfg: &'a TextConfig,
}
pub(crate) struct Built {
pub(crate) spans: Vec<Span>,
pub(crate) line_texts: Vec<String>,
pub(crate) hlines: Vec<HLine>,
}
struct OpenRun {
run: EqRun,
font: u16,
end: f32,
}
fn stacked_script_order(glyphs: &[LineGlyph], cfg: &TextConfig) -> (Vec<usize>, Vec<Range<usize>>) {
let mut order: Vec<usize> = Vec::with_capacity(glyphs.len());
let mut fractions: Vec<Range<usize>> = Vec::new();
let mut i = 0;
while i < glyphs.len() {
if glyphs[i].script == 0 {
order.push(i);
i += 1;
continue;
}
let start = i;
while i < glyphs.len() && glyphs[i].script != 0 {
i += 1;
}
let run = start..i;
let span = |sign: i8| {
run.clone()
.filter(|&k| glyphs[k].script.signum() == sign)
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), k| {
(lo.min(glyphs[k].x0), hi.max(glyphs[k].x1))
})
};
let (up, down) = (span(1), span(-1));
let stacked = up.0 < down.1 && down.0 < up.1;
let (left, right) = run
.clone()
.filter(|&k| glyphs[k].is_fraction_term())
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), k| {
(lo.min(glyphs[k].x0), hi.max(glyphs[k].x1))
});
if left <= right {
let before = |k: &usize| (glyphs[*k].x0 + glyphs[*k].x1) / 2.0 < left;
let others: Vec<usize> = run.clone().filter(|&k| !glyphs[k].is_fraction_term()).collect();
let (ahead, behind): (Vec<usize>, Vec<usize>) = others.into_iter().partition(before);
push_stacked(glyphs, &ahead, &mut order);
for sign in [1, -1] {
let term: Vec<usize> = run
.clone()
.filter(|&k| glyphs[k].is_fraction_term() && glyphs[k].script.signum() == sign)
.collect();
term_order(glyphs, &term, cfg, &mut order);
}
push_stacked(glyphs, &behind, &mut order);
fractions.push(run);
} else if stacked {
order.extend(run.clone().filter(|&k| glyphs[k].script > 0));
order.extend(run.filter(|&k| glyphs[k].script < 0));
} else {
order.extend(run);
}
}
(order, fractions)
}
fn term_order(glyphs: &[LineGlyph], term: &[usize], cfg: &TextConfig, order: &mut Vec<usize>) {
let mut k = 0;
while k < term.len() {
let base = &glyphs[term[k]];
order.push(term[k]);
k += 1;
if base.text == "\u{221A}" {
continue;
}
let start = k;
while k < term.len() && glyphs[term[k]].size <= cfg.term_script_max_size_ratio * base.size {
k += 1;
}
let scripts = &term[start..k];
let offset = cfg.term_script_min_offset_em * base.size;
let (ups, downs): (Vec<usize>, Vec<usize>) = scripts.iter().partition(|&&i| glyphs[i].y < base.y - offset);
let extent = |part: &[usize]| {
part.iter().fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &i| {
(lo.min(glyphs[i].x0), hi.max(glyphs[i].x1))
})
};
let (up, down) = (extent(&ups), extent(&downs));
if up.0 < down.1 && down.0 < up.1 {
order.extend(ups);
order.extend(downs);
} else {
order.extend(scripts);
}
}
}
fn push_stacked(glyphs: &[LineGlyph], run: &[usize], order: &mut Vec<usize>) {
let span = |sign: i8| {
run.iter()
.filter(|&&k| glyphs[k].script.signum() == sign)
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), &k| {
(lo.min(glyphs[k].x0), hi.max(glyphs[k].x1))
})
};
let (up, down) = (span(1), span(-1));
if up.0 < down.1 && down.0 < up.1 {
order.extend(run.iter().filter(|&&k| glyphs[k].script > 0));
order.extend(run.iter().filter(|&&k| glyphs[k].script < 0));
} else {
order.extend(run);
}
}
#[derive(Default)]
struct FractionMarks {
before: HashMap<usize, String>,
after: HashMap<usize, String>,
}
fn fraction_marks(
glyphs: &[LineGlyph],
order: &[usize],
fractions: &[Range<usize>],
cfg: &TextConfig,
) -> FractionMarks {
let mut marks = FractionMarks::default();
let compound = |term: &[usize]| {
let largest = term.iter().map(|&pos| glyphs[order[pos]].size).fold(0.0, f32::max);
let term: Vec<usize> = term
.iter()
.copied()
.filter(|&pos| glyphs[order[pos]].size > cfg.term_script_max_size_ratio * largest)
.collect();
term.windows(2).any(|pair| {
let (left, right) = (&glyphs[order[pair[0]]], &glyphs[order[pair[1]]]);
right.x0 - left.x1 > cfg.fraction_space_min_em * right.size
}) || term.iter().any(|&pos| {
glyphs[order[pos]]
.text
.chars()
.any(|ch| "+-\u{2212}\u{B1}\u{B7}\u{D7}=,".contains(ch))
})
};
for run in fractions {
let positions: Vec<usize> = (0..order.len()).filter(|&pos| run.contains(&order[pos])).collect();
let term = |sign: i8| -> Vec<usize> {
positions
.iter()
.copied()
.filter(|&pos| {
let glyph = &glyphs[order[pos]];
glyph.is_fraction_term() && glyph.script.signum() == sign
})
.collect()
};
let (numerator, denominator) = (term(1), term(-1));
let (Some(&den_start), false) = (denominator.first(), numerator.is_empty()) else {
continue;
};
for (idx, term) in [numerator, denominator].iter().enumerate() {
let (first, last) = (term[0], term[term.len() - 1]);
if idx == 1 {
marks.before.entry(den_start).or_default().push('/');
}
let radical = glyphs[order[first]].text == "\u{221A}" && term.len() > 1;
if radical && compound(&term[1..]) {
marks.before.entry(term[1]).or_default().push('(');
marks.after.entry(last).or_default().push(')');
} else if !radical && compound(term) {
marks.before.entry(first).or_default().push('(');
marks.after.entry(last).or_default().push(')');
}
}
}
marks
}
fn term_scripts(glyphs: &[LineGlyph], order: &[usize], cfg: &TextConfig) -> HashMap<usize, u8> {
let mut scripts = HashMap::new();
let mut base: HashMap<i8, &LineGlyph> = HashMap::new();
for &index in order {
let glyph = &glyphs[index];
if glyph.script.abs() != FRACTION_TERM {
base.clear();
continue;
}
if glyph.text == "\u{221A}" {
base.remove(&glyph.script);
continue;
}
let Some(&prev) = base.get(&glyph.script) else {
base.insert(glyph.script, glyph);
continue;
};
if glyph.size > cfg.term_script_max_size_ratio * prev.size {
base.insert(glyph.script, glyph);
continue;
}
let offset = cfg.term_script_min_offset_em * prev.size;
if glyph.y < prev.y - offset {
scripts.insert(index, SUP);
} else if glyph.y > prev.y + offset {
scripts.insert(index, SUB);
}
}
scripts
}
fn fraction_space(
glyphs: &[LineGlyph],
order: &[usize],
pos: usize,
fractions: &[Range<usize>],
cfg: &TextConfig,
) -> Option<bool> {
let glyph = &glyphs[order[pos]];
let prev = &glyphs[order[pos.checked_sub(1)?]];
let run_of = |index: usize| {
fractions
.iter()
.find(|run| run.contains(&index) && glyphs[index].is_fraction_term())
};
let wide = |gap: f32| gap > cfg.fraction_space_min_em * glyph.size;
let extent = |run: &Range<usize>| {
run.clone()
.filter(|&k| glyphs[k].is_fraction_term())
.map(|k| (glyphs[k].x0, glyphs[k].x1))
.fold((f32::INFINITY, f32::NEG_INFINITY), |(lo, hi), (x0, x1)| {
(lo.min(x0), hi.max(x1))
})
};
match (run_of(order[pos]), run_of(order[pos - 1])) {
(Some(run), Some(prev_run)) if run == prev_run => {
Some(prev.script.signum() == glyph.script.signum() && wide(glyph.x0 - prev.x1))
}
(Some(run), _) => Some(wide(extent(run).0 - prev.x1)),
(None, Some(prev_run)) => Some(wide(glyph.x0 - extent(prev_run).1)),
(None, None) => None,
}
}
fn push_text(spans: &mut Vec<Span>, text: &str, style: u8, color: [u8; 3]) {
match spans.last_mut() {
Some(span) if span.style == style && span.color == color => span.text.push_str(text),
_ => spans.push(Span {
text: text.to_string(),
style,
href: None,
color,
math: None,
note: None,
}),
}
}
impl TextBuilder<'_> {
fn placed_line_spans(&self, line: &Line) -> Vec<Span> {
if !line.glyphs.iter().any(LineGlyph::is_fraction_term) {
return self.line_spans(line);
}
let mut placed = line.clone();
for glyph in &mut placed.glyphs {
if glyph.script.abs() == FRACTION_TERM {
glyph.script = glyph.script.signum();
} else if glyph.script.abs() == RAISED_FRACTION_TERM {
glyph.script = 1;
}
}
self.line_spans(&placed)
}
pub(crate) fn line_spans(&self, line: &Line) -> Vec<Span> {
let mut spans: Vec<Span> = Vec::new();
let (order, fractions) = stacked_script_order(&line.glyphs, self.cfg);
let marks = fraction_marks(&line.glyphs, &order, &fractions, self.cfg);
let term_scripts = term_scripts(&line.glyphs, &order, self.cfg);
let close_after = |spans: &mut Vec<Span>, pos: usize| {
if let Some(close) = marks.after.get(&pos) {
let glyph = &line.glyphs[order[pos]];
push_text(spans, close, line.style_of(glyph, self.fonts), glyph.color);
}
};
for (glyph_idx, &index) in order.iter().enumerate() {
if glyph_idx > 0 {
close_after(&mut spans, glyph_idx - 1);
}
let glyph = &line.glyphs[index];
let base_style = line.style_of(glyph, self.fonts);
let style = base_style | term_scripts.get(&index).copied().unwrap_or(0);
let mut space = fraction_space(&line.glyphs, &order, glyph_idx, &fractions, self.cfg)
.unwrap_or(glyph.space_before)
&& glyph_idx > 0;
if let Some(before) = marks.before.get(&glyph_idx) {
if space {
push_text(&mut spans, " ", base_style, glyph.color);
}
push_text(&mut spans, before, base_style, glyph.color);
space = false;
}
let mut lead = "";
if let Some(span) = spans.last_mut() {
let same_link = span.href.as_deref() == glyph.link.as_deref();
if space {
if same_link || span.href.is_none() {
span.text.push(' ');
} else {
lead = " ";
}
}
if span.style == style && span.color == glyph.color && same_link {
span.text.push_str(&glyph.text);
continue;
}
}
spans.push(Span {
text: format!("{lead}{}", glyph.text),
style,
href: glyph.link.as_deref().map(str::to_string),
color: glyph.color,
math: None,
note: None,
});
}
if let Some(last) = order.len().checked_sub(1) {
close_after(&mut spans, last);
}
spans
}
pub(crate) fn build(&self, lines: &[Line], skip: usize, mask: u8) -> Built {
let texts: Vec<String> = lines.iter().map(|line| line.text()).collect();
let mut read: Vec<HLine> = Vec::with_capacity(lines.len());
let mut hlines: Vec<HLine> = Vec::with_capacity(lines.len());
let mut line_texts: Vec<String> = Vec::with_capacity(lines.len());
for (line_idx, line) in lines.iter().enumerate() {
let mut line_spans = self.line_spans(line);
let mut placed_spans = self.placed_line_spans(line);
let soft_hyphen = match texts.get(line_idx + 1) {
Some(next) => {
self.join_line_end(&mut placed_spans, &texts[line_idx], next);
self.join_line_end(&mut line_spans, &texts[line_idx], next)
}
None => false,
};
line_texts.push(line_spans.iter().map(|span| span.text.as_str()).collect());
read.push(HLine {
spans: line_spans,
soft_hyphen,
});
hlines.push(HLine {
spans: placed_spans,
soft_hyphen,
});
}
let mut spans = running_spans(&read, mask);
if skip > 0 && !lines.is_empty() {
let n: usize = lines[0]
.glyphs
.iter()
.take(skip)
.map(|glyph| glyph.text.chars().count())
.sum();
strip_chars(&mut spans, n);
}
Built {
spans,
line_texts,
hlines,
}
}
fn join_line_end(&self, spans: &mut Vec<Span>, text: &str, next: &str) -> bool {
if url_continues(text, next) {
if text.ends_with('-') && url_hyphen_is_soft(text, next, self.vocab) {
if let Some(last) = spans.last_mut() {
last.text.pop();
if last.text.is_empty() {
spans.pop();
}
}
return true;
}
return false;
}
if text.ends_with('-') && text.chars().count() > 1 {
if remove_hyphen(text, next, self.vocab, self.cfg) {
if let Some(last) = spans.last_mut() {
last.text.pop();
if last.text.is_empty() {
spans.pop();
}
}
return true;
}
} else if !text.ends_with('/')
&& !text.is_empty()
&& !joins_without_space(text, next)
&& let Some(last) = spans.last_mut()
{
last.text.push(' ');
}
false
}
pub(crate) fn eq_runs(&self, lines: &[Line]) -> Vec<EqRun> {
let mut runs: Vec<EqRun> = Vec::new();
for line in lines {
let mut current: Option<OpenRun> = None;
for glyph in &line.glyphs {
if glyph.text.contains('\u{FFFD}') {
close_run(&mut current, &mut runs);
continue;
}
let style = line.style_of(glyph, self.fonts) & !(SUP | SUB);
if self.stands_alone(glyph) {
close_run(&mut current, &mut runs);
runs.push(EqRun {
text: glyph.text.clone(),
x: glyph.ox,
y: glyph.oy,
width: (glyph.x1 - glyph.x0).max(MIN_RUN_WIDTH_PT),
size: glyph.size,
style,
color: glyph.color,
ink: Some(glyph.ink),
});
continue;
}
match current.as_mut().filter(|open| self.extends_run(open, glyph)) {
Some(open) => {
if glyph.space_before {
open.run.text.push(' ');
}
open.run.text.push_str(&glyph.text);
open.end = glyph.x1;
open.run.width = glyph.x1 - open.run.x;
}
None => {
close_run(&mut current, &mut runs);
current = Some(OpenRun {
run: EqRun {
text: glyph.text.clone(),
x: glyph.x0,
y: glyph.oy,
width: (glyph.x1 - glyph.x0).max(MIN_RUN_WIDTH_PT),
size: glyph.size,
style,
color: glyph.color,
ink: None,
},
font: glyph.font,
end: glyph.x1,
});
}
}
}
close_run(&mut current, &mut runs);
}
runs
}
fn stands_alone(&self, glyph: &LineGlyph) -> bool {
let axis = glyph.oy - self.cfg.math_axis_height_em * glyph.size;
glyph.ink.height() > self.cfg.tall_glyph_min_height_em * glyph.size
|| (glyph.ink.cy() - axis).abs() > self.cfg.off_axis_min_offset_em * glyph.size
|| glyph.text == "\u{221A}"
|| BAR_GLYPHS.contains(&glyph.text.as_str())
}
fn extends_run(&self, open: &OpenRun, glyph: &LineGlyph) -> bool {
open.font == glyph.font
&& (open.run.size - glyph.size).abs() < self.cfg.run_size_tolerance_pt
&& (open.run.y - glyph.oy).abs() < self.cfg.run_baseline_tolerance_pt
&& open.run.color == glyph.color
&& glyph.x0 - open.end < self.cfg.run_max_gap_em * glyph.size
&& glyph.x0 >= open.run.x
}
pub(crate) fn table(&self, grid: Grid) -> Table {
let rows = grid
.rows
.iter()
.map(|row| {
row.iter()
.map(|cell| TableCell {
col: cell.col,
colspan: cell.colspan,
rowspan: cell.rowspan,
spans: self.cell_spans(&cell.lines),
})
.collect()
})
.collect();
Table {
n_cols: grid.n_cols,
header_rows: grid.header_rows,
col_align: grid
.col_align
.iter()
.map(|align| match align {
Align::Left => "left",
Align::Center => "center",
Align::Right => "right",
})
.collect(),
rows,
rule_above: grid.rule_above,
rule_bottom: grid.rule_bottom,
rule_left: grid.rule_left,
rule_right: grid.rule_right,
geom: TableGeom {
bbox: grid.bbox,
col_bounds: grid.col_bounds,
col_text: grid.col_text,
row_bounds: grid.row_bounds,
row_baselines: grid.row_baselines,
size: grid.size,
},
}
}
fn cell_spans(&self, lines: &[Line]) -> Vec<Span> {
let mut spans: Vec<Span> = Vec::new();
for (line_idx, line) in lines.iter().enumerate() {
let mut line_spans = self.line_spans(line);
if let Some(next) = lines.get(line_idx + 1) {
if next.baseline - line.baseline > line.size * self.cfg.cell_wrap_min_dy_em {
self.join_line_end(&mut line_spans, &line.text(), &next.text());
} else if let Some(last) = line_spans.last_mut() {
last.text.push(' ');
}
}
spans.extend(line_spans);
}
spans
}
}
pub(crate) fn slug(text: &str) -> String {
let mut out = String::new();
for ch in text.chars() {
if ch.is_alphanumeric() {
out.extend(ch.to_lowercase());
} else if !out.ends_with('-') && !out.is_empty() {
out.push('-');
}
}
out.trim_end_matches('-').chars().take(MAX_SLUG_CHARS).collect()
}
pub(crate) fn tokens(text: &str) -> impl Iterator<Item = &str> {
text.split(|ch: char| !(ch.is_alphabetic() || ch == '-'))
.filter(|token| !token.is_empty())
}
pub(crate) fn build_vocab<'a>(blocks: impl Iterator<Item = &'a [Line]>) -> HashSet<String> {
let mut vocab = HashSet::new();
for lines in blocks {
let mut prev_hyphen = false;
for line in lines {
let text = line.text();
let ends_hyphen = text.ends_with('-');
let line_tokens: Vec<&str> = tokens(&text).collect();
let n = line_tokens.len();
for (i, token) in line_tokens.into_iter().enumerate() {
if (i == 0 && prev_hyphen) || (i + 1 == n && ends_hyphen) {
continue;
}
let word = token.trim_matches('-').to_lowercase();
if word.is_empty() {
continue;
}
for part in word.split('-') {
if !part.is_empty() {
vocab.insert(part.to_string());
}
}
vocab.insert(word);
}
prev_hyphen = ends_hyphen;
}
}
vocab
}
pub(crate) fn url_continues(text: &str, next: &str) -> bool {
let Some(last) = text.split_whitespace().last() else {
return false;
};
let last = last.trim_start_matches(['(', '[', '<', '"', '\u{201c}']);
if matches!(last, "http:" | "https:") && next.starts_with("//") {
return true;
}
if !(last.contains("://") || last.starts_with("www.")) {
return false;
}
let Some(first) = next.trim_start().chars().next() else {
return false;
};
if next.starts_with(char::is_whitespace) {
return false;
}
match last.chars().last() {
Some('_' | '-' | '/' | '?' | '=' | '&' | '#' | '~' | '%' | ':') => true,
Some('.') => {
let token = next.split_whitespace().next().unwrap_or("");
let host = token.split('/').next().unwrap_or("");
(first.is_lowercase() || first.is_ascii_digit()) && !host.chars().any(char::is_uppercase)
}
_ => false,
}
}
fn url_hyphen_is_soft(text: &str, next: &str, vocab: &HashSet<String>) -> bool {
let left: String = text
.chars()
.rev()
.skip(1)
.take_while(|ch| ch.is_alphabetic())
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
let right: String = next.chars().take_while(|ch| ch.is_alphabetic()).collect();
!left.is_empty() && !right.is_empty() && vocab.contains(&format!("{left}{right}").to_lowercase())
}
pub(crate) fn remove_hyphen(left: &str, right: &str, vocab: &HashSet<String>, cfg: &TextConfig) -> bool {
let trailing: String = left
.chars()
.rev()
.skip(1)
.take_while(|ch| ch.is_alphabetic())
.collect::<Vec<_>>()
.into_iter()
.rev()
.collect();
let leading: String = right.chars().take_while(|ch| ch.is_alphabetic()).collect();
if trailing.is_empty() || leading.is_empty() {
return false;
}
if right.chars().nth(leading.chars().count()) == Some('-') {
return false;
}
if !leading.chars().next().unwrap().is_lowercase() {
let capitals = |part: &str| part.chars().all(char::is_uppercase);
return trailing.chars().count() >= 2
&& leading.chars().count() >= 2
&& capitals(&trailing)
&& capitals(&leading)
&& vocab.contains(&format!("{trailing}{leading}").to_lowercase());
}
let before: Vec<char> = left.chars().rev().skip(1 + trailing.chars().count()).take(1).collect();
if before.first() == Some(&'-') {
return false;
}
if trailing.chars().filter(|ch| ch.is_uppercase()).count() >= 2
&& trailing.chars().last().is_some_and(char::is_uppercase)
{
return false;
}
let (left_part, right_part) = (trailing.to_lowercase(), leading.to_lowercase());
if vocab.contains(&format!("{left_part}{right_part}")) {
return true;
}
if vocab.contains(&format!("{left_part}-{right_part}")) {
return false;
}
let known = |word: &str| {
vocab.contains(word)
|| ["ed", "d", "ing", "s", "es"].iter().any(|suffix| {
word.strip_suffix(suffix).is_some_and(|stem| {
stem.chars().count() >= cfg.compound_part_min_chars_count && vocab.contains(stem)
})
})
};
!(left_part.chars().count() >= cfg.compound_part_min_chars_count
&& vocab.contains(&left_part)
&& known(&right_part))
}
pub(crate) fn strip_chars(spans: &mut Vec<Span>, mut n: usize) {
while n > 0 && !spans.is_empty() {
let len = spans[0].text.chars().count();
if len <= n {
n -= len;
spans.remove(0);
} else {
spans[0].text = spans[0].text.chars().skip(n).collect();
n = 0;
}
}
if let Some(first) = spans.first_mut() {
first.text = first.text.trim_start().to_string();
}
}
fn running_spans(hlines: &[HLine], mask: u8) -> Vec<Span> {
let mut spans: Vec<Span> = Vec::new();
for span in hlines.iter().flat_map(|hline| hline.spans.iter()) {
let style = span.style & !mask;
match spans.last_mut() {
Some(prev) if prev.style == style && prev.color == span.color && prev.href == span.href => {
prev.text.push_str(&span.text)
}
_ => spans.push(Span {
text: span.text.clone(),
style,
href: span.href.clone(),
color: span.color,
math: None,
note: None,
}),
}
}
spans
}
fn close_run(current: &mut Option<OpenRun>, runs: &mut Vec<EqRun>) {
if let Some(open) = current.take() {
runs.push(open.run);
}
}
fn joins_without_space(text: &str, next: &str) -> bool {
let (Some(last), Some(first)) = (text.trim_end().chars().last(), next.trim_start().chars().next()) else {
return false;
};
is_cjk_punctuation_mark(last) || (is_cjk_char(last) && is_cjk_char(first))
}
fn is_cjk_char(ch: char) -> bool {
matches!(
ch,
'\u{3000}'..='\u{30FF}' | '\u{3400}'..='\u{4DBF}' | '\u{4E00}'..='\u{9FFF}' | '\u{F900}'..='\u{FAFF}' | '\u{FF00}'..='\u{FFEF}'
)
}
fn is_cjk_punctuation_mark(ch: char) -> bool {
matches!(ch, '\u{3001}'..='\u{303F}') || (matches!(ch, '\u{FF01}'..='\u{FF65}') && !ch.is_alphanumeric())
}
#[cfg(test)]
#[allow(clippy::min_ident_chars, clippy::missing_docs_in_private_items)]
mod tests {
use super::*;
#[test]
fn chinese_and_japanese_lines_join_without_space() {
assert!(joins_without_space("外国人の数が年々", "増えています。"));
assert!(joins_without_space("身につけるための教材です。", "Irodori"));
assert!(!joins_without_space("such as 日本語", "while N2"));
assert!(!joins_without_space("the people", "communicating"));
}
use std::collections::HashSet;
fn vocab(words: &[&str]) -> HashSet<String> {
words.iter().map(|w| w.to_string()).collect()
}
#[test]
fn urls_broken_across_lines_go_on() {
assert!(url_continues(
"available at https://github.com/shaoqingren/faster_",
"rcnn (in MATLAB) and"
));
assert!(url_continues(
"see https://github.com/rbgirshick/py-faster-",
"rcnn (in Python)."
));
assert!(url_continues("at www.robots.ox.ac.", "uk/~vgg"));
assert!(!url_continues("results at https://example.com/page.html.", "We then"));
assert!(!url_continues("the dot-product (multi-", "plicative) attention"));
assert!(!url_continues("https://example.com/a", "and more"));
let vocab: HashSet<String> = ["openai", "faster", "rcnn"].iter().map(|w| w.to_string()).collect();
assert!(url_hyphen_is_soft("https://ope-", "nai.com/blog", &vocab));
assert!(!url_hyphen_is_soft(
"https://github.com/rbgirshick/py-faster-",
"rcnn",
&vocab
));
assert!(url_continues("see http:", "//arxiv.org/abs/1804.08838"));
assert!(url_continues("https://aclanthology.", "org/N19-1246"));
assert!(!url_continues(
"URL http://arxiv.org/abs/2104.08691.",
"arXiv: 2104.08691."
));
}
#[test]
fn soft_hyphens_are_removed() {
let v = vocab(&["multi", "head", "multi-head", "self", "attention", "information"]);
let cfg = TextConfig::default();
assert!(remove_hyphen("dot-product (multi-", "plicative) attention", &v, &cfg));
assert!(remove_hyphen("more in-", "formation is needed", &v, &cfg));
assert!(!remove_hyphen("layers of self-", "attention are used", &v, &cfg));
assert!(!remove_hyphen("we use multi-", "head attention", &v, &cfg));
assert!(!remove_hyphen("the English-", "German task", &v, &cfg));
assert!(!remove_hyphen("pages 10-", "20 of the", &v, &cfg));
assert!(!remove_hyphen("a state-of-", "the-art model", &v, &cfg));
}
}