Tidy up library

This commit is contained in:
Laurenz 2022-11-03 16:50:26 +01:00
parent 46921a8c28
commit 33928a00dc
44 changed files with 119 additions and 125 deletions

View File

@ -17,13 +17,12 @@ use pico_args::Arguments;
use same_file::{is_same_file, Handle}; use same_file::{is_same_file, Handle};
use siphasher::sip128::{Hasher128, SipHasher}; use siphasher::sip128::{Hasher128, SipHasher};
use termcolor::{ColorChoice, StandardStream, WriteColor}; use termcolor::{ColorChoice, StandardStream, WriteColor};
use walkdir::WalkDir;
use typst::diag::{FileError, FileResult, SourceError, StrResult}; use typst::diag::{FileError, FileResult, SourceError, StrResult};
use typst::font::{Font, FontBook, FontInfo, FontVariant}; use typst::font::{Font, FontBook, FontInfo, FontVariant};
use typst::syntax::{Source, SourceId}; use typst::syntax::{Source, SourceId};
use typst::util::{Buffer, PathExt}; use typst::util::{Buffer, PathExt};
use typst::{Config, World}; use typst::{Config, World};
use walkdir::WalkDir;
type CodespanResult<T> = Result<T, CodespanError>; type CodespanResult<T> = Result<T, CodespanError>;
type CodespanError = codespan_reporting::files::Error; type CodespanError = codespan_reporting::files::Error;

View File

@ -1,6 +1,6 @@
use std::fmt::Write; use std::fmt::Write;
use typst::diag::format_xml_like_error; use typst::diag::{format_xml_like_error, FileError};
use crate::prelude::*; use crate::prelude::*;

View File

@ -1,13 +1,13 @@
//! Computational utility functions. //! Foundational functions.
mod calc;
mod color; mod color;
mod data; mod data;
mod math;
mod string; mod string;
pub use calc::*;
pub use color::*; pub use color::*;
pub use data::*; pub use data::*;
pub use math::*;
pub use string::*; pub use string::*;
use comemo::Track; use comemo::Track;

View File

@ -115,7 +115,7 @@ impl StyleMapExt for StyleMap {
fn set_family(&mut self, preferred: text::FontFamily, existing: StyleChain) { fn set_family(&mut self, preferred: text::FontFamily, existing: StyleChain) {
self.set( self.set(
text::TextNode::FAMILY, text::TextNode::FAMILY,
FallbackList( text::FallbackList(
std::iter::once(preferred) std::iter::once(preferred)
.chain(existing.get(text::TextNode::FAMILY).0.iter().cloned()) .chain(existing.get(text::TextNode::FAMILY).0.iter().cloned())
.collect(), .collect(),

View File

@ -80,7 +80,7 @@ impl PartialOrd for FlowChild {
} }
/// Performs flow layout. /// Performs flow layout.
pub struct FlowLayouter { struct FlowLayouter {
/// The regions to layout children into. /// The regions to layout children into.
regions: Regions, regions: Regions,
/// Whether the flow should expand to fill the region. /// Whether the flow should expand to fill the region.
@ -112,7 +112,7 @@ enum FlowItem {
impl FlowLayouter { impl FlowLayouter {
/// Create a new flow layouter. /// Create a new flow layouter.
pub fn new(regions: &Regions) -> Self { fn new(regions: &Regions) -> Self {
let expand = regions.expand; let expand = regions.expand;
let full = regions.first; let full = regions.first;
@ -132,7 +132,7 @@ impl FlowLayouter {
} }
/// Layout spacing. /// Layout spacing.
pub fn layout_spacing(&mut self, spacing: Spacing, styles: StyleChain) { fn layout_spacing(&mut self, spacing: Spacing, styles: StyleChain) {
match spacing { match spacing {
Spacing::Relative(v) => { Spacing::Relative(v) => {
// Resolve the spacing and limit it to the remaining space. // Resolve the spacing and limit it to the remaining space.
@ -150,7 +150,7 @@ impl FlowLayouter {
} }
/// Layout a block. /// Layout a block.
pub fn layout_block( fn layout_block(
&mut self, &mut self,
world: Tracked<dyn World>, world: Tracked<dyn World>,
block: &Content, block: &Content,
@ -206,7 +206,7 @@ impl FlowLayouter {
} }
/// Finish the frame for one region. /// Finish the frame for one region.
pub fn finish_region(&mut self) { fn finish_region(&mut self) {
// Determine the size of the flow in this region dependening on whether // Determine the size of the flow in this region dependening on whether
// the region expands. // the region expands.
let mut size = self.expand.select(self.full, self.used); let mut size = self.expand.select(self.full, self.used);
@ -254,7 +254,7 @@ impl FlowLayouter {
} }
/// Finish layouting and return the resulting frames. /// Finish layouting and return the resulting frames.
pub fn finish(mut self) -> Vec<Frame> { fn finish(mut self) -> Vec<Frame> {
if self.expand.y { if self.expand.y {
while !self.regions.backlog.is_empty() { while !self.regions.backlog.is_empty() {
self.finish_region(); self.finish_region();

View File

@ -99,7 +99,7 @@ castable! {
} }
/// Performs grid layout. /// Performs grid layout.
pub struct GridLayouter<'a> { struct GridLayouter<'a> {
/// The core context. /// The core context.
world: Tracked<'a, dyn World>, world: Tracked<'a, dyn World>,
/// The grid cells. /// The grid cells.
@ -140,7 +140,7 @@ impl<'a> GridLayouter<'a> {
/// Create a new grid layouter. /// Create a new grid layouter.
/// ///
/// This prepares grid layout by unifying content and gutter tracks. /// This prepares grid layout by unifying content and gutter tracks.
pub fn new( fn new(
world: Tracked<'a, dyn World>, world: Tracked<'a, dyn World>,
tracks: Axes<&[TrackSizing]>, tracks: Axes<&[TrackSizing]>,
gutter: Axes<&[TrackSizing]>, gutter: Axes<&[TrackSizing]>,
@ -211,7 +211,7 @@ impl<'a> GridLayouter<'a> {
} }
/// Determines the columns sizes and then layouts the grid row-by-row. /// Determines the columns sizes and then layouts the grid row-by-row.
pub fn layout(mut self) -> SourceResult<Vec<Frame>> { fn layout(mut self) -> SourceResult<Vec<Frame>> {
self.measure_columns()?; self.measure_columns()?;
for y in 0 .. self.rows.len() { for y in 0 .. self.rows.len() {

View File

@ -44,16 +44,16 @@ use crate::text::{
LinebreakNode, ParChild, ParNode, ParbreakNode, SmartQuoteNode, SpaceNode, TextNode, LinebreakNode, ParChild, ParNode, ParbreakNode, SmartQuoteNode, SpaceNode, TextNode,
}; };
/// The root-level layout. /// Root-level layout.
#[capability] #[capability]
pub trait Layout: 'static + Sync + Send { pub trait LayoutRoot: 'static + Sync + Send {
/// Layout into one frame per page. /// Layout into one frame per page.
fn layout(&self, world: Tracked<dyn World>) -> SourceResult<Vec<Frame>>; fn layout_root(&self, world: Tracked<dyn World>) -> SourceResult<Vec<Frame>>;
} }
impl Layout for Content { impl LayoutRoot for Content {
#[comemo::memoize] #[comemo::memoize]
fn layout(&self, world: Tracked<dyn World>) -> SourceResult<Vec<Frame>> { fn layout_root(&self, world: Tracked<dyn World>) -> SourceResult<Vec<Frame>> {
let styles = StyleChain::with_root(&world.config().styles); let styles = StyleChain::with_root(&world.config().styles);
let scratch = Scratch::default(); let scratch = Scratch::default();
@ -259,7 +259,7 @@ struct Scratch<'a> {
/// Determines whether a style could interrupt some composable structure. /// Determines whether a style could interrupt some composable structure.
#[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Ord, PartialOrd)]
pub enum Interruption { enum Interruption {
/// The style forces a list break. /// The style forces a list break.
List, List,
/// The style forces a paragraph break. /// The style forces a paragraph break.
@ -269,11 +269,7 @@ pub enum Interruption {
} }
impl<'a> Builder<'a> { impl<'a> Builder<'a> {
pub fn new( fn new(world: Tracked<'a, dyn World>, scratch: &'a Scratch<'a>, top: bool) -> Self {
world: Tracked<'a, dyn World>,
scratch: &'a Scratch<'a>,
top: bool,
) -> Self {
Self { Self {
world, world,
scratch, scratch,
@ -284,7 +280,7 @@ impl<'a> Builder<'a> {
} }
} }
pub fn into_doc( fn into_doc(
mut self, mut self,
styles: StyleChain<'a>, styles: StyleChain<'a>,
) -> SourceResult<(DocNode, StyleChain<'a>)> { ) -> SourceResult<(DocNode, StyleChain<'a>)> {
@ -293,7 +289,7 @@ impl<'a> Builder<'a> {
Ok((DocNode(pages), shared)) Ok((DocNode(pages), shared))
} }
pub fn into_flow( fn into_flow(
mut self, mut self,
styles: StyleChain<'a>, styles: StyleChain<'a>,
) -> SourceResult<(FlowNode, StyleChain<'a>)> { ) -> SourceResult<(FlowNode, StyleChain<'a>)> {
@ -302,7 +298,7 @@ impl<'a> Builder<'a> {
Ok((FlowNode(children), shared)) Ok((FlowNode(children), shared))
} }
pub fn accept( fn accept(
&mut self, &mut self,
content: &'a Content, content: &'a Content,
styles: StyleChain<'a>, styles: StyleChain<'a>,
@ -740,7 +736,7 @@ enum Last {
impl<'a, T> CollapsingBuilder<'a, T> { impl<'a, T> CollapsingBuilder<'a, T> {
/// Create a new style-vec builder. /// Create a new style-vec builder.
pub fn new() -> Self { fn new() -> Self {
Self { Self {
builder: StyleVecBuilder::new(), builder: StyleVecBuilder::new(),
staged: vec![], staged: vec![],
@ -749,7 +745,7 @@ impl<'a, T> CollapsingBuilder<'a, T> {
} }
/// Whether the builder is empty. /// Whether the builder is empty.
pub fn is_empty(&self) -> bool { fn is_empty(&self) -> bool {
self.builder.is_empty() && self.staged.is_empty() self.builder.is_empty() && self.staged.is_empty()
} }
@ -760,7 +756,7 @@ impl<'a, T> CollapsingBuilder<'a, T> {
/// Between weak items, there may be at least one per layer and among the /// Between weak items, there may be at least one per layer and among the
/// candidates the strongest one (smallest `weakness`) wins. When tied, /// candidates the strongest one (smallest `weakness`) wins. When tied,
/// the one that compares larger through `PartialOrd` wins. /// the one that compares larger through `PartialOrd` wins.
pub fn weak(&mut self, item: T, styles: StyleChain<'a>, weakness: u8) fn weak(&mut self, item: T, styles: StyleChain<'a>, weakness: u8)
where where
T: PartialOrd, T: PartialOrd,
{ {
@ -788,31 +784,31 @@ impl<'a, T> CollapsingBuilder<'a, T> {
} }
/// Forces nearby weak items to collapse. /// Forces nearby weak items to collapse.
pub fn destructive(&mut self, item: T, styles: StyleChain<'a>) { fn destructive(&mut self, item: T, styles: StyleChain<'a>) {
self.flush(false); self.flush(false);
self.builder.push(item, styles); self.builder.push(item, styles);
self.last = Last::Destructive; self.last = Last::Destructive;
} }
/// Allows nearby weak items to exist. /// Allows nearby weak items to exist.
pub fn supportive(&mut self, item: T, styles: StyleChain<'a>) { fn supportive(&mut self, item: T, styles: StyleChain<'a>) {
self.flush(true); self.flush(true);
self.builder.push(item, styles); self.builder.push(item, styles);
self.last = Last::Supportive; self.last = Last::Supportive;
} }
/// Has no influence on other items. /// Has no influence on other items.
pub fn ignorant(&mut self, item: T, styles: StyleChain<'a>) { fn ignorant(&mut self, item: T, styles: StyleChain<'a>) {
self.staged.push((item, styles, None)); self.staged.push((item, styles, None));
} }
/// Iterate over the contained items. /// Iterate over the contained items.
pub fn items(&self) -> impl DoubleEndedIterator<Item = &T> { fn items(&self) -> impl DoubleEndedIterator<Item = &T> {
self.builder.items().chain(self.staged.iter().map(|(item, ..)| item)) self.builder.items().chain(self.staged.iter().map(|(item, ..)| item))
} }
/// Return the finish style vec and the common prefix chain. /// Return the finish style vec and the common prefix chain.
pub fn finish(mut self) -> (StyleVec<T>, StyleChain<'a>) { fn finish(mut self) -> (StyleVec<T>, StyleChain<'a>) {
self.flush(false); self.flush(false);
self.builder.finish() self.builder.finish()
} }

View File

@ -2,6 +2,7 @@ use std::str::FromStr;
use super::ColumnsNode; use super::ColumnsNode;
use crate::prelude::*; use crate::prelude::*;
use crate::text::TextNode;
/// Layouts its child onto one or multiple pages. /// Layouts its child onto one or multiple pages.
#[derive(PartialEq, Clone, Hash)] #[derive(PartialEq, Clone, Hash)]

View File

@ -89,7 +89,7 @@ castable! {
} }
/// Performs stack layout. /// Performs stack layout.
pub struct StackLayouter<'a> { struct StackLayouter<'a> {
/// The stacking direction. /// The stacking direction.
dir: Dir, dir: Dir,
/// The axis of the stacking direction. /// The axis of the stacking direction.
@ -125,7 +125,7 @@ enum StackItem {
impl<'a> StackLayouter<'a> { impl<'a> StackLayouter<'a> {
/// Create a new stack layouter. /// Create a new stack layouter.
pub fn new(dir: Dir, regions: &Regions, styles: StyleChain<'a>) -> Self { fn new(dir: Dir, regions: &Regions, styles: StyleChain<'a>) -> Self {
let axis = dir.axis(); let axis = dir.axis();
let expand = regions.expand; let expand = regions.expand;
let full = regions.first; let full = regions.first;
@ -149,7 +149,7 @@ impl<'a> StackLayouter<'a> {
} }
/// Add spacing along the spacing direction. /// Add spacing along the spacing direction.
pub fn layout_spacing(&mut self, spacing: Spacing) { fn layout_spacing(&mut self, spacing: Spacing) {
match spacing { match spacing {
Spacing::Relative(v) => { Spacing::Relative(v) => {
// Resolve the spacing and limit it to the remaining space. // Resolve the spacing and limit it to the remaining space.
@ -169,7 +169,7 @@ impl<'a> StackLayouter<'a> {
} }
/// Layout an arbitrary block. /// Layout an arbitrary block.
pub fn layout_block( fn layout_block(
&mut self, &mut self,
world: Tracked<dyn World>, world: Tracked<dyn World>,
block: &Content, block: &Content,
@ -223,7 +223,7 @@ impl<'a> StackLayouter<'a> {
} }
/// Advance to the next region. /// Advance to the next region.
pub fn finish_region(&mut self) { fn finish_region(&mut self) {
// Determine the size of the stack in this region dependening on whether // Determine the size of the stack in this region dependening on whether
// the region expands. // the region expands.
let used = self.used.to_axes(self.axis); let used = self.used.to_axes(self.axis);
@ -279,7 +279,7 @@ impl<'a> StackLayouter<'a> {
} }
/// Finish layouting and return the resulting frames. /// Finish layouting and return the resulting frames.
pub fn finish(mut self) -> Vec<Frame> { fn finish(mut self) -> Vec<Frame> {
self.finish_region(); self.finish_region();
self.finished self.finished
} }
@ -287,7 +287,7 @@ impl<'a> StackLayouter<'a> {
/// A container with a main and cross component. /// A container with a main and cross component.
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)] #[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Gen<T> { struct Gen<T> {
/// The main component. /// The main component.
pub cross: T, pub cross: T,
/// The cross component. /// The cross component.
@ -296,12 +296,12 @@ pub struct Gen<T> {
impl<T> Gen<T> { impl<T> Gen<T> {
/// Create a new instance from the two components. /// Create a new instance from the two components.
pub const fn new(cross: T, main: T) -> Self { const fn new(cross: T, main: T) -> Self {
Self { cross, main } Self { cross, main }
} }
/// Convert to the specific representation, given the current main axis. /// Convert to the specific representation, given the current main axis.
pub fn to_axes(self, main: Axis) -> Axes<T> { fn to_axes(self, main: Axis) -> Axes<T> {
match main { match main {
Axis::X => Axes::new(self.main, self.cross), Axis::X => Axes::new(self.main, self.cross),
Axis::Y => Axes::new(self.cross, self.main), Axis::Y => Axes::new(self.cross, self.main),
@ -311,12 +311,12 @@ impl<T> Gen<T> {
impl Gen<Abs> { impl Gen<Abs> {
/// The zero value. /// The zero value.
pub fn zero() -> Self { fn zero() -> Self {
Self { cross: Abs::zero(), main: Abs::zero() } Self { cross: Abs::zero(), main: Abs::zero() }
} }
/// Convert to a point. /// Convert to a point.
pub fn to_point(self, main: Axis) -> Point { fn to_point(self, main: Axis) -> Point {
self.to_axes(main).to_point() self.to_axes(main).to_point()
} }
} }

View File

@ -1,19 +1,19 @@
//! Typst's standard library. //! Typst's standard library.
pub mod base;
pub mod graphics; pub mod graphics;
pub mod layout; pub mod layout;
pub mod math; pub mod math;
pub mod prelude; pub mod prelude;
pub mod structure; pub mod structure;
pub mod text; pub mod text;
pub mod utility;
mod ext; mod ext;
use typst::geom::{Align, Color, Dir, GenAlign}; use typst::geom::{Align, Color, Dir, GenAlign};
use typst::model::{LangItems, Node, Scope, StyleMap}; use typst::model::{LangItems, Node, Scope, StyleMap};
use self::layout::Layout; use self::layout::LayoutRoot;
/// Construct the standard library scope. /// Construct the standard library scope.
pub fn scope() -> Scope { pub fn scope() -> Scope {
@ -83,32 +83,32 @@ pub fn scope() -> Scope {
std.define("NN", ""); std.define("NN", "");
std.define("RR", ""); std.define("RR", "");
// Utility. // Base.
std.def_fn("type", utility::type_); std.def_fn("type", base::type_);
std.def_fn("assert", utility::assert); std.def_fn("assert", base::assert);
std.def_fn("eval", utility::eval); std.def_fn("eval", base::eval);
std.def_fn("int", utility::int); std.def_fn("int", base::int);
std.def_fn("float", utility::float); std.def_fn("float", base::float);
std.def_fn("abs", utility::abs); std.def_fn("abs", base::abs);
std.def_fn("min", utility::min); std.def_fn("min", base::min);
std.def_fn("max", utility::max); std.def_fn("max", base::max);
std.def_fn("even", utility::even); std.def_fn("even", base::even);
std.def_fn("odd", utility::odd); std.def_fn("odd", base::odd);
std.def_fn("mod", utility::mod_); std.def_fn("mod", base::mod_);
std.def_fn("range", utility::range); std.def_fn("range", base::range);
std.def_fn("luma", utility::luma); std.def_fn("luma", base::luma);
std.def_fn("rgb", utility::rgb); std.def_fn("rgb", base::rgb);
std.def_fn("cmyk", utility::cmyk); std.def_fn("cmyk", base::cmyk);
std.def_fn("repr", utility::repr); std.def_fn("repr", base::repr);
std.def_fn("str", utility::str); std.def_fn("str", base::str);
std.def_fn("regex", utility::regex); std.def_fn("regex", base::regex);
std.def_fn("letter", utility::letter); std.def_fn("letter", base::letter);
std.def_fn("roman", utility::roman); std.def_fn("roman", base::roman);
std.def_fn("symbol", utility::symbol); std.def_fn("symbol", base::symbol);
std.def_fn("lorem", utility::lorem); std.def_fn("lorem", base::lorem);
std.def_fn("csv", utility::csv); std.def_fn("csv", base::csv);
std.def_fn("json", utility::json); std.def_fn("json", base::json);
std.def_fn("xml", utility::xml); std.def_fn("xml", base::xml);
// Predefined colors. // Predefined colors.
std.define("black", Color::BLACK); std.define("black", Color::BLACK);
@ -155,7 +155,7 @@ pub fn styles() -> StyleMap {
/// Construct the standard lang item mapping. /// Construct the standard lang item mapping.
pub fn items() -> LangItems { pub fn items() -> LangItems {
LangItems { LangItems {
root: |world, content| content.layout(world), root: |world, content| content.layout_root(world),
em: |styles| styles.get(text::TextNode::SIZE), em: |styles| styles.get(text::TextNode::SIZE),
dir: |styles| styles.get(text::TextNode::DIR), dir: |styles| styles.get(text::TextNode::DIR),
space: || text::SpaceNode.pack(), space: || text::SpaceNode.pack(),

View File

@ -5,7 +5,7 @@ use rex::parser::color::RGBA;
use rex::render::{Backend, Cursor, Renderer}; use rex::render::{Backend, Cursor, Renderer};
use typst::font::Font; use typst::font::Font;
use super::*; use super::MathNode;
use crate::prelude::*; use crate::prelude::*;
use crate::text::{variant, LinebreakNode, SpaceNode, TextNode}; use crate::text::{variant, LinebreakNode, SpaceNode, TextNode};

View File

@ -1,27 +1,20 @@
//! Helpful imports for creating library functionality. //! Helpful imports for creating library functionality.
pub use std::fmt::{self, Debug, Formatter}; pub use std::fmt::{self, Debug, Formatter};
pub use std::hash::Hash;
pub use std::io;
pub use std::num::NonZeroUsize; pub use std::num::NonZeroUsize;
pub use std::sync::Arc;
pub use comemo::Tracked; pub use comemo::Tracked;
pub use typst::diag::{ pub use typst::diag::{bail, error, with_alternative, At, SourceResult, StrResult};
bail, error, with_alternative, At, FileError, FileResult, SourceError, SourceResult,
StrResult,
};
pub use typst::frame::*; pub use typst::frame::*;
pub use typst::geom::*; pub use typst::geom::*;
pub use typst::model::{ pub use typst::model::{
array, capability, castable, dict, dynamic, format_str, node, Args, Array, array, capability, castable, dict, dynamic, format_str, node, Args, Array, Cast,
Capability, Cast, Content, Dict, Dynamic, Fold, Func, Key, LangItems, Node, Resolve, Content, Dict, Fold, Func, Key, Node, Resolve, Scope, Selector, Show, Smart, Str,
Scope, Selector, Show, Smart, Str, StyleChain, StyleMap, StyleVec, Value, Vm, StyleChain, StyleMap, StyleVec, Value, Vm,
}; };
pub use typst::syntax::{Span, Spanned}; pub use typst::syntax::{Span, Spanned};
pub use typst::util::{format_eco, EcoString}; pub use typst::util::{format_eco, EcoString};
pub use typst::World; pub use typst::World;
pub use super::ext::{ContentExt, StyleMapExt}; pub use super::ext::{ContentExt, StyleMapExt};
pub use super::layout::{Layout, LayoutBlock, LayoutInline, Regions}; pub use super::layout::{LayoutBlock, LayoutInline, Regions};
pub use super::text::{FallbackList, TextNode};

View File

@ -1,9 +1,9 @@
use unscanny::Scanner; use unscanny::Scanner;
use crate::base::Numbering;
use crate::layout::{BlockSpacing, GridNode, HNode, TrackSizing}; use crate::layout::{BlockSpacing, GridNode, HNode, TrackSizing};
use crate::prelude::*; use crate::prelude::*;
use crate::text::{ParNode, SpaceNode}; use crate::text::{ParNode, SpaceNode, TextNode};
use crate::utility::Numbering;
/// An unordered (bulleted) or ordered (numbered) list. /// An unordered (bulleted) or ordered (numbered) list.
#[derive(Debug, Hash)] #[derive(Debug, Hash)]

View File

@ -1,4 +1,5 @@
use crate::prelude::*; use crate::prelude::*;
use crate::text::TextNode;
/// A reference to a label. /// A reference to a label.
#[derive(Debug, Hash)] #[derive(Debug, Hash)]

View File

@ -70,7 +70,7 @@ impl<const L: DecoLine> Show for DecoNode<L> {
/// ///
/// For more details, see [`DecoNode`]. /// For more details, see [`DecoNode`].
#[derive(Debug, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Decoration { pub(super) struct Decoration {
pub line: DecoLine, pub line: DecoLine,
pub stroke: PartialStroke<Abs>, pub stroke: PartialStroke<Abs>,
pub offset: Smart<Abs>, pub offset: Smart<Abs>,
@ -91,7 +91,7 @@ pub const STRIKETHROUGH: DecoLine = 1;
pub const OVERLINE: DecoLine = 2; pub const OVERLINE: DecoLine = 2;
/// Add line decorations to a single run of shaped text. /// Add line decorations to a single run of shaped text.
pub fn decorate( pub(super) fn decorate(
frame: &mut Frame, frame: &mut Frame,
deco: &Decoration, deco: &Decoration,
text: &Text, text: &Text,

View File

@ -11,7 +11,6 @@ mod shift;
pub use deco::*; pub use deco::*;
pub use link::*; pub use link::*;
pub use par::*; pub use par::*;
pub use quotes::*;
pub use raw::*; pub use raw::*;
pub use shaping::*; pub use shaping::*;
pub use shift::*; pub use shift::*;
@ -22,6 +21,7 @@ use rustybuzz::Tag;
use typst::font::{FontMetrics, FontStretch, FontStyle, FontWeight, VerticalFontMetric}; use typst::font::{FontMetrics, FontStretch, FontStyle, FontWeight, VerticalFontMetric};
use typst::util::EcoString; use typst::util::EcoString;
use self::quotes::*;
use crate::prelude::*; use crate::prelude::*;
/// A single run of text with the same style. /// A single run of text with the same style.
@ -107,22 +107,22 @@ impl TextNode {
/// Whether the font weight should be increased by 300. /// Whether the font weight should be increased by 300.
#[property(skip, fold)] #[property(skip, fold)]
pub const BOLD: Toggle = false; pub(super) const BOLD: Toggle = false;
/// Whether the font style should be inverted. /// Whether the font style should be inverted.
#[property(skip, fold)] #[property(skip, fold)]
pub const ITALIC: Toggle = false; pub(super) const ITALIC: Toggle = false;
/// A case transformation that should be applied to the text. /// A case transformation that should be applied to the text.
#[property(skip)] #[property(skip)]
pub const CASE: Option<Case> = None; pub(super) const CASE: Option<Case> = None;
/// Whether small capital glyphs should be used. ("smcp") /// Whether small capital glyphs should be used. ("smcp")
#[property(skip)] #[property(skip)]
pub const SMALLCAPS: bool = false; pub(super) const SMALLCAPS: bool = false;
/// A destination the text should be linked to. /// A destination the text should be linked to.
#[property(skip, referenced)] #[property(skip, referenced)]
pub const LINK: Option<Destination> = None; pub(crate) const LINK: Option<Destination> = None;
/// Decorative lines. /// Decorative lines.
#[property(skip, fold)] #[property(skip, fold)]
pub const DECO: Decoration = vec![]; pub(super) const DECO: Decoration = vec![];
fn construct(_: &mut Vm, args: &mut Args) -> SourceResult<Content> { fn construct(_: &mut Vm, args: &mut Args) -> SourceResult<Content> {
// The text constructor is special: It doesn't create a text node. // The text constructor is special: It doesn't create a text node.

View File

@ -4,7 +4,7 @@ use super::{Lang, Region};
/// State machine for smart quote subtitution. /// State machine for smart quote subtitution.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct Quoter { pub(super) struct Quoter {
/// How many quotes have been opened. /// How many quotes have been opened.
quote_depth: usize, quote_depth: usize,
/// Whether an opening quote might follow. /// Whether an opening quote might follow.
@ -68,7 +68,7 @@ fn is_opening_bracket(c: char) -> bool {
} }
/// Decides which quotes to subtitute smart quotes with. /// Decides which quotes to subtitute smart quotes with.
pub struct Quotes<'s> { pub(super) struct Quotes<'s> {
/// The opening single quote. /// The opening single quote.
pub single_open: &'s str, pub single_open: &'s str,
/// The closing single quote. /// The closing single quote.

View File

@ -13,7 +13,7 @@ use crate::prelude::*;
/// This type contains owned or borrowed shaped text runs, which can be /// This type contains owned or borrowed shaped text runs, which can be
/// measured, used to reshape substrings more quickly and converted into a /// measured, used to reshape substrings more quickly and converted into a
/// frame. /// frame.
pub struct ShapedText<'a> { pub(super) struct ShapedText<'a> {
/// The text that was shaped. /// The text that was shaped.
pub text: &'a str, pub text: &'a str,
/// The text direction. /// The text direction.
@ -32,7 +32,7 @@ pub struct ShapedText<'a> {
/// A single glyph resulting from shaping. /// A single glyph resulting from shaping.
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
pub struct ShapedGlyph { pub(super) struct ShapedGlyph {
/// The font the glyph is contained in. /// The font the glyph is contained in.
pub font: Font, pub font: Font,
/// The glyph's index in the font. /// The glyph's index in the font.
@ -318,7 +318,7 @@ struct ShapingContext<'a> {
} }
/// Shape text into [`ShapedText`]. /// Shape text into [`ShapedText`].
pub fn shape<'a>( pub(super) fn shape<'a>(
world: Tracked<dyn World>, world: Tracked<dyn World>,
text: &'a str, text: &'a str,
styles: StyleChain<'a>, styles: StyleChain<'a>,
@ -534,7 +534,7 @@ fn nbsp_delta(font: &Font) -> Option<Em> {
Some(font.advance(nbsp)? - font.advance(space)?) Some(font.advance(nbsp)? - font.advance(space)?)
} }
/// Resolve the font variant with `BOLD` and `ITALIC` factored in. /// Resolve the font variant.
pub fn variant(styles: StyleChain) -> FontVariant { pub fn variant(styles: StyleChain) -> FontVariant {
let mut variant = FontVariant::new( let mut variant = FontVariant::new(
styles.get(TextNode::STYLE), styles.get(TextNode::STYLE),

View File

@ -11,7 +11,7 @@ use crate::prelude::*;
/// codepoints. If that fails, we fall back to rendering shrunk normal letters /// codepoints. If that fails, we fall back to rendering shrunk normal letters
/// in a raised way. /// in a raised way.
#[derive(Debug, Hash)] #[derive(Debug, Hash)]
pub struct ShiftNode<const S: ScriptKind>(pub Content); pub struct ShiftNode<const S: ShiftKind>(pub Content);
/// Shift the text into superscript. /// Shift the text into superscript.
pub type SuperNode = ShiftNode<SUPERSCRIPT>; pub type SuperNode = ShiftNode<SUPERSCRIPT>;
@ -20,7 +20,7 @@ pub type SuperNode = ShiftNode<SUPERSCRIPT>;
pub type SubNode = ShiftNode<SUBSCRIPT>; pub type SubNode = ShiftNode<SUBSCRIPT>;
#[node(Show)] #[node(Show)]
impl<const S: ScriptKind> ShiftNode<S> { impl<const S: ShiftKind> ShiftNode<S> {
/// Whether to prefer the dedicated sub- and superscript characters of the /// Whether to prefer the dedicated sub- and superscript characters of the
/// font. /// font.
pub const TYPOGRAPHIC: bool = true; pub const TYPOGRAPHIC: bool = true;
@ -35,7 +35,7 @@ impl<const S: ScriptKind> ShiftNode<S> {
} }
} }
impl<const S: ScriptKind> Show for ShiftNode<S> { impl<const S: ShiftKind> Show for ShiftNode<S> {
fn unguard_parts(&self, _: Selector) -> Content { fn unguard_parts(&self, _: Selector) -> Content {
Self(self.0.clone()).pack() Self(self.0.clone()).pack()
} }
@ -72,7 +72,7 @@ impl<const S: ScriptKind> Show for ShiftNode<S> {
/// Find and transform the text contained in `content` to the given script kind /// Find and transform the text contained in `content` to the given script kind
/// if and only if it only consists of `Text`, `Space`, and `Empty` leaf nodes. /// if and only if it only consists of `Text`, `Space`, and `Empty` leaf nodes.
fn search_text(content: &Content, mode: ScriptKind) -> Option<EcoString> { fn search_text(content: &Content, mode: ShiftKind) -> Option<EcoString> {
if content.is_empty() { if content.is_empty() {
Some(EcoString::new()) Some(EcoString::new())
} else if content.is::<SpaceNode>() { } else if content.is::<SpaceNode>() {
@ -114,7 +114,7 @@ fn is_shapable(world: Tracked<dyn World>, text: &str, styles: StyleChain) -> boo
/// Convert a string to sub- or superscript codepoints if all characters /// Convert a string to sub- or superscript codepoints if all characters
/// can be mapped to such a codepoint. /// can be mapped to such a codepoint.
fn convert_script(text: &str, mode: ScriptKind) -> Option<EcoString> { fn convert_script(text: &str, mode: ShiftKind) -> Option<EcoString> {
let mut result = EcoString::with_capacity(text.len()); let mut result = EcoString::with_capacity(text.len());
let converter = match mode { let converter = match mode {
SUPERSCRIPT => to_superscript_codepoint, SUPERSCRIPT => to_superscript_codepoint,
@ -179,10 +179,10 @@ fn to_subscript_codepoint(c: char) -> Option<char> {
} }
/// A category of script. /// A category of script.
pub type ScriptKind = usize; pub type ShiftKind = usize;
/// Text that is rendered smaller and raised, also known as superior. /// Text that is rendered smaller and raised, also known as superior.
const SUPERSCRIPT: ScriptKind = 0; const SUPERSCRIPT: ShiftKind = 0;
/// Text that is rendered smaller and lowered, also known as inferior. /// Text that is rendered smaller and lowered, also known as inferior.
const SUBSCRIPT: ScriptKind = 1; const SUBSCRIPT: ShiftKind = 1;

View File

Before

Width:  |  Height:  |  Size: 27 KiB

After

Width:  |  Height:  |  Size: 27 KiB

View File

Before

Width:  |  Height:  |  Size: 1.4 KiB

After

Width:  |  Height:  |  Size: 1.4 KiB

View File

Before

Width:  |  Height:  |  Size: 595 B

After

Width:  |  Height:  |  Size: 595 B

View File

Before

Width:  |  Height:  |  Size: 8.4 KiB

After

Width:  |  Height:  |  Size: 8.4 KiB

View File

Before

Width:  |  Height:  |  Size: 5.3 KiB

After

Width:  |  Height:  |  Size: 5.3 KiB

View File

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

Before

Width:  |  Height:  |  Size: 10 KiB

After

Width:  |  Height:  |  Size: 10 KiB

View File

Before

Width:  |  Height:  |  Size: 6.4 KiB

After

Width:  |  Height:  |  Size: 6.4 KiB

View File

Before

Width:  |  Height:  |  Size: 57 KiB

After

Width:  |  Height:  |  Size: 57 KiB

View File

@ -2,13 +2,12 @@ use std::path::{Path, PathBuf};
use comemo::{Prehashed, Track, Tracked}; use comemo::{Prehashed, Track, Tracked};
use iai::{black_box, main, Iai}; use iai::{black_box, main, Iai};
use unscanny::Scanner;
use typst::diag::{FileError, FileResult}; use typst::diag::{FileError, FileResult};
use typst::font::{Font, FontBook}; use typst::font::{Font, FontBook};
use typst::syntax::{Source, SourceId, TokenMode, Tokens}; use typst::syntax::{Source, SourceId, TokenMode, Tokens};
use typst::util::Buffer; use typst::util::Buffer;
use typst::{Config, World}; use typst::{Config, World};
use unscanny::Scanner;
const TEXT: &str = include_str!("../typ/benches/bench.typ"); const TEXT: &str = include_str!("../typ/benches/bench.typ");
const FONT: &[u8] = include_bytes!("../../fonts/IBMPlexSans-Regular.ttf"); const FONT: &[u8] = include_bytes!("../../fonts/IBMPlexSans-Regular.ttf");

View File

@ -11,9 +11,6 @@ use comemo::Prehashed;
use elsa::FrozenVec; use elsa::FrozenVec;
use once_cell::unsync::OnceCell; use once_cell::unsync::OnceCell;
use tiny_skia as sk; use tiny_skia as sk;
use unscanny::Scanner;
use walkdir::WalkDir;
use typst::diag::{bail, FileError, FileResult}; use typst::diag::{bail, FileError, FileResult};
use typst::font::{Font, FontBook}; use typst::font::{Font, FontBook};
use typst::frame::{Element, Frame}; use typst::frame::{Element, Frame};
@ -24,6 +21,8 @@ use typst::util::{Buffer, PathExt};
use typst::{Config, World}; use typst::{Config, World};
use typst_library::layout::PageNode; use typst_library::layout::PageNode;
use typst_library::text::{TextNode, TextSize}; use typst_library::text::{TextNode, TextSize};
use unscanny::Scanner;
use walkdir::WalkDir;
const TYP_DIR: &str = "typ"; const TYP_DIR: &str = "typ";
const REF_DIR: &str = "ref"; const REF_DIR: &str = "ref";

View File

@ -1,8 +1,7 @@
// Test basic functions. // Test the `assert` function.
// Ref: false // Ref: false
--- ---
// Test the `assert` function.
#assert(1 + 1 == 2) #assert(1 + 1 == 2)
#assert(range(2, 5) == (2, 3, 4)) #assert(range(2, 5) == (2, 3, 4))
#assert(not false) #assert(not false)

View File

@ -10,7 +10,7 @@
#table(columns: data(0).len(), ..cells) #table(columns: data(0).len(), ..cells)
--- ---
// Error: 6-16 file not found (searched at typ/utility/nope.csv) // Error: 6-16 file not found (searched at typ/base/nope.csv)
#csv("nope.csv") #csv("nope.csv")
--- ---

7
tests/typ/base/type.typ Normal file
View File

@ -0,0 +1,7 @@
// Test the `type` function.
// Ref: false
---
#test(type(1), "integer")
#test(type(ltr), "direction")
#test(type(10 / 3), "float")

View File

@ -1,4 +1,4 @@
// Test simple text. // Test plain text.
--- ---
#set page(width: 250pt, height: 120pt) #set page(width: 250pt, height: 120pt)