Implement native text accents for unmodified LaTeX jobs

This commit is contained in:
gloamxun committed 2026-11-20 16:15:30 +08:00
1 parent ca60c66a17
commit 4eeb5686b8
16 files changed
+269 -18

No files matched your search

@@ -332,6 +332,7 @@ impl NativeBox {
}
TextNode::Indent(w)
| TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w)
| TextNode::Kern { width: w, .. } => HorizontalItem::Box(HorizontalBox {
width: *w as i64,
..HorizontalBox::default()
@@ -612,6 +613,7 @@ pub(super) fn hpack(
}
TextNode::Indent(w)
| TextNode::MathBoundary { width: w, .. }
| TextNode::AccentKern(w)
| TextNode::Kern { width: w, .. } => width += *w as i64,
TextNode::Glue(g) | TextNode::NamedGlue(g, _) => {
width += g.width as i64;
@@ -50,6 +50,7 @@ pub enum DiagnosticNode {
},
Output(OutputNode),
Unsupported(String),
AccentKern(i32),
}
/// A semantic view, without recursively copying the box's painted contents.
#[derive(Clone, Debug, PartialEq, Eq, Hash, serde::Serialize, serde::Deserialize)]
@@ -209,6 +210,7 @@ pub(super) fn text_nodes(nodes: &[TextNode]) -> Vec<DiagnosticNode> {
name: None,
},
TextNode::Leaders(leader) => leader_node(leader),
TextNode::AccentKern(width) => DiagnosticNode::AccentKern(*width),
TextNode::Kern { width, explicit } => DiagnosticNode::Kern {
width: *width,
explicit: *explicit,
@@ -471,6 +473,12 @@ impl Printer<'_> {
&format!("{prefix}."),
)?;
}
DiagnosticNode::AccentKern(width) => {
self.command("kern");
self.literal(" ");
self.number(i64::from(*width));
self.literal(" (for accent)");
}
DiagnosticNode::Kern { width, explicit } => {
self.command("kern");
if *explicit {
+16 -1
View File
@@ -3393,6 +3393,7 @@ impl Executor {
)) | Meaning::CharGiven(_)
| Meaning::Primitive(
Primitive::Char
| Primitive::Accent
| Primitive::Hskip
| Primitive::Hfil
| Primitive::Hfill
@@ -3565,6 +3566,7 @@ impl Executor {
}
Unskip | Unkern | Unpenalty => self.delete_last(primitive)?,
ItalicCorrection => self.append_italic_correction()?,
Accent => self.text_accent(&token, files)?,
Shipout => self.scan_box(boxes::Destination::Shipout, files)?,
Leaders | Cleaders | Xleaders => self.scan_leaders(primitive, files)?,
Vrule => {
@@ -3741,13 +3743,23 @@ impl Executor {
key: Option<Key>,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.assignment_inner(primitive, key, files)?;
self.assignment_with_box_policy(primitive, key, true, files)
}
fn assignment_with_box_policy(
&mut self,
primitive: Option<Primitive>,
key: Option<Key>,
allow_setbox: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
self.assignment_inner(primitive, key, allow_setbox, files)?;
self.finish_assignment()
}
fn assignment_inner(
&mut self,
mut primitive: Option<Primitive>,
mut key: Option<Key>,
allow_setbox: bool,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use Primitive::*;
@@ -3918,6 +3930,9 @@ impl Executor {
}
Some(Parshape) => self.scan_paragraph_shape(global, files)?,
Some(Setbox) => {
if !allow_setbox {
return self.fail("improper native setbox in an assignment prefix");
}
let n = self.register_index(files)?;
self.optional_equals(files)?;
if self
@@ -276,7 +276,7 @@ impl Executor {
};
}
if self.meaning(&t.token) == Meaning::Parameter(Parameter::Tabskip) {
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), files)?;
self.assignment_inner(None, Some(Key::Parameter(Parameter::Tabskip)), true, files)?;
} else {
return Ok(t);
}
@@ -249,6 +249,7 @@ impl Executor {
n,
TextNode::Glyph { .. }
| TextNode::Kern { .. }
| TextNode::AccentKern(_)
| TextNode::Box(_)
| TextNode::Indent(_)
| TextNode::Rule(_)
@@ -312,7 +312,7 @@ impl Executor {
self.display.as_mut().unwrap().alignment = Some(list);
// fin_align's do_assignments runs in the empty display math list. In
// particular, the second closing shift is expanded before pop_nest.
let close = self.display_assignments(files)?;
let close = self.assignments_before_content(true, files)?;
if !matches!(
self.meaning(&close.token),
Meaning::Character(TokenKind::Character(_, CatCode::MathShift))
@@ -353,14 +353,19 @@ impl Executor {
self.display.take().unwrap();
self.resume_after_display(span, files)
}
fn display_assignments(
pub(super) fn assignments_before_content(
&mut self,
allow_setbox: bool,
files: &mut impl SourceProvider,
) -> Result<InputToken, Error> {
use Primitive::*;
loop {
let t = self.expanded_non_space(files)?;
match self.meaning(&t.token) {
let meaning = self.meaning(&t.token);
if !allow_setbox && Self::suppresses_meaning(&t, &meaning) {
continue;
}
match meaning {
Meaning::Primitive(Relax) => continue,
Meaning::Primitive(p)
if p.page_dimension().is_some()
@@ -431,7 +436,7 @@ impl Executor {
| Insertpenalties
) =>
{
self.assignment(Some(p), None, files)?
self.assignment_with_box_policy(Some(p), None, allow_setbox, files)?
}
Meaning::Count(n) => self.assignment(None, Some(Key::Count(n)), files)?,
Meaning::Toks(n) => self.assignment(None, Some(Key::Toks(n)), files)?,
@@ -20,7 +20,7 @@ impl Tail {
TextNode::Glue(g)
| TextNode::NamedGlue(g, _)
| TextNode::Leaders(LeaderGlue { glue: g, .. }) => Self::Glue(*g, false),
TextNode::Kern { width, .. } => Self::Kern(*width),
TextNode::Kern { width, .. } | TextNode::AccentKern(width) => Self::Kern(*width),
TextNode::Penalty(n) => Self::Penalty(*n),
TextNode::Glyph { ligature, .. } => Self::Other(if *ligature { 7 } else { 0 }),
TextNode::MathChar(_) => Self::Other(0),
@@ -1,5 +1,128 @@
use super::*;
use crate::provenance::{Derivation, PaintSource};
fn accent_glyph(state: &State, font: FontId, slot: u8, token: &Token, accent: bool) -> TextNode {
let origin = TokenOrigin::from(token);
let source = PaintSource::token(origin);
let source = if accent {
source.derived(Derivation::Accent)
} else {
source
};
let glyph = super::super::fonts::text_glyph(state, font, slot, source.clone());
TextNode::Glyph {
font,
glyph,
slot,
original: char::from(slot).to_string(),
ligature: false,
left_boundary: false,
right_boundary: false,
origins: vec![origin.span],
component_sources: vec![source],
hyphen_char: state.hyphen_character(font),
}
}
impl Executor {
pub(super) fn text_accent(
&mut self,
token: &Token,
files: &mut impl SourceProvider,
) -> Result<(), Error> {
use super::super::boxes::{PackSpec, hpack};
if !self.math.is_empty() {
return self.fail("a text accent in math mode requires a math accent");
}
let span = token.invocation.unwrap_or(token.span);
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::TextFont);
self.reads.insert(Dependency::FontResources);
let slot = self.integer(files)?;
let slot = u8::try_from(slot)
.map_err(|_| self.error("native accent character must be in 0..255", span))?;
let font = self.state.text_font();
if !self.state.font_has_slot(font, slot) {
return self.missing_glyph(font, slot, span, files);
}
let accent_font = self
.state
.fonts
.font(font)
.map_err(|error| self.error(error, span))?;
let x_height = i64::from(accent_font.x_height());
let accent_slant = f64::from(accent_font.parameters()[0]) / 65_536.0;
let mut accent = accent_glyph(&self.state, font, slot, token, true);
let base = self.assignments_before_content(false, files)?;
let base_slot = match self.meaning(&base.token) {
Meaning::Character(TokenKind::Character(c, CatCode::Letter | CatCode::Other)) => {
Some(i32::try_from(u32::from(c)).expect("a Unicode scalar fits i32"))
}
Meaning::CharGiven(c) => Some(i32::from(c)),
Meaning::Primitive(Primitive::Char) => Some(self.integer(files)?),
_ => None,
};
let mut assembled = Vec::with_capacity(4);
if let Some(base_slot) = base_slot {
let base_span = base.token.invocation.unwrap_or(base.token.span);
let base_slot = u8::try_from(base_slot).map_err(|_| {
self.error("native accent base character must be in 0..255", base_span)
})?;
let base_font = self.state.text_font();
if self.state.font_has_slot(base_font, base_slot) {
let font = self
.state
.fonts
.font(base_font)
.map_err(|error| self.error(error, base_span))?;
let base_slant = f64::from(font.parameters()[0]) / 65_536.0;
let base_node = accent_glyph(&self.state, base_font, base_slot, &base.token, false);
let TextNode::Glyph { glyph: mark, .. } = &accent else {
unreachable!("a text accent begins with its character");
};
let TextNode::Glyph { glyph: base, .. } = &base_node else {
unreachable!("an accent base is an unshaped character");
};
let shift = x_height - base.height;
let left = (((base.width - mark.width) as f64) / 2.0
+ base.height as f64 * base_slant
- x_height as f64 * accent_slant)
.round() as i64;
let right = -mark.width - left;
let kern = |width| {
i32::try_from(width)
.map(TextNode::AccentKern)
.map_err(|_| self.error("native accent kern exceeds capacity", span))
};
let left = kern(left)?;
let right = kern(right)?;
if shift != 0 {
self.reads.insert(Dependency::BoxPackState);
let mut shifted = hpack(vec![accent], PackSpec::Natural, span, &self.state)
.map_err(|error| self.error(error, span))?;
self.state.last_badness = shifted.badness;
shifted.shift = shift;
accent = TextNode::Box(shifted.horizontal_item());
}
assembled.extend([left, accent, right, base_node]);
} else {
self.missing_glyph(base_font, base_slot, base_span, files)?;
assembled.push(accent);
}
} else {
self.unread(base)?;
assembled.push(accent);
}
let paragraph = self
.paragraph
.as_mut()
.expect("the text accent starts horizontal mode");
paragraph.nodes.extend(assembled);
paragraph.space_factor = 1000;
Ok(())
}
pub(super) fn append_italic_correction(&mut self) -> Result<(), Error> {
self.reads.insert(Dependency::ParagraphMode);
self.reads.insert(Dependency::BoxPackState);
@@ -8,7 +8,8 @@ use std::{
sync::{Arc, Mutex, OnceLock, Weak},
};
const SCHEMA: u32 = 27;
const SCHEMA: u32 = 28;
const PREVIOUS_SCHEMA: u32 = 27;
const ENGINE: &str = concat!("texrra-native/", env!("CARGO_PKG_VERSION"));
#[derive(serde::Serialize, serde::Deserialize)]
@@ -105,16 +106,16 @@ impl FormatImage {
schema: u32,
engine: String,
}
// Check identity before decoding state: old schemas can lack fields
// which the current kernel must own, even with a valid checksum.
// Schema 28 adds primitive and node variants. All schema 27 state
// fields and variants remain readable with their original meanings.
let identity: Identity =
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
if identity.schema != SCHEMA || identity.engine != ENGINE {
if !matches!(identity.schema, PREVIOUS_SCHEMA | SCHEMA) || identity.engine != ENGINE {
return Err("incompatible native format image".into());
}
let image: Self =
serde_json::from_str(&envelope.payload).map_err(|error| error.to_string())?;
if image.schema != SCHEMA
if image.schema != identity.schema
|| image.engine != ENGINE
|| image.state.is_initex()
|| image.state.group_depth() != 0
@@ -70,6 +70,8 @@ pub enum TextNode {
post_break: Vec<TextNode>,
replacement_count: u8,
},
/// Spacing owned by a text accent and protected from leading discard.
AccentKern(i32),
}
#[derive(Clone, Debug, PartialEq, Eq, serde::Serialize, serde::Deserialize)]
pub struct NativeParagraph {
@@ -383,6 +385,7 @@ fn width(n: &TextNode) -> i64 {
TextNode::Rule(r) => r.dimensions().0,
TextNode::Output(node) => node.dimensions().map_or(0, |(width, _, _)| width),
TextNode::Kern { width: n, .. }
| TextNode::AccentKern(n)
| TextNode::MathBoundary { width: n, .. }
| TextNode::Indent(n) => *n as i64,
_ => 0,
@@ -584,6 +587,7 @@ fn break_lines(
&& matches!(
projected[i - 1],
BreakNode::Content(_)
| BreakNode::AccentKern(_)
| BreakNode::Discretionary { .. }
| BreakNode::Kern {
explicit: false,
@@ -1316,6 +1320,7 @@ fn add_hyphens(
| TextNode::NamedGlue(_, _)
| TextNode::Leaders(_)
| TextNode::Penalty(_)
| TextNode::AccentKern(_)
| TextNode::Kern { explicit: true, .. }
)
})
@@ -128,6 +128,7 @@ pub(super) enum BreakNode {
post_break: Option<Widths>,
replacement_count: u8,
},
AccentKern(i32),
}
impl BreakNode {
@@ -146,6 +147,7 @@ impl BreakNode {
TextNode::Glue(glue)
| TextNode::NamedGlue(glue, _)
| TextNode::Leaders(LeaderGlue { glue, .. }) => Self::Glue(*glue),
TextNode::AccentKern(width) => Self::AccentKern(*width),
TextNode::Kern { width, explicit } => Self::Kern {
width: *width,
explicit: *explicit,
@@ -178,7 +180,9 @@ impl BreakNode {
natural,
..Default::default()
},
Self::Kern { width, .. } | Self::MathBoundary { width, .. } => Widths {
Self::Kern { width, .. }
| Self::AccentKern(width)
| Self::MathBoundary { width, .. } => Widths {
natural: i64::from(width),
..Default::default()
},
@@ -230,7 +230,7 @@ impl<'a> Tracer<'a> {
self.short(post_break, out)?;
i += usize::from(*replacement_count);
}
TextNode::Kern { .. } | TextNode::Penalty(_) => {}
TextNode::Kern { .. } | TextNode::AccentKern(_) | TextNode::Penalty(_) => {}
}
i += 1;
}
@@ -312,6 +312,7 @@ pub enum Primitive {
Overwithdelims,
Atopwithdelims,
Abovewithdelims,
Accent,
}
impl Primitive {
@@ -722,6 +723,7 @@ impl Default for State {
("radical", Radical),
("left", Left),
("right", Right),
("accent", Accent),
("mathaccent", Mathaccent),
("mathchoice", Mathchoice),
("overline", Overline),