Render hyperlinks with hyperref green colour

This commit is contained in:
gloamxun committed 2026-10-19 18:29:24 +08:00
1 parent a8b20563fb
commit 09781d40e9
12 files changed
+158 -11

No files matched your search

+3 -1
View File
@@ -361,7 +361,9 @@ platform path separator for multiple directories). A local style can use
local package options, arbitrary TeX code, and the full LaTeX package ecosystem local package options, arbitrary TeX code, and the full LaTeX package ecosystem
are not implemented. These LaTeX command are not implemented. These LaTeX command
definitions support up to nine parameters, including one optional first definitions support up to nine parameters, including one optional first
parameter with a default value. Unknown packages fail with a clear error. parameter with a default value. Unknown packages fail with a clear error. Hyperlinks (`\href`, `\url`, and
resolved citations) use hyperref's green link colour; PDF link annotations are
not emitted.
`\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file. `\includegraphics` embeds PNG, JPEG, or BMP files relative to the `.tex` file.
It supports `width`, `height`, and `scale`; width and height accept physical It supports `width`, `height`, and `scale`; width and height accept physical
+7
View File
@@ -201,6 +201,10 @@ pub struct PageStyleOverride {
/// Marker character used by `\thepage` inside header/footer runs; the page /// Marker character used by `\thepage` inside header/footer runs; the page
/// renderer substitutes the concrete page number before measuring and painting. /// renderer substitutes the concrete page number before measuring and painting.
/// Private-use marker for a dotted leader in generated contents lines. /// Private-use marker for a dotted leader in generated contents lines.
/// Private-use marker toggling hyperlink paint for the following glyphs.
pub const LINK_START_MARKER: char = '\u{F3000}';
pub const LINK_END_MARKER: char = '\u{F3001}';
pub const CONTENTS_LEADER_MARKER: char = '\u{F6000}'; pub const CONTENTS_LEADER_MARKER: char = '\u{F6000}';
pub const PAGE_NUMBER_MARKER: char = '\u{F5000}'; pub const PAGE_NUMBER_MARKER: char = '\u{F5000}';
@@ -413,6 +417,8 @@ pub struct Run {
pub monospace: bool, pub monospace: bool,
pub sans: bool, pub sans: bool,
pub small_caps: bool, pub small_caps: bool,
/// Hyperlink text (rendered in the hyperref link colour).
pub link: bool,
/// True for the synthetic kern that carries paragraph indentation. /// True for the synthetic kern that carries paragraph indentation.
pub paragraph_indent: bool, pub paragraph_indent: bool,
/// Alignment declaration active when this run started its paragraph. /// Alignment declaration active when this run started its paragraph.
@@ -437,6 +443,7 @@ impl Run {
monospace: false, monospace: false,
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
paragraph_indent: false, paragraph_indent: false,
alignment: None, alignment: None,
} }
+25
View File
@@ -464,6 +464,7 @@ struct Parser {
text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool, bool)>, text_style_stack: Vec<(expanded::TextStyle, bool, bool, bool, bool, bool)>,
style_declarations: Vec<(usize, expanded::TextStyle)>, style_declarations: Vec<(usize, expanded::TextStyle)>,
group_depth: usize, group_depth: usize,
link_depth: usize,
section_numbers: [u32; 4], section_numbers: [u32; 4],
has_chapters: bool, has_chapters: bool,
equation_number: u32, equation_number: u32,
@@ -575,6 +576,7 @@ impl Parser {
text_style_stack: Vec::new(), text_style_stack: Vec::new(),
style_declarations: Vec::new(), style_declarations: Vec::new(),
group_depth: 0, group_depth: 0,
link_depth: 0,
section_numbers: [0; 4], section_numbers: [0; 4],
has_chapters: false, has_chapters: false,
equation_number: 0, equation_number: 0,
@@ -885,6 +887,7 @@ impl Parser {
monospace, monospace,
sans, sans,
small_caps, small_caps,
link: self.link_depth > 0,
paragraph_indent: false, paragraph_indent: false,
alignment: None, alignment: None,
}; };
@@ -932,6 +935,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
@@ -1148,6 +1152,12 @@ impl Parser {
} }
expanded::FrontendEventKind::LiteralAmpersand expanded::FrontendEventKind::LiteralAmpersand
| expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(), | expanded::FrontendEventKind::MathCell => self.append_literal_ampersand(),
expanded::FrontendEventKind::LinkStart => {
self.link_depth = self.link_depth.saturating_add(1);
}
expanded::FrontendEventKind::LinkEnd => {
self.link_depth = self.link_depth.saturating_sub(1);
}
expanded::FrontendEventKind::LiteralCharacter(character) => { expanded::FrontendEventKind::LiteralCharacter(character) => {
self.append_text(&character.to_string()) self.append_text(&character.to_string())
} }
@@ -1410,6 +1420,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
@@ -1503,6 +1514,7 @@ impl Parser {
let monospace = self.monospace; let monospace = self.monospace;
let sans = self.sans; let sans = self.sans;
let small_caps = self.small_caps; let small_caps = self.small_caps;
let link = self.link_depth > 0;
if self.table.is_some() { if self.table.is_some() {
let mut pieces = text.split('&').peekable(); let mut pieces = text.split('&').peekable();
while let Some(piece) = pieces.next() { while let Some(piece) = pieces.next() {
@@ -1514,6 +1526,7 @@ impl Parser {
monospace, monospace,
sans, sans,
small_caps, small_caps,
link,
); );
if pieces.peek().is_some() { if pieces.peek().is_some() {
self.finish_table_cell(); self.finish_table_cell();
@@ -1528,6 +1541,7 @@ impl Parser {
monospace, monospace,
sans, sans,
small_caps, small_caps,
link,
); );
} }
let alignment = self.paragraph_alignment; let alignment = self.paragraph_alignment;
@@ -1576,6 +1590,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
@@ -1614,6 +1629,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
@@ -1657,6 +1673,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
@@ -1710,6 +1727,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
@@ -1804,6 +1822,7 @@ impl Parser {
let monospace = self.monospace; let monospace = self.monospace;
let sans = self.sans; let sans = self.sans;
let small_caps = self.small_caps; let small_caps = self.small_caps;
let link = self.link_depth > 0;
append_run( append_run(
self.target_runs(), self.target_runs(),
"&".to_string(), "&".to_string(),
@@ -1812,6 +1831,7 @@ impl Parser {
monospace, monospace,
sans, sans,
small_caps, small_caps,
link,
); );
} }
@@ -1850,6 +1870,7 @@ impl Parser {
sans: false, sans: false,
small_caps: false, small_caps: false,
link: true,
y_offset: None, y_offset: None,
@@ -2368,6 +2389,7 @@ fn indent_run(indent: common::Scaled) -> Run {
monospace: false, monospace: false,
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
footnote_number: None, footnote_number: None,
paragraph_indent: true, paragraph_indent: true,
@@ -2415,6 +2437,7 @@ fn append_run(
monospace: bool, monospace: bool,
sans: bool, sans: bool,
small_caps: bool, small_caps: bool,
link: bool,
) { ) {
if text.is_empty() { if text.is_empty() {
return; return;
@@ -2438,6 +2461,7 @@ fn append_run(
&& last.monospace == monospace && last.monospace == monospace
&& last.sans == sans && last.sans == sans
&& last.small_caps == small_caps && last.small_caps == small_caps
&& last.link == link
{ {
last.text.push_str(&text); last.text.push_str(&text);
return; return;
@@ -2456,6 +2480,7 @@ fn append_run(
monospace, monospace,
sans, sans,
small_caps, small_caps,
link,
paragraph_indent: false, paragraph_indent: false,
alignment: None, alignment: None,
+4
View File
@@ -264,6 +264,10 @@ pub enum FrontendEventKind {
header: bool, header: bool,
}, },
PageNumber, PageNumber,
/// Start of hyperlink material.
LinkStart,
/// End of hyperlink material.
LinkEnd,
/// A package or class was loaded from a local file. /// A package or class was loaded from a local file.
PackageLoaded(String), PackageLoaded(String),
/// A separator between author blocks (LaTeX's \And). /// A separator between author blocks (LaTeX's \And).
+1 -1
View File
@@ -15,7 +15,7 @@ chapter headings with chapter-prefixed section numbering and page breaks;
deferred top-float queue for figures; document-level custom `\maketitle`; deferred top-float queue for figures; document-level custom `\maketitle`;
abstract quotation formatting, unnumbered `\paragraph` headings, natbib-style abstract quotation formatting, unnumbered `\paragraph` headings, natbib-style
author-year citations and plainnat bibliography formatting with duplicate-year author-year citations and plainnat bibliography formatting with duplicate-year
`2014a`/`2014b` suffixes; `2014a`/`2014b` suffixes; hyperref-style green `\href`/`\url`/citation text;
`\vbox`/`\vtop` vertical-material capture with inline splicing `\vbox`/`\vtop` vertical-material capture with inline splicing
(`build_positioned_pages` is the only page builder and no separate break (`build_positioned_pages` is the only page builder and no separate break
planner remains); conditional Base-14 font embedding and natural-width centered planner remains); conditional Base-14 font embedding and natural-width centered
+3 -3
View File
@@ -103,8 +103,8 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- Contents: chapter headings are listed with chapter-prefixed section - Contents: chapter headings are listed with chapter-prefixed section
numbers, but contents are not split per chapter. numbers, but contents are not split per chapter.
- Preprint title blocks: ORCID icons embedded in `\author` are dropped because - Preprint title blocks: ORCID icons embedded in `\author` are dropped because
metadata does not carry PDF images, and links/URLs remain plain black text metadata does not carry images. Hyperlinks use hyperref's green text colour;
instead of colored hyperref links. Title-block vertical spacing is tighter PDF link annotations are not emitted. Title-block vertical spacing is tighter
than the reference class. than the reference class.
## Verification ## Verification
@@ -114,7 +114,7 @@ See `docs/ROADMAP.md` for concrete implementation plans.
- ASCII-only documents use non-embedded Base-14 Times/Courier (arXiv PDF is - ASCII-only documents use non-embedded Base-14 Times/Courier (arXiv PDF is
about 0.7 MB); documents with accented/non-WinAnsi text embed Liberation about 0.7 MB); documents with accented/non-WinAnsi text embed Liberation
faces. Tables use natural column widths and centered rules. faces. Tables use natural column widths and centered rules.
- `cargo fmt --check` passes; `cargo test --offline` (48 tests: 44 compiler - `cargo fmt --check` passes; `cargo test --offline` (49 tests: 45 compiler
integration tests + 4 server tests) covers the three examples, the arXiv integration tests + 4 server tests) covers the three examples, the arXiv
fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output, fixture, figure/table floats (top and bottom), newpage, page styles and `\thispagestyle`, SVG/PDF output,
project API, static frontend assets, path traversal, the legacy project API, static frontend assets, path traversal, the legacy
+1 -1
View File
@@ -74,7 +74,7 @@ const PRELUDE: &str = r#"
\def\nocite#1{} \def\nocite#1{}
\def\newblock{ } \def\newblock{ }
\def\caption#1{\texrracaptionstart#1\texrracaptionend} \def\caption#1{\texrracaptionstart#1\texrracaptionend}
\def\href#1#2{#2} \def\href#1#2{\texrrahref{#2}}
\def\hline{\texrratablerule} \def\hline{\texrratablerule}
\def\toprule{\texrratablerule} \def\toprule{\texrratablerule}
\def\midrule{\texrratablerule} \def\midrule{\texrratablerule}
+29
View File
@@ -1417,6 +1417,15 @@ fn boxworks_line_break(
); );
} }
} }
if run.link {
horizontal.push(
ds::Char {
char: texrra_core::document::LINK_START_MARKER,
font: null_font_id,
}
.into(),
);
}
horizontal.push( horizontal.push(
ds::Char { ds::Char {
char: glyph_character, char: glyph_character,
@@ -1424,6 +1433,15 @@ fn boxworks_line_break(
} }
.into(), .into(),
); );
if run.link {
horizontal.push(
ds::Char {
char: texrra_core::document::LINK_END_MARKER,
font: null_font_id,
}
.into(),
);
}
previous_character = Some(glyph_character); previous_character = Some(glyph_character);
previous_font_id = Some(font_id); previous_font_id = Some(font_id);
} }
@@ -1516,6 +1534,7 @@ fn boxworks_line_break(
} }
let mut line_items = Vec::new(); let mut line_items = Vec::new();
let mut leader_pending = false; let mut leader_pending = false;
let mut link_state = false;
for item in &line_box.list { for item in &line_box.list {
match item { match item {
ds::Horizontal::Char(character) => { ds::Horizontal::Char(character) => {
@@ -1523,6 +1542,14 @@ fn boxworks_line_break(
leader_pending = true; leader_pending = true;
continue; continue;
} }
if character.char == texrra_core::document::LINK_START_MARKER {
link_state = true;
continue;
}
if character.char == texrra_core::document::LINK_END_MARKER {
link_state = false;
continue;
}
if let Some(marker) = inline_markers.get(&character.char) { if let Some(marker) = inline_markers.get(&character.char) {
match marker { match marker {
InlineMarker::RaiseStart(raise) => { InlineMarker::RaiseStart(raise) => {
@@ -1563,6 +1590,7 @@ fn boxworks_line_break(
italic, italic,
monospace, monospace,
sans, sans,
link: link_state,
font_size: glyph_size, font_size: glyph_size,
y_offset, y_offset,
}); });
@@ -2469,6 +2497,7 @@ pub(super) fn render_pdf(
sans: false, sans: false,
small_caps: false, small_caps: false,
link: false,
y_offset: None, y_offset: None,
+2
View File
@@ -1039,6 +1039,7 @@ fn layout_framed_runs(
italic: run.italic, italic: run.italic,
monospace: run.monospace, monospace: run.monospace,
sans: run.sans, sans: run.sans,
link: run.link,
font_size: glyph_size, font_size: glyph_size,
y_offset: run.y_offset.unwrap_or_default(), y_offset: run.y_offset.unwrap_or_default(),
}); });
@@ -3326,6 +3327,7 @@ pub(super) fn text_line_metrics_scaled(
italic, italic,
monospace, monospace,
sans, sans,
link: _,
font_size: glyph_size, font_size: glyph_size,
y_offset, y_offset,
} = item } = item
+41
View File
@@ -3171,6 +3171,7 @@ fn url_primitive(
} }
_ => argument.as_slice(), _ => argument.as_slice(),
}; };
write_event(input, token, FrontendEventKind::LinkStart);
write_event( write_event(
input, input,
token, token,
@@ -3202,6 +3203,7 @@ fn url_primitive(
token, token,
FrontendEventKind::TextStyleEnd(TextStyle::Monospace), FrontendEventKind::TextStyleEnd(TextStyle::Monospace),
); );
write_event(input, token, FrontendEventKind::LinkEnd);
Ok(()) Ok(())
} }
@@ -3655,6 +3657,33 @@ fn vbox_end_primitive(
Ok(()) Ok(())
} }
fn href_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
// The prelude macro consumes the URL argument; this primitive only sees the
// visible link text, which is wrapped in a link span for hyperref colour.
let content = read_unexpanded_argument(input, token, "expects link text")?;
let inner = strip_braced_tokens(&content).to_vec();
write_event(input, token, FrontendEventKind::LinkStart);
let trace_key = token.trace_key();
let mut expansion = inner;
expansion.push(control_sequence_token(input, "texrralinkend", trace_key));
input
.as_mut()
.expansions_mut()
.extend(expansion.into_iter().rev());
Ok(())
}
fn link_end_primitive(
token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>,
) -> texlang::prelude::Result<()> {
write_event(input, token, FrontendEventKind::LinkEnd);
Ok(())
}
fn fbox_primitive( fn fbox_primitive(
token: token::Token, token: token::Token,
input: &mut vm::ExecutionInput<CompilerState>, input: &mut vm::ExecutionInput<CompilerState>,
@@ -7696,6 +7725,18 @@ fn built_in_commands() -> HashMap<&'static str, texlang::command::BuiltIn<Compil
"includegraphics", "includegraphics",
texlang::command::BuiltIn::new_execution(includegraphics_command_primitive), texlang::command::BuiltIn::new_execution(includegraphics_command_primitive),
); );
built_ins.insert(
"href",
texlang::command::BuiltIn::new_execution(href_primitive),
);
built_ins.insert(
"texrrahref",
texlang::command::BuiltIn::new_execution(href_primitive),
);
built_ins.insert(
"texrralinkend",
texlang::command::BuiltIn::new_execution(link_end_primitive),
);
built_ins.insert( built_ins.insert(
"fam", "fam",
texlang::variable::Command::new_singleton( texlang::variable::Command::new_singleton(
+29 -5
View File
@@ -24,6 +24,7 @@ pub(super) enum LineItem {
italic: bool, italic: bool,
monospace: bool, monospace: bool,
sans: bool, sans: bool,
link: bool,
font_size: u8, font_size: u8,
y_offset: Scaled, y_offset: Scaled,
}, },
@@ -48,12 +49,14 @@ pub(super) enum LineItem {
struct TextSpan { struct TextSpan {
text: String, text: String,
style: Style, style: Style,
link: bool,
y_offset: Mm, y_offset: Mm,
} }
pub(super) struct PositionedSpan { pub(super) struct PositionedSpan {
pub(super) text: String, pub(super) text: String,
pub(super) style: Style, pub(super) style: Style,
pub(super) link: bool,
pub(super) x: Mm, pub(super) x: Mm,
pub(super) y_offset: Mm, pub(super) y_offset: Mm,
} }
@@ -137,6 +140,7 @@ impl TextLine {
italic, italic,
monospace, monospace,
sans, sans,
link,
font_size: glyph_size, font_size: glyph_size,
y_offset, y_offset,
} if is_cjk(*character) => { } if is_cjk(*character) => {
@@ -161,7 +165,9 @@ impl TextLine {
monospace_family, monospace_family,
sans_family, sans_family,
*glyph_size, *glyph_size,
*link,
), ),
link: *link,
y_offset: scaled_to_mm(*y_offset), y_offset: scaled_to_mm(*y_offset),
})); }));
} }
@@ -171,10 +177,19 @@ impl TextLine {
italic, italic,
monospace, monospace,
sans, sans,
link,
font_size: glyph_size, font_size: glyph_size,
y_offset, y_offset,
} => { } => {
let style_key = (*bold, *italic, *monospace, *sans, *glyph_size, *y_offset); let style_key = (
*bold,
*italic,
*monospace,
*sans,
*link,
*glyph_size,
*y_offset,
);
if text_style != Some(style_key) { if text_style != Some(style_key) {
flush_text( flush_text(
&mut items, &mut items,
@@ -396,6 +411,7 @@ impl TextLine {
spans.push(PositionedSpan { spans.push(PositionedSpan {
text: span.text.clone(), text: span.text.clone(),
style: span.style, style: span.style,
link: span.link,
x, x,
y_offset: span.y_offset, y_offset: span.y_offset,
}); });
@@ -426,6 +442,7 @@ impl TextLine {
spans.push(PositionedSpan { spans.push(PositionedSpan {
text: leader, text: leader,
style, style,
link: false,
x, x,
y_offset: Mm::from(0.0), y_offset: Mm::from(0.0),
}); });
@@ -504,10 +521,11 @@ impl TextLine {
}; };
let _ = write!( let _ = write!(
output, output,
"<text x=\"{:.4}\" y=\"{:.4}\" xml:space=\"preserve\" font-family=\"{family}\" font-size=\"{:.4}\" font-weight=\"{weight}\" font-style=\"{slant}\">{}</text>", "<text x=\"{:.4}\" y=\"{:.4}\" xml:space=\"preserve\" font-family=\"{family}\" font-size=\"{:.4}\" font-weight=\"{weight}\" font-style=\"{slant}\"{}>{}</text>",
f64::from(x + horizontal_offset + span.x), f64::from(x + horizontal_offset + span.x),
f64::from(baseline - span.y_offset), f64::from(baseline - span.y_offset),
svg_font_size(span.style.font_size()), svg_font_size(span.style.font_size()),
if span.link { " fill=\"#008000\"" } else { "" },
escape_html(&span.text), escape_html(&span.text),
); );
} }
@@ -517,7 +535,7 @@ impl TextLine {
fn flush_text( fn flush_text(
items: &mut Vec<TextLineItem>, items: &mut Vec<TextLineItem>,
text: &mut String, text: &mut String,
style_key: &mut Option<(bool, bool, bool, bool, u8, Scaled)>, style_key: &mut Option<(bool, bool, bool, bool, bool, u8, Scaled)>,
cjk_family: Option<FontFamily<fonts::Font>>, cjk_family: Option<FontFamily<fonts::Font>>,
monospace_family: Option<FontFamily<fonts::Font>>, monospace_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>, sans_family: Option<FontFamily<fonts::Font>>,
@@ -527,10 +545,10 @@ fn flush_text(
*style_key = None; *style_key = None;
return; return;
} }
let (bold, italic, monospace, sans, glyph_size, y_offset) = let (bold, italic, monospace, sans, link, glyph_size, y_offset) =
style_key style_key
.take() .take()
.unwrap_or((false, false, false, false, font_size, Scaled::ZERO)); .unwrap_or((false, false, false, false, false, font_size, Scaled::ZERO));
items.push(TextLineItem::Text(TextSpan { items.push(TextLineItem::Text(TextSpan {
text: std::mem::take(text), text: std::mem::take(text),
style: text_style_for( style: text_style_for(
@@ -543,7 +561,9 @@ fn flush_text(
monospace_family, monospace_family,
sans_family, sans_family,
glyph_size, glyph_size,
link,
), ),
link,
y_offset: scaled_to_mm(y_offset), y_offset: scaled_to_mm(y_offset),
})); }));
} }
@@ -558,8 +578,12 @@ fn text_style_for(
monospace_family: Option<FontFamily<fonts::Font>>, monospace_family: Option<FontFamily<fonts::Font>>,
sans_family: Option<FontFamily<fonts::Font>>, sans_family: Option<FontFamily<fonts::Font>>,
font_size: u8, font_size: u8,
link: bool,
) -> Style { ) -> Style {
let mut style = Style::new().with_font_size(font_size); let mut style = Style::new().with_font_size(font_size);
if link {
style = style.with_color(genpdf::style::Color::Rgb(0, 128, 0));
}
if bold && !is_cjk { if bold && !is_cjk {
style = style.bold(); style = style.bold();
} }
+13
View File
@@ -1384,3 +1384,16 @@ fn natbib_citations_use_author_year() {
"bibliography years should carry a/b suffixes: {third}" "bibliography years should carry a/b suffixes: {third}"
); );
} }
#[test]
fn href_text_is_painted_with_the_link_colour() {
let source = r"\documentclass{article}
\begin{document}
See \href{https://example.com}{the example site} for details.
\end{document}";
let value = fresh_preview(source, "href.tex");
assert_eq!(value["status"], "ok", "{value}");
let svg = page_svg(&value, 0);
assert!(svg.contains("fill=\"#008000\""), "{svg}");
assert!(svg.contains(">example</text>"), "{svg}");
}