bare-x-to-pdf 0.2.0 → 0.3.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -90,6 +90,7 @@ pub struct ListLevel {
90
90
  pub suffix: ListSuffix,
91
91
  pub rpr: Option<RunProps>,
92
92
  pub tab_pos: Option<f64>,
93
+ pub size_percent: Option<f64>,
93
94
  }
94
95
 
95
96
  #[derive(Debug, Clone)]
@@ -121,6 +122,9 @@ pub struct Styles {
121
122
  hatches: HashMap<String, (Color, f64, f64)>,
122
123
  fill_images: HashMap<String, String>,
123
124
  opacities: HashMap<String, f64>,
125
+ defaults: HashMap<String, Element>,
126
+ pub page_layout_elements: HashMap<String, Element>,
127
+ pub master_page_elements: HashMap<String, Element>,
124
128
  }
125
129
 
126
130
  impl Styles {
@@ -156,6 +160,9 @@ impl Styles {
156
160
  for el in container.elements() {
157
161
  match el.name.as_str() {
158
162
  "default-style" => {
163
+ if let Some(family) = el.attr("family") {
164
+ out.defaults.insert(family.to_string(), el.clone());
165
+ }
159
166
  if el.attr("family") == Some("paragraph") {
160
167
  let style = parse_style(el, &fonts);
161
168
  out.default_paragraph.ppr.merge(&style.ppr);
@@ -185,6 +192,7 @@ impl Styles {
185
192
  }
186
193
  "page-layout" => {
187
194
  if let Some(name) = el.attr("name") {
195
+ out.page_layout_elements.insert(name.to_string(), el.clone());
188
196
  out.page_layouts.insert(name.to_string(), parse_page_layout(el));
189
197
  }
190
198
  }
@@ -225,6 +233,7 @@ impl Styles {
225
233
  if let Some(masters) = root.child("master-styles") {
226
234
  for master in masters.children("master-page") {
227
235
  let Some(name) = master.attr("name") else { continue };
236
+ out.master_page_elements.insert(name.to_string(), master.clone());
228
237
  out.master_pages.insert(
229
238
  name.to_string(),
230
239
  MasterPage {
@@ -317,6 +326,61 @@ impl Styles {
317
326
  }
318
327
 
319
328
  pub fn graphic(&self, name: &str) -> GraphicProps {
329
+ self.graphic_family("graphic", name)
330
+ }
331
+
332
+ pub fn family_text(&self, family: &str, name: &str, base_size: f64) -> (ParagraphProps, RunProps) {
333
+ let mut ppr = ParagraphProps::default();
334
+ let mut rpr = RunProps::default();
335
+ let mut size = base_size;
336
+ for style in self.chain(family, name) {
337
+ ppr.merge(&style.ppr);
338
+ let mut r = style.rpr.clone();
339
+ if let Some(pct) = style.size_percent {
340
+ r.size = Some(size * pct);
341
+ }
342
+ if let Some(s) = r.size {
343
+ size = s;
344
+ }
345
+ rpr.merge(&r);
346
+ }
347
+ (ppr, rpr)
348
+ }
349
+
350
+ pub fn default_text(&self, family: &str) -> (ParagraphProps, RunProps) {
351
+ match self.defaults.get(family) {
352
+ Some(el) => {
353
+ let style = parse_style(el, &self.fonts);
354
+ (style.ppr, style.rpr)
355
+ }
356
+ None => (ParagraphProps::default(), RunProps::default()),
357
+ }
358
+ }
359
+
360
+ pub fn paragraph_on(&self, base: &(ParagraphProps, RunProps), name: Option<&str>) -> (ParagraphProps, RunProps) {
361
+ let (mut ppr, mut rpr) = base.clone();
362
+ if let Some(name) = name {
363
+ for style in self.chain("paragraph", name) {
364
+ ppr.merge(&style.ppr);
365
+ let mut r = style.rpr.clone();
366
+ if let Some(pct) = style.size_percent {
367
+ r.size = Some(rpr.size.unwrap_or(18.0) * pct);
368
+ }
369
+ rpr.merge(&r);
370
+ }
371
+ }
372
+ (ppr, rpr)
373
+ }
374
+
375
+ pub fn graphic_family(&self, family: &str, name: &str) -> GraphicProps {
376
+ self.graphic_chain(family, name, false)
377
+ }
378
+
379
+ pub fn graphic_with_default(&self, family: &str, name: &str) -> GraphicProps {
380
+ self.graphic_chain(family, name, true)
381
+ }
382
+
383
+ fn graphic_chain(&self, family: &str, name: &str, with_default: bool) -> GraphicProps {
320
384
  let mut props = GraphicProps {
321
385
  wrap: Wrap::TopAndBottom,
322
386
  h_pos: "from-left".into(),
@@ -326,8 +390,15 @@ impl Styles {
326
390
  opacity: 1.0,
327
391
  ..GraphicProps::default()
328
392
  };
329
- for style_name in self.chain_names("graphic", name) {
330
- let Some(el) = self.raw_graphic(&style_name) else { continue };
393
+ let default = if with_default { self.defaults.get("graphic") } else { None };
394
+ let chain: Vec<&Element> = default
395
+ .into_iter()
396
+ .chain(self.chain_names(family, name).iter().filter_map(|n| self.raw.get(&format!("{family}:{n}")).or_else(|| self.raw_graphic(n))))
397
+ .collect();
398
+ if with_default {
399
+ props.stroke = Some((0.5, Color(0, 0, 0)));
400
+ }
401
+ for el in chain {
331
402
  let Some(g) = el.child("graphic-properties") else { continue };
332
403
  if let Some(opacity) = g.attr("opacity").and_then(percent) {
333
404
  props.opacity = opacity;
@@ -388,7 +459,16 @@ impl Styles {
388
459
  let color = g.attr("stroke-color").and_then(Color::parse_hex).unwrap_or(Color(0, 0, 0));
389
460
  props.stroke = Some((width, color));
390
461
  }
391
- None => {}
462
+ None => {
463
+ if let Some((width, color)) = props.stroke.as_mut() {
464
+ if let Some(w) = g.attr("stroke-width").and_then(length) {
465
+ *width = w.max(0.5);
466
+ }
467
+ if let Some(c) = g.attr("stroke-color").and_then(Color::parse_hex) {
468
+ *color = c;
469
+ }
470
+ }
471
+ }
392
472
  }
393
473
  if let Some(border) = g.attr("border").filter(|b| *b != "none") {
394
474
  if let Some((w, c, _)) = parse_border(border) {
@@ -452,6 +532,18 @@ impl Styles {
452
532
  names
453
533
  }
454
534
 
535
+ pub fn elements(&self, family: &str, name: &str) -> Vec<&Element> {
536
+ self.chain_names(family, name).iter().filter_map(|n| self.raw.get(&format!("{family}:{n}"))).collect()
537
+ }
538
+
539
+ pub fn default_style(&self, family: &str) -> Option<&Element> {
540
+ self.defaults.get(family)
541
+ }
542
+
543
+ pub fn run_props(&self, text_properties: &Element) -> RunProps {
544
+ parse_text_properties(text_properties, &self.fonts).0
545
+ }
546
+
455
547
  pub fn section_columns(&self, name: &str) -> Option<ColumnsBlock> {
456
548
  let el = self.raw.get(&format!("section:{name}"))?;
457
549
  let props = el.child("section-properties")?;
@@ -518,9 +610,7 @@ impl Styles {
518
610
 
519
611
  pub fn cell(&self, name: &str) -> CellProps {
520
612
  let mut props = CellProps::default();
521
- let Some(p) = self.raw.get(&format!("table-cell:{name}")).and_then(|e| e.child("table-cell-properties")) else {
522
- return props;
523
- };
613
+ let Some(el) = self.raw.get(&format!("table-cell:{name}")) else { return props };
524
614
  let side = |value: Option<&str>| -> BorderSide {
525
615
  match value {
526
616
  None => BorderSide::Unset,
@@ -528,28 +618,57 @@ impl Styles {
528
618
  Some(v) => parse_border(v).map(|(w, c, s)| BorderSide::Line { width: w, color: c, style: s }).unwrap_or(BorderSide::None),
529
619
  }
530
620
  };
531
- let all = side(p.attr("border"));
532
- props.borders = Borders { top: all, left: all, bottom: all, right: all, ..Borders::default() };
533
- for (name, slot) in [("border-top", &mut props.borders.top), ("border-left", &mut props.borders.left), ("border-bottom", &mut props.borders.bottom), ("border-right", &mut props.borders.right)] {
534
- let s = side(p.attr(name));
535
- if s != BorderSide::Unset {
536
- *slot = s;
537
- }
538
- }
539
- let pad = |n: &str| p.attr(n).and_then(length);
540
- let all_pad = pad("padding");
541
- props.margins = CellMargins {
542
- top: pad("padding-top").or(all_pad),
543
- left: pad("padding-left").or(all_pad),
544
- bottom: pad("padding-bottom").or(all_pad),
545
- right: pad("padding-right").or(all_pad),
621
+ let apply_borders = |p: &Element, borders: &mut Borders| {
622
+ let all = side(p.attr("border"));
623
+ if all != BorderSide::Unset {
624
+ *borders = Borders { top: all, left: all, bottom: all, right: all, ..Borders::default() };
625
+ }
626
+ for (name, slot) in [("border-top", &mut borders.top), ("border-left", &mut borders.left), ("border-bottom", &mut borders.bottom), ("border-right", &mut borders.right)] {
627
+ let s = side(p.attr(name));
628
+ if s != BorderSide::Unset {
629
+ *slot = s;
630
+ }
631
+ }
546
632
  };
547
- props.fill = p.attr("background-color").filter(|c| *c != "transparent").and_then(Color::parse_hex);
548
- props.valign = match p.attr("vertical-align") {
549
- Some("middle") => VAlign::Center,
550
- Some("bottom") => VAlign::Bottom,
551
- _ => VAlign::Top,
633
+ let padding = |p: &Element, margins: &mut CellMargins| {
634
+ let pad = |n: &str| p.attr(n).and_then(length);
635
+ let all = pad("padding");
636
+ margins.top = pad("padding-top").or(all).or(margins.top);
637
+ margins.left = pad("padding-left").or(all).or(margins.left);
638
+ margins.bottom = pad("padding-bottom").or(all).or(margins.bottom);
639
+ margins.right = pad("padding-right").or(all).or(margins.right);
552
640
  };
641
+ props.valign = VAlign::Top;
642
+ if let Some(p) = el.child("table-cell-properties") {
643
+ apply_borders(p, &mut props.borders);
644
+ padding(p, &mut props.margins);
645
+ props.fill = p.attr("background-color").filter(|c| *c != "transparent").and_then(Color::parse_hex);
646
+ props.valign = match p.attr("vertical-align") {
647
+ Some("middle") => VAlign::Center,
648
+ Some("bottom") => VAlign::Bottom,
649
+ _ => VAlign::Top,
650
+ };
651
+ }
652
+ if let Some(g) = el.child("graphic-properties") {
653
+ padding(g, &mut props.margins);
654
+ if g.attr("fill") != Some("none") {
655
+ if let Some(c) = g.attr("fill-color").and_then(Color::parse_hex) {
656
+ props.fill = Some(c);
657
+ }
658
+ }
659
+ if let Some(v) = g.attr("textarea-vertical-align") {
660
+ props.valign = match v {
661
+ "middle" => VAlign::Center,
662
+ "bottom" => VAlign::Bottom,
663
+ _ => VAlign::Top,
664
+ };
665
+ }
666
+ }
667
+ if props.borders == Borders::default() {
668
+ if let Some(p) = el.child("paragraph-properties") {
669
+ apply_borders(p, &mut props.borders);
670
+ }
671
+ }
553
672
  props
554
673
  }
555
674
  }
@@ -791,8 +910,10 @@ fn parse_list(el: &Element, fonts: &HashMap<String, String>) -> Vec<Option<ListL
791
910
  hanging = Some(min_label);
792
911
  }
793
912
  }
794
- let rpr = lvl.child("text-properties").map(|t| parse_text_properties(t, fonts).0);
795
- levels[level - 1] = Some(ListLevel { kind, left, hanging, suffix, rpr, tab_pos });
913
+ let text = lvl.child("text-properties").map(|t| parse_text_properties(t, fonts));
914
+ let size_percent = text.as_ref().and_then(|t| t.1);
915
+ let rpr = text.map(|t| t.0);
916
+ levels[level - 1] = Some(ListLevel { kind, left, hanging, suffix, rpr, tab_pos, size_percent });
796
917
  }
797
918
  levels
798
919
  }
@@ -196,7 +196,7 @@ pub(crate) fn parse_chart(root: &Element) -> Option<Chart> {
196
196
  categories = cache_points(cat).into_iter().map(|p| p.unwrap_or_default()).collect();
197
197
  }
198
198
  }
199
- series.push(ChartSeries { name, values });
199
+ series.push(ChartSeries { name, values, color: None, point_colors: Vec::new(), no_line: false });
200
200
  }
201
201
  if series.is_empty() {
202
202
  return None;
@@ -216,7 +216,7 @@ pub(crate) fn parse_chart(root: &Element) -> Option<Chart> {
216
216
  let gap_width = group.child("gapWidth").and_then(|g| g.attr("val")).and_then(|v| v.parse::<f64>().ok()).unwrap_or(150.0);
217
217
  let markers = group.child("marker").and_then(|m| m.attr("val")).map(|v| v != "0").unwrap_or(true)
218
218
  && !group.children("ser").any(|s| s.child("marker").and_then(|m| m.child("symbol")).and_then(|s| s.attr("val")) == Some("none"));
219
- Some(Chart { title: chart_title(root), kind, categories, series, legend, gap_width, markers })
219
+ Some(Chart { title: chart_title(root), kind, categories, series, legend, gap_width, markers, style: ChartStyle::default() })
220
220
  }
221
221
 
222
222
  pub(crate) fn chart_title(root: &Element) -> Option<String> {
@@ -7,6 +7,7 @@ use std::fmt::Write;
7
7
  const DEFAULT_FONT: &str = "Calibri";
8
8
  const DEFAULT_SIZE: f64 = 11.0;
9
9
  const DEFAULT_CELL_MARGIN_X: f64 = 5.4;
10
+ const TEXT_SHIFT: f64 = 0.1;
10
11
 
11
12
  pub struct Emitted {
12
13
  pub source: String,
@@ -21,6 +22,7 @@ pub fn emit(doc: &Document, fonts: &FontSet) -> Emitted {
21
22
  files: RefCell::new(Vec::new()),
22
23
  page: RefCell::new(PageSetup::default()),
23
24
  para_line: Cell::new(None),
25
+ table_depth: Cell::new(0),
24
26
  };
25
27
  emitter.preamble();
26
28
  for (index, section) in doc.sections.iter().enumerate() {
@@ -39,6 +41,7 @@ struct Emitter<'a> {
39
41
  files: RefCell<Vec<(String, Vec<u8>)>>,
40
42
  page: RefCell<PageSetup>,
41
43
  para_line: Cell<Option<f64>>,
44
+ table_depth: Cell<u32>,
42
45
  }
43
46
 
44
47
  struct CellOut {
@@ -94,8 +97,8 @@ impl Emitter<'_> {
94
97
  pt(page.height),
95
98
  pt(page.margin.top),
96
99
  pt(page.margin.bottom),
97
- pt(page.margin.left),
98
- pt(page.margin.right)
100
+ pt(page.margin.left + self.text_shift()),
101
+ pt(page.margin.right - self.text_shift())
99
102
  );
100
103
  if section.columns > 1 {
101
104
  let _ = writeln!(self.out, "#set columns(gutter: {})", pt(section.column_gap));
@@ -635,6 +638,7 @@ impl Emitter<'_> {
635
638
  }
636
639
 
637
640
  fn text_expr_line(&self, text: &str, props: &RunProps, spacing: LineSpacing, empty_line: bool) -> String {
641
+ let text = &if self.table_depth.get() > 0 && !self.doc.cell_metrics { hyphen_break_opportunities(text) } else { std::borrow::Cow::Borrowed(text) };
638
642
  if props.caps == Some(true) {
639
643
  return self.text_expr_content_line(&typst_str(&text.to_uppercase()), props, spacing, empty_line);
640
644
  }
@@ -804,9 +808,21 @@ impl Emitter<'_> {
804
808
 
805
809
  fn chart_expr(&self, chart: &Chart, w: f64, h: f64) -> String {
806
810
  const COLORS: [&str; 6] = ["#4472c4", "#ed7d31", "#a5a5a5", "#ffc000", "#5b9bd5", "#70ad47"];
811
+ let hex = |c: &Color| format!("\"#{}\"", c.hex().trim_start_matches('#'));
812
+ let series_color = |i: usize| chart.series.get(i).and_then(|s| s.color.as_ref()).map(hex).unwrap_or_else(|| typst_str(COLORS[i % COLORS.len()]));
813
+ let point_color = |i: usize| {
814
+ chart
815
+ .series
816
+ .first()
817
+ .and_then(|s| s.point_colors.get(i).copied().flatten())
818
+ .map(|c| hex(&c))
819
+ .unwrap_or_else(|| typst_str(COLORS[i % COLORS.len()]))
820
+ };
821
+ let grid = chart.style.grid.as_ref().map(hex).unwrap_or_else(|| "\"#b3b3b3\"".into());
822
+ let font = typst_str(&chart.style.font.as_deref().map_or_else(|| "Carlito".to_string(), |f| self.fonts.resolve(f, None)));
807
823
  let label = |text: &str, size: f64, bold: bool| {
808
824
  format!(
809
- "text(font: \"Carlito\", size: {}, weight: {}, {})",
825
+ "text(font: {font}, size: {}, weight: {}, {})",
810
826
  pt(size),
811
827
  if bold { "\"bold\"" } else { "\"regular\"" },
812
828
  typst_str(text)
@@ -855,7 +871,7 @@ impl Emitter<'_> {
855
871
  let a = (angle + sweep * k as f64 / steps as f64).to_radians();
856
872
  points.push(format!("({}, {})", pt(cx + radius * a.cos()), pt(cy + radius * a.sin())));
857
873
  }
858
- items.push(format!("place(top + left, polygon(fill: rgb({}), stroke: 0.5pt + white, {}))", typst_str(COLORS[i % COLORS.len()]), points.join(", ")));
874
+ items.push(format!("place(top + left, polygon(fill: rgb({}), stroke: 0.5pt + white, {}))", point_color(i), points.join(", ")));
859
875
  angle += sweep;
860
876
  }
861
877
  } else {
@@ -876,16 +892,25 @@ impl Emitter<'_> {
876
892
  let t = ((v - axis_min) / span).clamp(0.0, 1.0);
877
893
  if horizontal { (plot_left + t * plot_w, 0.0) } else { (0.0, plot_bottom - t * plot_h) }
878
894
  };
895
+ if chart.style.plot_fill.is_some() || chart.style.plot_border.is_some() {
896
+ let fill = chart.style.plot_fill.as_ref().map(|c| format!("fill: rgb({}), ", hex(c))).unwrap_or_default();
897
+ let stroke = chart.style.plot_border.as_ref().map(|c| format!("stroke: 0.5pt + rgb({})", hex(c))).unwrap_or_else(|| "stroke: none".into());
898
+ items.push(format!("place(top + left, dx: {}, dy: {}, rect(width: {}, height: {}, {fill}{stroke}))", pt(plot_left), pt(plot_top), pt(plot_w), pt(plot_h)));
899
+ }
879
900
  let mut tick = axis_min;
880
901
  while tick <= axis_max + step * 0.01 {
881
902
  let text = crate::xlsx::format::general(tick);
882
903
  if horizontal {
883
904
  let x = value_pos(tick).0;
884
- items.push(format!("place(top + left, dx: {}, dy: {}, line(angle: 90deg, length: {}, stroke: 0.4pt + rgb(\"#b3b3b3\")))", pt(x), pt(plot_top), pt(plot_h)));
905
+ if !chart.style.no_grid {
906
+ items.push(format!("place(top + left, dx: {}, dy: {}, line(angle: 90deg, length: {}, stroke: 0.4pt + rgb({grid})))", pt(x), pt(plot_top), pt(plot_h)));
907
+ }
885
908
  items.push(format!("place(top + left, dx: {}, dy: {}, box(width: 30pt, align(center, {})))", pt(x - 15.0), pt(plot_bottom + 4.0), label(&text, 10.0, false)));
886
909
  } else {
887
910
  let y = value_pos(tick).1;
888
- items.push(format!("place(top + left, dx: {}, dy: {}, line(length: {}, stroke: 0.4pt + rgb(\"#b3b3b3\")))", pt(plot_left), pt(y), pt(plot_w)));
911
+ if !chart.style.no_grid {
912
+ items.push(format!("place(top + left, dx: {}, dy: {}, line(length: {}, stroke: 0.4pt + rgb({grid})))", pt(plot_left), pt(y), pt(plot_w)));
913
+ }
889
914
  items.push(format!("place(top + left, dx: 0pt, dy: {}, box(width: {}, align(right, {})))", pt(y - 6.0), pt(plot_left - 5.0), label(&text, 10.0, false)));
890
915
  }
891
916
  tick += step;
@@ -910,7 +935,7 @@ impl Emitter<'_> {
910
935
  let bar = (slot / (series_count as f64 + chart.gap_width.max(0.0) / 100.0)).max(0.5);
911
936
  let gap = slot - bar * series_count as f64;
912
937
  for (si, s) in chart.series.iter().enumerate() {
913
- let color = typst_str(COLORS[si % COLORS.len()]);
938
+ let color = series_color(si);
914
939
  for (ci, v) in s.values.iter().enumerate() {
915
940
  let Some(v) = v else { continue };
916
941
  let start = ci as f64 * slot + gap / 2.0 + si as f64 * bar;
@@ -927,7 +952,7 @@ impl Emitter<'_> {
927
952
  }
928
953
  ChartKind::Line | ChartKind::Area => {
929
954
  for (si, s) in chart.series.iter().enumerate() {
930
- let color = typst_str(COLORS[si % COLORS.len()]);
955
+ let color = series_color(si);
931
956
  let points: Vec<(f64, f64)> = s
932
957
  .values
933
958
  .iter()
@@ -940,7 +965,7 @@ impl Emitter<'_> {
940
965
  poly.push(format!("({}, {})", pt(points[0].0), pt(zero.1)));
941
966
  items.push(format!("place(top + left, polygon(fill: rgb({color}).transparentize(30%), {}))", poly.join(", ")));
942
967
  }
943
- for pair in points.windows(2) {
968
+ for pair in points.windows(2).filter(|_| !s.no_line) {
944
969
  items.push(format!(
945
970
  "place(top + left, line(start: ({}, {}), end: ({}, {}), stroke: 1.5pt + rgb({color})))",
946
971
  pt(pair[0].0), pt(pair[0].1), pt(pair[1].0), pt(pair[1].1)
@@ -961,7 +986,7 @@ impl Emitter<'_> {
961
986
  let x = if legend == Some(LegendPos::Left) { 6.0 } else { plot_right + 6.0 };
962
987
  let mut y = plot_top + (plot_h - legend_names.len() as f64 * 12.0).max(0.0) / 2.0;
963
988
  for (i, name) in legend_names.iter().enumerate() {
964
- items.push(format!("place(top + left, dx: {}, dy: {}, rect(width: 6pt, height: 6pt, fill: rgb({})))", pt(x), pt(y + 3.0), typst_str(COLORS[i % COLORS.len()])));
989
+ items.push(format!("place(top + left, dx: {}, dy: {}, rect(width: 6pt, height: 6pt, fill: rgb({})))", pt(x), pt(y + 3.0), if chart.kind == ChartKind::Pie { point_color(i) } else { series_color(i) }));
965
990
  items.push(format!("place(top + left, dx: {}, dy: {}, box(width: {}, clip: true, {}))", pt(x + 9.0), pt(y), pt(legend_side_width - 8.0), label(name, 9.0, false)));
966
991
  y += 12.0;
967
992
  }
@@ -972,14 +997,15 @@ impl Emitter<'_> {
972
997
  let mut x = (w - total) / 2.0;
973
998
  let y = if legend == Some(LegendPos::Top) { title_height } else { h - legend_band_height - 4.0 };
974
999
  for (i, name) in legend_names.iter().enumerate() {
975
- items.push(format!("place(top + left, dx: {}, dy: {}, rect(width: 6pt, height: 6pt, fill: rgb({})))", pt(x), pt(y + 3.0), typst_str(COLORS[i % COLORS.len()])));
1000
+ items.push(format!("place(top + left, dx: {}, dy: {}, rect(width: 6pt, height: 6pt, fill: rgb({})))", pt(x), pt(y + 3.0), if chart.kind == ChartKind::Pie { point_color(i) } else { series_color(i) }));
976
1001
  items.push(format!("place(top + left, dx: {}, dy: {}, {})", pt(x + 9.0), pt(y), label(name, 9.0, false)));
977
1002
  x += widths[i];
978
1003
  }
979
1004
  }
980
1005
  None => {}
981
1006
  }
982
- format!("block(width: {}, height: {}, fill: white, stroke: 0.5pt + rgb(\"#bfbfbf\"), clip: true, {{ {} }})", pt(w), pt(h), items.join("; "))
1007
+ let border = chart.style.border.as_ref().map(hex).unwrap_or_else(|| "\"#bfbfbf\"".into());
1008
+ format!("block(width: {}, height: {}, fill: white, stroke: 0.5pt + rgb({border}), clip: true, {{ {} }})", pt(w), pt(h), items.join("; "))
983
1009
  }
984
1010
 
985
1011
  fn register(&self, image: &ImageData) -> String {
@@ -1121,7 +1147,7 @@ impl Emitter<'_> {
1121
1147
  })
1122
1148
  .collect();
1123
1149
  format!(
1124
- "box(width: {w}, height: {h}, place(top + left, curve(fill: {fill}, stroke: {stroke}, {})) + place(top + left, block(width: {w}, height: {height}, {inset}, {body})))",
1150
+ "box(width: {w}, height: {h}, place(top + left, curve(fill: {fill}, fill-rule: \"even-odd\", stroke: {stroke}, {})) + place(top + left, block(width: {w}, height: {height}, {inset}, {body})))",
1125
1151
  parts.join(", ")
1126
1152
  )
1127
1153
  }
@@ -1161,6 +1187,7 @@ impl Emitter<'_> {
1161
1187
  HPosition::Align(_, HAlign::Center) => ("center", 0.0),
1162
1188
  HPosition::Align(_, HAlign::Right) => ("right", 0.0),
1163
1189
  };
1190
+ let dx = dx - self.text_shift();
1164
1191
  match anchor.vertical {
1165
1192
  VPosition::Offset(VRef::Page, y) => {
1166
1193
  let _ = writeln!(out, "#place(top + {h_align}, dx: {}, dy: {}, {expr})", pt(dx), pt(y - margin.top));
@@ -1205,6 +1232,13 @@ impl Emitter<'_> {
1205
1232
  }
1206
1233
 
1207
1234
  fn table_expr(&self, table: &Table) -> String {
1235
+ self.table_depth.set(self.table_depth.get() + 1);
1236
+ let expr = self.table_expr_inner(table);
1237
+ self.table_depth.set(self.table_depth.get() - 1);
1238
+ expr
1239
+ }
1240
+
1241
+ fn table_expr_inner(&self, table: &Table) -> String {
1208
1242
  if table.rows.is_empty() {
1209
1243
  return "box()".to_string();
1210
1244
  }
@@ -1395,11 +1429,35 @@ impl Emitter<'_> {
1395
1429
  rows_arg,
1396
1430
  rendered.join(",\n")
1397
1431
  );
1398
- if table.indent.abs() > 0.01 {
1399
- expr = format!("pad(left: {}, {})", pt(table.indent), expr);
1432
+ let indent = table.indent + self.table_border_offset(table);
1433
+ if indent.abs() > 0.01 {
1434
+ expr = format!("pad(left: {}, {})", pt(indent), expr);
1400
1435
  }
1401
1436
  expr
1402
1437
  }
1438
+
1439
+ fn text_shift(&self) -> f64 {
1440
+ if self.doc.writer_text_offset {
1441
+ TEXT_SHIFT
1442
+ } else {
1443
+ 0.0
1444
+ }
1445
+ }
1446
+
1447
+ fn table_border_offset(&self, table: &Table) -> f64 {
1448
+ if !self.doc.table_at_border_center {
1449
+ return 0.0;
1450
+ }
1451
+ let first = table.rows.first().and_then(|r| r.cells.first());
1452
+ let side = match first.map(|c| c.borders.left) {
1453
+ Some(own) if own != BorderSide::Unset => own,
1454
+ _ => table.borders.left,
1455
+ };
1456
+ match side {
1457
+ BorderSide::Line { width, .. } => ((width * 20.0).round() / 2.0).floor() / 20.0,
1458
+ _ => 0.0,
1459
+ }
1460
+ }
1403
1461
  }
1404
1462
 
1405
1463
  fn png_size(data: &[u8]) -> Option<(u32, u32)> {
@@ -1517,6 +1575,24 @@ pub fn pt(value: f64) -> String {
1517
1575
  format!("{rounded}pt")
1518
1576
  }
1519
1577
 
1578
+ fn hyphen_break_opportunities(text: &str) -> std::borrow::Cow<'_, str> {
1579
+ let chars: Vec<char> = text.chars().collect();
1580
+ let breaks_after = |i: usize| {
1581
+ chars[i] == '-' && i > 0 && chars[i - 1].is_alphabetic() && chars.get(i + 1).is_some_and(|c| c.is_ascii_digit())
1582
+ };
1583
+ if !(0..chars.len()).any(breaks_after) {
1584
+ return std::borrow::Cow::Borrowed(text);
1585
+ }
1586
+ let mut out = String::with_capacity(text.len() + 3);
1587
+ for (i, ch) in chars.iter().enumerate() {
1588
+ out.push(*ch);
1589
+ if breaks_after(i) {
1590
+ out.push('\u{200B}');
1591
+ }
1592
+ }
1593
+ std::borrow::Cow::Owned(out)
1594
+ }
1595
+
1520
1596
  pub fn typst_str(text: &str) -> String {
1521
1597
  let mut out = String::with_capacity(text.len() + 2);
1522
1598
  out.push('"');
@@ -1,5 +1,6 @@
1
1
  pub mod emit;
2
2
  pub mod fonts;
3
+ mod notes;
3
4
  pub mod world;
4
5
 
5
6
  use crate::error::Error;
@@ -31,9 +32,16 @@ pub fn render_pdf(doc: &Document, fonts_dir: &Path) -> Result<Vec<u8>, Error> {
31
32
  .output
32
33
  .map_err(|errors| Error::new(format!("layout failed: {}", diagnostics(&errors))))?;
33
34
 
34
- let pdf = typst_pdf::pdf(&paged, &PdfOptions::default())
35
+ let mut pdf = typst_pdf::pdf(&paged, &PdfOptions::default())
35
36
  .map_err(|errors| Error::new(format!("pdf export failed: {}", diagnostics(&errors))))?;
36
37
 
38
+ let has_notes = doc.sections.iter().any(|s| !s.notes.is_empty());
39
+ if has_notes && paged.pages().len() == doc.sections.len() {
40
+ let pages: Vec<(f64, &[crate::model::PageNote])> =
41
+ doc.sections.iter().map(|s| (s.page.height, s.notes.as_slice())).collect();
42
+ pdf = notes::append_notes(pdf, &pages)?;
43
+ }
44
+
37
45
  typst::comemo::evict(0);
38
46
  Ok(pdf)
39
47
  }