Execute and render TeX--XeT direction spans in native layouts

This commit is contained in:
gloamxun committed 2026-11-21 16:46:17 +08:00
1 parent a93d1bb902
commit 22e3ba993d
17 files changed
+460 -54

No files matched your search

+80 -42
View File
@@ -147,6 +147,17 @@ enum PackedHorizontal<'a> {
Output(&'a OutputNode),
}
impl PackedHorizontal<'_> {
fn width(&self) -> i64 {
match self {
Self::Item(HorizontalItem::Box(b)) => b.width,
Self::Item(HorizontalItem::Glue { width, .. }) | Self::Leaders(_, width) => *width,
Self::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width),
_ => 0,
}
}
}
pub(super) enum BoxPaint<'a> {
Box(&'a HorizontalBox),
PdfColor,
@@ -218,21 +229,24 @@ pub(super) enum GeometryItem {
impl NativeBox {
pub(super) fn output_nodes(&self) -> (Vec<&OutputNode>, bool) {
fn walk<'a>(b: &'a NativeBox, out: &mut Vec<&'a OutputNode>, leaders: &mut bool) {
fn walk<'a>(b: &'a NativeBox, rtl: bool, out: &mut Vec<&'a OutputNode>, leaders: &mut bool) {
if b.kind.is_unset() {
return;
}
match &b.content {
BoxContent::Horizontal(nodes) => {
for n in nodes {
match n {
let order = super::direction::visual_order(nodes, rtl && !b.display);
let order = order.as_deref();
for index in 0..nodes.len() {
let (index, rtl) = order.map_or((index, false), |order| order[index]);
match &nodes[index] {
TextNode::Output(o) => out.push(o),
TextNode::Leaders(_) => *leaders = true,
TextNode::Box(b)
| TextNode::MathChar(b)
| TextNode::Glyph { glyph: b, .. } => {
if let Some(b) = &b.native_box {
walk(b, out, leaders)
walk(b, rtl, out, leaders)
}
}
_ => {}
@@ -245,7 +259,7 @@ impl NativeBox {
NativeVerticalNode::Output(o) => out.push(o),
NativeVerticalNode::Leaders(_) => *leaders = true,
NativeVerticalNode::Box(b) | NativeVerticalNode::Line(b) => {
walk(b, out, leaders)
walk(b, rtl, out, leaders)
}
_ => {}
}
@@ -255,7 +269,7 @@ impl NativeBox {
}
let mut out = Vec::new();
let mut leaders = false;
walk(self, &mut out, &mut leaders);
walk(self, false, &mut out, &mut leaders);
(out, leaders)
}
@@ -271,7 +285,7 @@ impl NativeBox {
cancellation,
leader_depth: 0,
};
self.walk_at(0, 0, 0, false, &mut budget, &mut |x, y, item| {
self.walk_at(0, 0, 0, false, false, &mut budget, &mut |x, y, item| {
if let BoxPaint::Output(o) = item {
if o.needs_shipout_position() {
output_positions.push([x, y]);
@@ -301,9 +315,9 @@ impl NativeBox {
/// The box never stores a second recursive copy of its children for paint.
pub fn horizontal_items(&self) -> Option<Vec<HorizontalItem>> {
Some(
self.packed_horizontal()?
self.packed_horizontal(false)?
.into_iter()
.filter_map(|item| match item {
.filter_map(|(item, _)| match item {
PackedHorizontal::Item(value) => Some(value),
PackedHorizontal::Leaders(_, width) => Some(HorizontalItem::Glue {
width,
@@ -317,16 +331,14 @@ impl NativeBox {
)
}
fn packed_horizontal(&self) -> Option<Vec<PackedHorizontal<'_>>> {
fn packed_horizontal<'a>(&'a self, rtl: bool) -> Option<Vec<(PackedHorizontal<'a>, bool)>> {
let BoxContent::Horizontal(nodes) = &self.content else {
return None;
};
let (mut cumulative, mut previous) = (0, 0);
let mut items = Vec::new();
for node in nodes {
if matches!(node, TextNode::Box(b) if b.native_box.as_ref().is_some_and(|b| b.kind.is_unset()))
{
continue;
let mut pack = |node: &'a TextNode| {
if matches!(node, TextNode::Box(b) if b.native_box.as_ref().is_some_and(|b| b.kind.is_unset())) {
return None;
}
let item = match node {
TextNode::Glyph { glyph, .. }
@@ -361,18 +373,22 @@ impl NativeBox {
let g = leader.glue;
let width = i64::from(g.width)
+ self.setting.adjustment(g, &mut cumulative, &mut previous);
items.push(PackedHorizontal::Leaders(leader, width));
continue;
return Some(PackedHorizontal::Leaders(leader, width));
}
TextNode::Output(node) => {
items.push(PackedHorizontal::Output(node));
continue;
return Some(PackedHorizontal::Output(node));
}
_ => continue,
_ => return None,
};
items.push(PackedHorizontal::Item(item));
}
Some(items)
Some(PackedHorizontal::Item(item))
};
let Some(order) = super::direction::visual_order(nodes, rtl) else {
return Some(nodes.iter().filter_map(|node| pack(node).map(|item| (item, false))).collect());
};
// Glue accumulates its rounding in logical order before the device
// reverses a span. Reuse those adjusted widths in visual order.
let mut logical: Vec<_> = nodes.iter().map(pack).collect();
Some(order.into_iter().filter_map(|(i, rtl)| logical[i].take().map(|item| (item, rtl))).collect())
}
pub fn node_count(&self) -> usize {
@@ -591,11 +607,21 @@ pub(super) fn dimensions_fit(w: i64, h: i64, d: i64) -> Result<(), String> {
}
}
pub(super) fn hpack(
mut nodes: Vec<TextNode>,
nodes: Vec<TextNode>,
spec: PackSpec,
span: Span,
state: &State,
) -> Result<NativeBox, String> {
hpack_with_direction_report(nodes, spec, span, state).map(|(packed, _)| packed)
}
pub(super) fn hpack_with_direction_report(
mut nodes: Vec<TextNode>,
spec: PackSpec,
span: Span,
state: &State,
) -> Result<(NativeBox, (usize, usize)), String> {
let direction_problems = super::direction::complete_box(&mut nodes);
let (mut width, mut height, mut depth) = (0, 0, 0);
let (mut stretch, mut shrink) = ([0; 4], [0; 4]);
for node in &nodes {
@@ -663,7 +689,7 @@ pub(super) fn hpack(
}));
}
let diagnostic = super::diagnostics::text_nodes(&nodes);
Ok(NativeBox {
Ok((NativeBox {
kind: BoxKind::Horizontal,
display: false,
width: desired,
@@ -677,7 +703,7 @@ pub(super) fn hpack(
diagnostic_eligible,
excess,
span,
})
}, direction_problems))
}
/// Flatten already packed native geometry for the common PDF/SVG display list.
@@ -817,11 +843,11 @@ impl NativeBox {
y: i64,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
) -> Result<(), &'static str> {
self.walk_at(x, y, 0, false, &mut WalkBudget::for_geometry(), emit)
self.walk_at(x, y, 0, false, false, &mut WalkBudget::for_geometry(), emit)
}
pub(super) fn walk_pdf_links(&self, emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>)) {
self.walk_at(0, 0, 0, true, &mut WalkBudget::for_geometry(), emit)
self.walk_at(0, 0, 0, false, true, &mut WalkBudget::for_geometry(), emit)
.expect("link traversal of an already measured list");
}
@@ -830,6 +856,7 @@ impl NativeBox {
x: i64,
y: i64,
level: usize,
rtl: bool,
links: bool,
budget: &mut WalkBudget<'_>,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
@@ -840,9 +867,16 @@ impl NativeBox {
match &self.content {
BoxContent::Horizontal(nodes) => {
budget.inside_leader(nodes.len())?;
let rtl = rtl && !self.display;
let packed = self.packed_horizontal(rtl).unwrap();
let left = if rtl {
x + self.width - packed.iter().map(|(item, _)| item.width()).sum::<i64>()
} else {
x
};
let row = BoxLayout {
horizontal: true,
left: x,
left,
baseline: y,
width: self.width,
height: self.height,
@@ -850,14 +884,15 @@ impl NativeBox {
level,
};
if links {
emit(x, y, BoxPaint::RowStart(row));
emit(left, y, BoxPaint::RowStart(row));
}
walk_row(&self.packed_horizontal().unwrap(), row, links, budget, emit)?;
walk_row(&packed, row, links, budget, emit)?;
}
BoxContent::Vertical(nodes) => {
let edge = if rtl { x + self.width } else { x };
let container = BoxLayout {
horizontal: false,
left: x,
left: edge,
baseline: y,
width: self.width,
height: self.height,
@@ -874,7 +909,8 @@ impl NativeBox {
continue;
}
cursor += b.height;
b.walk_at(x + b.shift, cursor, level + 1, links, budget, emit)?;
let child_x = if rtl { edge - b.shift - b.width } else { x + b.shift };
b.walk_at(child_x, cursor, level + 1, rtl, links, budget, emit)?;
cursor += b.depth;
}
NativeVerticalNode::Glue(g) | NativeVerticalNode::NamedGlue(g, _) => {
@@ -894,9 +930,10 @@ impl NativeBox {
b.height + b.depth,
) {
b.walk_leader(
x + b.shift,
if rtl { edge - b.shift - b.width } else { x + b.shift },
pos + b.height,
level + 1,
rtl,
links,
budget,
emit,
@@ -922,14 +959,14 @@ impl NativeBox {
NativeVerticalNode::Rule(r) => {
let b = r.horizontal_item(self.width, 0, 0);
cursor += b.height;
emit(x, cursor, BoxPaint::Box(&b));
emit(if rtl { edge - b.width } else { x }, cursor, BoxPaint::Box(&b));
cursor += b.depth;
}
NativeVerticalNode::Output(node) => {
walk_output(node, x, cursor, container, links, emit);
walk_output(node, edge, cursor, container, links, emit);
if let Some(image) = node.image_box() {
cursor += image.height;
emit(x, cursor, BoxPaint::Box(&image));
emit(if rtl { edge - image.width } else { x }, cursor, BoxPaint::Box(&image));
cursor += image.depth;
}
}
@@ -946,13 +983,14 @@ impl NativeBox {
x: i64,
y: i64,
level: usize,
rtl: bool,
links: bool,
budget: &mut WalkBudget<'_>,
emit: &mut dyn FnMut(i64, i64, BoxPaint<'_>),
) -> Result<(), &'static str> {
budget.charge(1)?;
budget.leader_depth += 1;
let result = self.walk_at(x, y, level, links, budget, &mut |x, y, paint| {
let result = self.walk_at(x, y, level, rtl, links, budget, &mut |x, y, paint| {
if !matches!(paint, BoxPaint::Output(o) if matches!(o.operation,
OutputOperation::Open { .. } | OutputOperation::Write { .. } | OutputOperation::Close { .. }))
&& !matches!(paint, BoxPaint::PdfLink(node, _) if matches!(
@@ -975,7 +1013,7 @@ pub(super) fn bp(n: i64) -> i64 {
}
}
fn walk_row(
items: &[PackedHorizontal<'_>],
items: &[(PackedHorizontal<'_>, bool)],
row: BoxLayout,
links: bool,
budget: &mut WalkBudget<'_>,
@@ -983,11 +1021,11 @@ fn walk_row(
) -> Result<(), &'static str> {
let mut x = row.left;
let y = row.baseline;
for item in items {
for (item, rtl) in items {
match item {
PackedHorizontal::Item(HorizontalItem::Box(b)) => {
if let Some(child) = &b.native_box {
child.walk_at(x, y + child.shift, row.level + 1, links, budget, emit)?;
child.walk_at(x, y + child.shift, row.level + 1, *rtl, links, budget, emit)?;
} else {
if let Some(geometry) = &b.math_geometry {
budget.inside_leader(geometry.items.len())?;
@@ -1001,7 +1039,7 @@ fn walk_row(
match &leader.pattern {
LeaderPattern::Box(b) => {
for pos in leader.positions(row.left, x, *width, b.width) {
b.walk_leader(pos, y + b.shift, row.level + 1, links, budget, emit)?;
b.walk_leader(pos, y + b.shift, row.level + 1, *rtl, links, budget, emit)?;
}
}
LeaderPattern::Rule(r) if *width > 0 => {
@@ -58,6 +58,7 @@ pub enum DiagnosticNode {
AccentKern(i32),
AutoKern(i32),
MarginKern { width: i32, right: bool },
Direction(DirectionBoundary),
}
/// A semantic view, without recursively copying the box's painted contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -240,6 +241,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
width: *width,
explicit: *explicit,
},
TextNode::Direction(boundary) => DiagnosticNode::Direction(*boundary),
TextNode::MathBoundary { width, after } => DiagnosticNode::Math {
width: *width,
after: *after,
@@ -533,6 +535,7 @@ impl Printer<'_> {
}
self.number(*width as i64);
}
DiagnosticNode::Direction(boundary) => self.command(boundary.name()),
DiagnosticNode::Math { width, after } => {
self.command(if *after { "mathoff" } else { "mathon" });
if *width != 0 {
@@ -0,0 +1,168 @@
//! Owned TeX--XeT boundaries and visual traversal of logical horizontal lists.
use super::TextNode;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum DirectionBoundary {
BeginL,
EndL,
BeginR,
EndR,
}
impl DirectionBoundary {
pub(super) fn name(self) -> &'static str {
match self {
Self::BeginL => "beginL",
Self::EndL => "endL",
Self::BeginR => "beginR",
Self::EndR => "endR",
}
}
}
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum Region {
Left,
Right,
Math,
}
impl Region {
fn mark(node: &TextNode) -> Option<(Self, bool)> {
let mark = match node {
TextNode::Direction(DirectionBoundary::BeginL) => (Self::Left, true),
TextNode::Direction(DirectionBoundary::EndL) => (Self::Left, false),
TextNode::Direction(DirectionBoundary::BeginR) => (Self::Right, true),
TextNode::Direction(DirectionBoundary::EndR) => (Self::Right, false),
TextNode::MathBoundary { after, .. } => (Self::Math, !after),
_ => return None,
};
Some(mark)
}
fn node(self, begin: bool) -> TextNode {
TextNode::Direction(match (self, begin) {
(Self::Left, true) => DirectionBoundary::BeginL,
(Self::Left, false) => DirectionBoundary::EndL,
(Self::Right, true) => DirectionBoundary::BeginR,
(Self::Right, false) => DirectionBoundary::EndR,
(Self::Math, _) => return TextNode::MathBoundary { width: 0, after: !begin },
})
}
}
pub(super) fn has_directions(nodes: &[TextNode]) -> bool {
nodes.iter().any(|node| matches!(node, TextNode::Direction(_)))
}
pub(super) fn observe(stack: &mut Vec<Region>, node: &TextNode) {
if let Some((region, begin)) = Region::mark(node) {
if begin {
stack.push(region);
} else if stack.last() == Some(&region) {
stack.pop();
}
}
}
/// A paragraph carries direction spans through its chosen logical breaks.
/// Each packed line owns the corresponding openings and closings for output.
pub(super) fn line(nodes: &mut Vec<TextNode>, stack: &mut Vec<Region>) {
let prefix: Vec<_> = stack.iter().map(|region| region.node(true)).collect();
for node in nodes.iter() {
observe(stack, node);
}
nodes.splice(..0, prefix);
}
pub(super) fn close(nodes: &mut Vec<TextNode>, stack: &[Region]) {
nodes.extend(stack.iter().rev().map(|region| region.node(false)));
}
pub(super) fn complete_box(nodes: &mut Vec<TextNode>) -> (usize, usize) {
if !has_directions(nodes) {
return (0, 0);
}
let mut stack = Vec::new();
let mut extra = 0;
for node in nodes.iter_mut() {
match Region::mark(node) {
Some((region, false)) if stack.last() != Some(&region)
&& matches!(node, TextNode::Direction(_)) =>
{
*node = TextNode::Kern { width: 0, explicit: true };
extra += 1;
}
_ => observe(&mut stack, node),
}
}
close(nodes, &stack);
(stack.len(), extra)
}
struct Frame {
start: usize,
end: usize,
rtl: bool,
exit: Option<(usize, bool)>,
}
/// Indices in physical left-to-right order with the enclosing direction of
/// each item. Retain logical order in the box so unboxing and diagnostics see
/// original nodes. Pairing and traversal both take linear time.
pub(super) fn visual_order(nodes: &[TextNode], rtl: bool) -> Option<Vec<(usize, bool)>> {
if !rtl && !has_directions(nodes) {
return None;
}
let mut mates = vec![None; nodes.len()];
let mut open = Vec::new();
for (index, node) in nodes.iter().enumerate() {
if let Some((region, begin)) = Region::mark(node) {
if begin {
open.push((region, index));
} else if let Some(&(found, first)) = open.last()
&& region == found
{
open.pop();
mates[first] = Some((index, region));
mates[index] = Some((first, region));
}
}
}
let mut output = Vec::with_capacity(nodes.len());
let mut frames = vec![Frame { start: 0, end: nodes.len(), rtl, exit: None }];
while let Some(frame) = frames.last_mut() {
if frame.start == frame.end {
output.extend(frame.exit);
frames.pop();
continue;
}
let index = if frame.rtl {
frame.end -= 1;
frame.end
} else {
let index = frame.start;
frame.start += 1;
index
};
let rtl = frame.rtl;
output.push((index, rtl));
if let Some((mate, region)) = mates[index] {
let (start, end) = if rtl {
frame.end = mate;
(mate + 1, index)
} else {
frame.start = mate + 1;
(index + 1, mate)
};
frames.push(Frame {
start,
end,
rtl: region == Region::Right,
exit: Some((mate, rtl)),
});
}
}
Some(output)
}
@@ -3188,6 +3188,10 @@ impl Executor {
Primitive::XeTeXrevision => "XeTeXrevision".into(),
Primitive::XeTeXpdffile => "XeTeXpdffile".into(),
Primitive::XeTeXpicfile => "XeTeXpicfile".into(),
Primitive::BeginL => "beginL".into(),
Primitive::EndL => "endL".into(),
Primitive::BeginR => "beginR".into(),
Primitive::EndR => "endR".into(),
Primitive::XeTeXpdfpagecount => "XeTeXpdfpagecount".into(),
p if p.xetex_font_query_name().is_some() => {
p.xetex_font_query_name().unwrap().into()
@@ -3755,6 +3759,10 @@ impl Executor {
| Primitive::Unhbox
| Primitive::Unhcopy
| Primitive::Valign
| Primitive::BeginL
| Primitive::EndL
| Primitive::BeginR
| Primitive::EndR
)
)
{
@@ -3864,6 +3872,23 @@ impl Executor {
self.request_page();
self.events.push(Event::Paragraph(token.span));
}
BeginL | EndL | BeginR | EndR => {
let boundary = match primitive {
BeginL => DirectionBoundary::BeginL,
EndL => DirectionBoundary::EndL,
BeginR => DirectionBoundary::BeginR,
EndR => DirectionBoundary::EndR,
_ => unreachable!(),
};
if !self.math.is_empty() {
return self.fail("Missing $ inserted");
}
if self.read_parameter(Parameter::TeXXeTstate).width() <= 0 {
return self.fail(format!("Improper \\{}.", boundary.name()));
}
self.finish_text(true)?;
self.paragraph.as_mut().unwrap().nodes.push(TextNode::Direction(boundary));
}
BeginGroup => self.begin_group(GroupKind::SemiSimple, files)?,
EndGroup => self.finish_group(GroupKind::SemiSimple, token.span, files)?,
End | Dump => {
@@ -776,7 +776,7 @@ impl Executor {
} else {
b.nodes
};
boxes::hpack(nodes, frame.spec, frame.span, &self.state)
boxes::hpack_with_direction_report(nodes, frame.spec, frame.span, &self.state)
} else {
boxes::vpack(
self.vertical.take_nodes(),
@@ -785,8 +785,17 @@ impl Executor {
frame.kind,
frame.span,
)
.map(|packed| (packed, (0, 0)))
};
let b = result.map_err(|e| self.error(e, frame.span))?;
let (b, (missing, extra)) = result.map_err(|e| self.error(e, frame.span))?;
if missing != 0 || extra != 0 {
let line = self.error("", self.current).line;
files
.observe_message(&format!(
"\n\\endL or \\endR problem ({missing} missing, {extra} extra) detected at line {line}\n"
))
.map_err(|error| self.error(error, self.current))?;
}
self.diagnose_box(&b, files)?;
self.account_box(&b)?;
self.paragraph = frame.paragraph;
@@ -44,7 +44,7 @@ impl Tail {
TextNode::Insertion(_) => Self::Other(4),
TextNode::Discretionary { .. } => Self::Other(8),
TextNode::Language(_) | TextNode::Output(_) => Self::Other(9),
TextNode::MathBoundary { .. } => Self::Other(10),
TextNode::MathBoundary { .. } | TextNode::Direction(_) => Self::Other(10),
}
}
fn vertical(node: &NativeVerticalNode) -> Self {
@@ -8,9 +8,9 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 67;
const COMPATIBLE_SCHEMAS: [u32; 34] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, SCHEMA,
const SCHEMA: u32 = 68;
const COMPATIBLE_SCHEMAS: [u32; 35] = [
27, 28, 31, 32, 33, 34, 35, 36, 37, 38, 39, 43, 44, 45, 46, 47, 48, 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 64, 65, 66, 67, SCHEMA,
];
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
@@ -6,6 +6,8 @@ mod case;
mod context;
mod device;
mod diagnostics;
mod direction;
pub use direction::DirectionBoundary;
mod engine;
#[cfg(all(target_os = "linux", target_env = "gnu"))]
pub use engine::pdf_match::{RegexOutcome, RegexRequest, match_pdf_regex};
@@ -79,6 +79,7 @@ pub enum TextNode {
AccentKern(i32),
AutoKern(i32),
MarginKern { width: i32, right: bool, font: FontId, slot: u8 },
Direction(DirectionBoundary),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph {
@@ -493,6 +494,7 @@ fn discardable(n: &TextNode) -> bool {
| TextNode::Leaders(_)
| TextNode::Kern { .. }
| TextNode::MathBoundary { .. }
| TextNode::Direction(_)
| TextNode::Penalty(_)
)
}
@@ -609,6 +611,7 @@ fn line_material(
width: 0,
explicit: *explicit,
},
TextNode::Direction(boundary) => TextNode::Direction(*boundary),
TextNode::MathBoundary { after, .. } => TextNode::MathBoundary {
width: 0,
after: *after,
@@ -735,7 +738,7 @@ fn break_lines(
forced: false,
})
}
BreakNode::Kern { explicit: true, .. } | BreakNode::MathBoundary { .. }
BreakNode::Kern { explicit: true, .. } | BreakNode::MathBoundary { .. } | BreakNode::Direction
if auto_breaking && matches!(projected.get(i + 1), Some(BreakNode::Glue(_))) =>
{
Some(Break {
@@ -943,7 +946,7 @@ fn break_lines(
TextNode::Discretionary { .. } => ParagraphBreakKind::Discretionary,
TextNode::Penalty(_) => ParagraphBreakKind::Penalty,
TextNode::Kern { .. } => ParagraphBreakKind::Kern,
TextNode::MathBoundary { .. } => ParagraphBreakKind::Math,
TextNode::MathBoundary { .. } | TextNode::Direction(_) => ParagraphBreakKind::Math,
_ => ParagraphBreakKind::Glue,
}
},
@@ -1068,6 +1071,7 @@ fn pack(
keep_par_fill: bool,
terminal_marker: bool,
ends_in_pre_break: bool,
direction_stack: &[super::direction::Region],
state: &mut State,
span: Span,
files: &mut impl SourceProvider,
@@ -1098,6 +1102,7 @@ fn pack(
Parameter::Parfillskip,
));
}
super::direction::close(&mut material, direction_stack);
material.push(TextNode::NamedGlue(
p[&Parameter::Rightskip].glue(),
Parameter::Rightskip,
@@ -1286,8 +1291,10 @@ pub(super) fn finish(
let mut packed_diagnostic = Vec::new();
let mut packed_shrinking = Vec::new();
let mut pre_display_size = -1073741823;
let directions = super::direction::has_directions(&b.nodes);
let mut direction_stack = Vec::new();
for (i, (point, bad)) in path.iter().enumerate() {
let material = line_material(
let mut material = line_material(
&b.nodes,
start,
point.end,
@@ -1304,6 +1311,10 @@ pub(super) fn finish(
|| matches!(b.nodes.get(point.end), Some(TextNode::Penalty(_)))
|| (point.pre_break.is_some() && !ends_in_pre_break);
let keep_par_fill = i + 1 == path.len() && (i == 0 || !material.is_empty());
if directions {
// Keep a real breakpoint marker before the synthetic line closers.
super::direction::line(&mut material, &mut direction_stack);
}
let (line, line_box, adjustments, shrinking) = pack(
&material,
&parameters,
@@ -1311,6 +1322,7 @@ pub(super) fn finish(
keep_par_fill,
terminal_marker,
ends_in_pre_break,
&direction_stack,
state,
b.span,
files,
@@ -1360,7 +1372,11 @@ pub(super) fn finish(
badness.push(*bad);
start = point.next;
post = point.pre_break;
// A retained zero-tail breakpoint is already included in the line.
while !has_post(&b.nodes, post) && start < b.nodes.len() && discardable(&b.nodes[start]) {
if directions {
super::direction::observe(&mut direction_stack, &b.nodes[start]);
}
start += 1;
}
}
@@ -1445,6 +1461,7 @@ fn add_hyphens(
.rev()
.find(|n| match n {
TextNode::Language(_)
| TextNode::Direction(_)
| TextNode::Output(_)
| TextNode::Kern {
explicit: false, ..
@@ -1484,6 +1501,7 @@ fn add_hyphens(
matches!(
n,
TextNode::Language(_)
| TextNode::Direction(_)
| TextNode::Adjustment(_)
| TextNode::Insertion(_)
| TextNode::Mark(_)
@@ -134,6 +134,7 @@ pub(super) enum BreakNode {
replacement_count: u8,
},
AccentKern(i32),
Direction,
}
impl BreakNode {
@@ -166,6 +167,7 @@ impl BreakNode {
after: *after,
},
TextNode::Penalty(penalty) => Self::Penalty(*penalty),
TextNode::Direction(_) => Self::Direction,
TextNode::Discretionary {
automatic,
pre_break,
@@ -184,7 +186,7 @@ impl BreakNode {
fn widths(self) -> Widths {
match self {
Self::Glue(glue) => Widths::glue(glue),
Self::Penalty(_) | Self::Discretionary { .. } => Widths::default(),
Self::Penalty(_) | Self::Discretionary { .. } | Self::Direction => Widths::default(),
Self::Content(natural) => Widths {
natural,
..Default::default()
@@ -211,7 +213,7 @@ impl BreakNode {
pub(super) fn discardable(&self) -> bool {
matches!(
self,
Self::Glue(_) | Self::Kern { .. } | Self::MathBoundary { .. } | Self::Penalty(_)
Self::Glue(_) | Self::Kern { .. } | Self::MathBoundary { .. } | Self::Direction | Self::Penalty(_)
)
}
}
@@ -98,6 +98,7 @@ fn skippable(node: &TextNode) -> bool {
| TextNode::AccentKern(0)
| TextNode::AutoKern(_)
| TextNode::MathBoundary { width: 0, .. }
| TextNode::Direction(_)
| TextNode::Kern { explicit: false, .. }
| TextNode::Kern { width: 0, .. } => true,
TextNode::Output(node) => node.dimensions().is_none(),
@@ -222,7 +222,7 @@ impl Tracer {
out.push(' ');
}
}
TextNode::MathBoundary { .. } => out.push('$'),
TextNode::MathBoundary { .. } | TextNode::Direction(_) => out.push('$'),
TextNode::Discretionary {
pre_break,
post_break,
@@ -122,6 +122,7 @@ pub enum Parameter {
XeTeXuseglyphmetrics,
XeTeXdashbreakstate,
Suppressfontnotfounderror,
TeXXeTstate,
}
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
pub enum ParameterValue {
@@ -278,11 +279,13 @@ impl Parameter {
Self::XeTeXuseglyphmetrics,
Self::XeTeXdashbreakstate,
Self::Suppressfontnotfounderror,
Self::TeXXeTstate,
];
pub fn name(self) -> String {
match self {
Self::XeTeXuseglyphmetrics => "XeTeXuseglyphmetrics".into(),
Self::XeTeXdashbreakstate => "XeTeXdashbreakstate".into(),
Self::TeXXeTstate => "TeXXeTstate".into(),
_ => format!("{self:?}").to_ascii_lowercase(),
}
}
@@ -381,6 +381,10 @@ pub enum Primitive {
Udelimiter,
Uradical,
Umathaccent,
BeginL,
EndL,
BeginR,
EndR,
}
impl Primitive {
@@ -1202,6 +1206,7 @@ impl Default for State {
| Parameter::Tracingnesting
| Parameter::Tracingassigns
| Parameter::Savingvdiscards
| Parameter::TeXXeTstate
) || Parameter::XETEX.contains(p) {
continue;
}
@@ -1491,6 +1496,7 @@ impl State {
);
}
self.install_xetex_etex_commands();
self.install_direction_commands();
self
}
pub fn register_limit(&self) -> u16 {
@@ -1647,6 +1653,7 @@ impl State {
}
self.install_unicode_commands();
self.install_xetex_etex_commands();
self.install_direction_commands();
self
}
@@ -1714,6 +1721,24 @@ impl State {
}
}
fn install_direction_commands(&mut self) {
let enabled = self.profile == Profile::EtexBootstrap
&& matches!(self.input_profile, super::InputProfile::TeX8Bit | super::InputProfile::XeTeX);
for (name, primitive) in [
("beginL", Primitive::BeginL),
("endL", Primitive::EndL),
("beginR", Primitive::BeginR),
("endR", Primitive::EndR),
] {
self.update_profile_command(name, Meaning::Primitive(primitive), enabled);
}
self.update_profile_command(
&Parameter::TeXXeTstate.name(),
Meaning::Parameter(Parameter::TeXXeTstate),
enabled,
);
}
pub(super) fn profile_primitive_name(&self, primitive: Primitive) -> Option<&'static str> {
if self.input_profile == super::InputProfile::XeTeX {
return XETEX_PRIMITIVE_ALIASES
@@ -206,3 +206,71 @@ fn xetex_format_preserves_internal_version_and_profile_identity() {
))
);
}
#[test]
fn xetex_formats_and_paints_nested_direction_spans() {
use texrra_tex_core::render::DisplayItem;
let profile_probe = r"\catcode123=1 \catcode125=2
\message{\meaning\TeXXeTstate/\meaning\beginR/\meaning\endR}\end";
let pdftex = run(
State::initex().with_input_profile(InputProfile::TeX8Bit).with_etex(),
profile_probe,
);
assert_eq!(messages(&pdftex), [r"\TeXXeTstate/\beginR/\endR"]);
let plain = run(State::initex().with_input_profile(InputProfile::XeTeX), profile_probe);
assert_eq!(messages(&plain), ["undefined/undefined/undefined"]);
let seed = r"\catcode123=1 \catcode125=2
\TeXXeTstate=1 \let\rtl\beginR
\setbox0=\hbox{\vrule width2pt height2pt
\rtl\message{\the\lastnodetype}\vrule width3pt height2pt
\beginL\vrule width4pt height2pt\vrule width5pt height2pt\endL
\vrule width6pt height2pt\endR
\vrule width7pt height2pt}\dump";
let state = State::initex().with_input_profile(InputProfile::XeTeX).with_etex();
let dump = run(state, seed);
assert_eq!(messages(&dump), ["10"]);
let image = FormatImage::from_dump(dump, Vec::new(), Vec::new()).unwrap();
let bytes = image.encode().unwrap();
let result = FormatImage::decode(&bytes)
.unwrap()
.new_job(
Profile::EtexBootstrap,
InputProfile::XeTeX,
JobTime::new(2025, 10, 9, 0).unwrap(),
Limits::default(),
|_| Ok(seed.as_bytes().to_vec()),
)
.unwrap()
.with_native_pages()
.run(
source(r"{\TeXXeTstate=0 \message{\the\TeXXeTstate}}
\message{\the\TeXXeTstate} \shipout\box0 \end"),
&mut TestDevice,
)
.unwrap();
assert_eq!(messages(&result), ["0", "1"]);
let page = result.events.iter().find_map(|event| match event {
Event::Shipout(page) => Some(page.display_list().unwrap()),
_ => None,
}).unwrap();
let rules: Vec<_> = page.items.iter().filter_map(|item| match item {
DisplayItem::Rule { x, width, .. } => Some((*x, *width)),
_ => None,
}).collect();
let origin = rules[0].0;
let offsets: Vec<_> = rules.iter().map(|(x, w)| (x - origin, *w)).collect();
assert_eq!(
offsets,
[(0, 2), (2, 6), (8, 4), (12, 5), (17, 3), (20, 7)].map(|(x, w)| (x * 65536, w * 65536))
);
let error = Executor::new(
State::initex().with_input_profile(InputProfile::XeTeX).with_etex(),
Limits::default(),
)
.run(source(r"\noindent\beginR"), &mut NoFiles)
.unwrap_err();
assert!(error.message.contains(r"Improper \beginR"));
}
+28
View File
@@ -2175,6 +2175,34 @@ PDF,恢复实际 PFB 并反转斜切时复用 1277 步,只替换第二页。
全量编译一致。incremental-receipt.json 的 SHA-256 为
bbc0991b0316e6d76aa58649ec873525f5544ab530d93fe491fc6e16bd00a27d。
### TeX--XeT 水平列表方向与 ACL Unicode 样稿
pdfTeX 和 XeTeX 的扩展 profile 执行 `\TeXXeTstate`、`\beginL`、
`\endL`、`\beginR` 和 `\endR`。方向标记保留在逻辑列表中,
可供拆盒、诊断和 `\lastnodetype` 查询。断开的段落行保存方向边界,
发页时从逻辑列表派生视觉遍历,经过嵌套水平盒及纵盒。胶水先按逻辑
顺序取整,同一视觉遍历用于字形、输出节点、位置和来源映射。schema68
保存实际方向节点和绑定,可继续读取近期旧格式。
[XeTeX 断行时恢复方向节点](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L19543-L19551)
[XeTeX 出页反射方向区段](https://github.com/TeX-Live/texlive-source/blob/trunk/texk/web2c/xetexdir/xetex.web#L29618-L29639)
四页参考覆盖拉丁和阿拉伯文、嵌套左右区段、跨行及延迟写入。
指定相同字号后的 108 个 XDV 字形、144 DPI 灰度图和实际文件写入顺序
一致。pdfTeX 的一页嵌套规则对照也逐像素相同。分组、节点类型、
关闭方向后报错和缺失结束标记的诊断已对照。16 项定向回归通过。
三页编辑只改变第二页的方向,复用 69 步,PDF、SVG、来源映射
以及写入文件与独立全量一致。旧 schema67 实际加载并输出一页。
早期探测的默认光学字号和
`papersize` 设备指令差异保留。
原样 ACL XeLaTeX 示例已经建立真实参考。新 schema68 用未改动的
`xelatex.ini` 转储。原生样稿越过 Babel 的方向初始化,在
`\babelfont` 到达编码能力检查。Babel 以 `\XeTeXinputencoding`
识别 XeTeX,后续要接入实际的文件解码和原始字节位置。参考已经覆盖
当前行读完后切换原始字节模式、下一源文件使用 UTF-16LE。证据位于
`target/p3-xetex-acl`。
[ACL 官方 XeLaTeX 模板入口](https://github.com/acl-org/acl-style-files/blob/d5adc823ff0f80f98c80405ca0ab66c68e684409/README.md)
### 段尾弃置节点与原样 NeurIPS 行号
断行候选从前一个断点越过可弃置的段尾节点时,搜索与装盒均丢弃末尾
+16
View File
@@ -685,6 +685,22 @@ IEEE 会议单项参数复验,原生与参考均生成1页且三轮 aux 逐字
`matrix-original-ieee/report.json` SHA-256 为
`0abb0304e0cab323cd9e52f515d69e02fe8ced5d9a84b3e20aa9c9dcfb7fb276`。
### ACL 官方 XeLaTeX Unicode 示例
复用已有 ACL 固定归档中的原样 `acl_lualatex.tex`。参考使用
XeTeX 2026 与真正的 `xdvipdfmx`,使用发行版提供的
`TeXGyreTermesX.fontspec`、TeX Gyre TermesX、Lohit Devanagari、
Noto Sans Arabic 及冻结 Type 1 映射。几次缺包和字体名称探测的日志已保留。
原参考生成 1 页,短样稿的正文位于双栏格式的左栏。页面含真实天城体和
阿拉伯文字。一次 BibTeX 与四轮 LaTeX 完成,第三轮和第四轮的 aux 一致。
[ACL 官方示例与引擎选择](https://github.com/acl-org/acl-style-files/blob/d5adc823ff0f80f98c80405ca0ab66c68e684409/README.md)
原生基线在 `\TeXXeTstate` 停止。实现真实左右区段和发页后,原样
入口进入 `\babelfont`。Babel 检查 `\XeTeXinputencoding` 时仍取到
未定义,原生该样稿还不能出页。模板、配置、实际字体指纹、原参考和
原生诊断见 `target/p3-xetex-acl`。
[阶段记录](P2_M1_PROGRESS.md#tex--xet-水平列表方向与-acl-unicode-样稿)
### 原样 Elsevier CAS 双栏与 NeurIPS 2025
以 `767c8ff`、既有真实 schema51 和参考格式复验官方 CAS 双栏。