Add support for shortcut links in docs (#3547)

This commit is contained in:
Laurenz 2024-03-04 15:51:22 +01:00 committed by GitHub
parent b005dc37e5
commit e3bd39c9d1
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
64 changed files with 534 additions and 530 deletions

View File

@ -20,6 +20,7 @@ pub fn category(_: TokenStream, item: syn::Item) -> Result<TokenStream> {
Ok(quote! { Ok(quote! {
#(#attrs)* #(#attrs)*
#[allow(rustdoc::broken_intra_doc_links)]
#vis static #ident: #ty = { #vis static #ident: #ty = {
static DATA: #foundations::CategoryData = #foundations::CategoryData { static DATA: #foundations::CategoryData = #foundations::CategoryData {
name: #name, name: #name,

View File

@ -311,6 +311,7 @@ fn create_struct(element: &Elem) -> TokenStream {
#[doc = #docs] #[doc = #docs]
#[derive(#debug Clone, Hash)] #[derive(#debug Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)] #[allow(clippy::derived_hash_with_manual_eq)]
#[allow(rustdoc::broken_intra_doc_links)]
#vis struct #ident { #vis struct #ident {
#(#fields,)* #(#fields,)*
} }

View File

@ -233,6 +233,7 @@ fn create(func: &Func, item: &syn::ItemFn) -> TokenStream {
quote! { quote! {
#[doc = #docs] #[doc = #docs]
#[allow(dead_code)] #[allow(dead_code)]
#[allow(rustdoc::broken_intra_doc_links)]
#item #item
#[doc(hidden)] #[doc(hidden)]

View File

@ -101,7 +101,14 @@ fn create(ty: &Type, item: Option<&syn::Item>) -> TokenStream {
} }
}; };
let attr = item.map(|_| {
quote! { quote! {
#[allow(rustdoc::broken_intra_doc_links)]
}
});
quote! {
#attr
#item #item
#cast #cast

View File

@ -17,10 +17,10 @@ use crate::util::LazyHash;
/// using a [for loop]($scripting/#loops). /// using a [for loop]($scripting/#loops).
/// ///
/// You can convert /// You can convert
/// - a [string]($str) or an [array]($array) of integers to bytes with the /// - a [string]($str) or an [array] of integers to bytes with the [`bytes`]
/// [`bytes`]($bytes) constructor /// constructor
/// - bytes to a string with the [`str`]($str) constructor, with UTF-8 encoding /// - bytes to a string with the [`str`] constructor, with UTF-8 encoding
/// - bytes to an array of integers with the [`array`]($array) constructor /// - bytes to an array of integers with the [`array`] constructor
/// ///
/// When [reading]($read) data from a file, you can decide whether to load it /// When [reading]($read) data from a file, you can decide whether to load it
/// as a string or as raw bytes. /// as a string or as raw bytes.

View File

@ -67,7 +67,7 @@ use crate::util::{fat, BitSet, LazyHash};
/// ///
/// In the web app, you can hover over a content variable to see exactly which /// In the web app, you can hover over a content variable to see exactly which
/// elements the content is composed of and what fields they have. /// elements the content is composed of and what fields they have.
/// Alternatively, you can inspect the output of the [`repr`]($repr) function. /// Alternatively, you can inspect the output of the [`repr`] function.
#[ty(scope, cast)] #[ty(scope, cast)]
#[derive(Clone, Hash)] #[derive(Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)] #[allow(clippy::derived_hash_with_manual_eq)]
@ -569,10 +569,9 @@ impl Content {
} }
/// The location of the content. This is only available on content returned /// The location of the content. This is only available on content returned
/// by [query]($query) or provided by a /// by [query] or provided by a [show rule]($reference/styling/#show-rules),
/// [show rule]($reference/styling/#show-rules), for other content it will /// for other content it will be `{none}`. The resulting location can be
/// be `{none}`. The resulting location can be used with /// used with [counters]($counter), [state] and [queries]($query).
/// [counters]($counter), [state]($state) and [queries]($query).
#[func] #[func]
pub fn location(&self) -> Option<Location> { pub fn location(&self) -> Option<Location> {
self.inner.location self.inner.location

View File

@ -213,8 +213,8 @@ impl Datetime {
impl Datetime { impl Datetime {
/// Creates a new datetime. /// Creates a new datetime.
/// ///
/// You can specify the [datetime]($datetime) using a year, month, day, /// You can specify the [datetime] using a year, month, day, hour, minute,
/// hour, minute, and second. /// and second.
/// ///
/// _Note_: Depending on which components of the datetime you specify, Typst /// _Note_: Depending on which components of the datetime you specify, Typst
/// will store it in one of the following three ways: /// will store it in one of the following three ways:

View File

@ -22,8 +22,8 @@ impl Duration {
impl Duration { impl Duration {
/// Creates a new duration. /// Creates a new duration.
/// ///
/// You can specify the [duration]($duration) using weeks, days, hours, /// You can specify the [duration] using weeks, days, hours, minutes and
/// minutes and seconds. You can also get a duration by subtracting two /// seconds. You can also get a duration by subtracting two
/// [datetimes]($datetime). /// [datetimes]($datetime).
/// ///
/// ```example /// ```example

View File

@ -44,23 +44,22 @@ pub use crate::__select_where as select_where;
/// A filter for selecting elements within the document. /// A filter for selecting elements within the document.
/// ///
/// You can construct a selector in the following ways: /// You can construct a selector in the following ways:
/// - you can use an element [function]($function) /// - you can use an element [function]
/// - you can filter for an element function with /// - you can filter for an element function with
/// [specific fields]($function.where) /// [specific fields]($function.where)
/// - you can use a [string]($str) or [regular expression]($regex) /// - you can use a [string]($str) or [regular expression]($regex)
/// - you can use a [`{<label>}`]($label) /// - you can use a [`{<label>}`]($label)
/// - you can use a [`location`]($location) /// - you can use a [`location`]
/// - call the [`selector`]($selector) constructor to convert any of the above /// - call the [`selector`] constructor to convert any of the above types into a
/// types into a selector value and use the methods below to refine it /// selector value and use the methods below to refine it
/// ///
/// Selectors are used to [apply styling rules]($styling/#show-rules) to /// Selectors are used to [apply styling rules]($styling/#show-rules) to
/// elements. You can also use selectors to [query]($query) the document for /// elements. You can also use selectors to [query] the document for certain
/// certain types of elements. /// types of elements.
/// ///
/// Furthermore, you can pass a selector to several of Typst's built-in /// Furthermore, you can pass a selector to several of Typst's built-in
/// functions to configure their behaviour. One such example is the /// functions to configure their behaviour. One such example is the [outline]
/// [outline]($outline) where it can be used to change which elements are listed /// where it can be used to change which elements are listed within the outline.
/// within the outline.
/// ///
/// Multiple selectors can be combined using the methods shown below. However, /// Multiple selectors can be combined using the methods shown below. However,
/// not all kinds of selectors are supported in all places, at the moment. /// not all kinds of selectors are supported in all places, at the moment.

View File

@ -20,9 +20,9 @@ use crate::util::LazyHash;
/// Provides access to active styles. /// Provides access to active styles.
/// ///
/// The styles are currently opaque and only useful in combination with the /// The styles are currently opaque and only useful in combination with the
/// [`measure`]($measure) function. See its documentation for more details. In /// [`measure`] function. See its documentation for more details. In the future,
/// the future, the provided styles might also be directly accessed to look up /// the provided styles might also be directly accessed to look up styles
/// styles defined by [set rules]($styling/#set-rules). /// defined by [set rules]($styling/#set-rules).
/// ///
/// ```example /// ```example
/// #let thing(body) = context { /// #let thing(body) = context {

View File

@ -19,7 +19,7 @@ use crate::foundations::{cast, func, repr, scope, ty, Repr};
/// as `0`, `0.0`, `0.0.0`, and so on. /// as `0`, `0.0`, `0.0.0`, and so on.
/// ///
/// You can convert a version to an array of explicitly given components using /// You can convert a version to an array of explicitly given components using
/// the [`array`]($array) constructor. /// the [`array`] constructor.
#[ty(scope, cast)] #[ty(scope, cast)]
#[derive(Debug, Default, Clone, Hash)] #[derive(Debug, Default, Clone, Hash)]
#[allow(clippy::derived_hash_with_manual_eq)] #[allow(clippy::derived_hash_with_manual_eq)]

View File

@ -28,14 +28,14 @@ use crate::World;
/// other things you want to count. /// other things you want to count.
/// ///
/// Since counters change throughout the course of the document, their current /// Since counters change throughout the course of the document, their current
/// value is _contextual_ It is recommended to read the chapter on /// value is _contextual._ It is recommended to read the chapter on [context]
/// [context]($context) before continuing here. /// before continuing here.
/// ///
/// # Accessing a counter { #accessing } /// # Accessing a counter { #accessing }
/// To access the raw value of a counter, we can use the [`get`]($counter.get) /// To access the raw value of a counter, we can use the [`get`]($counter.get)
/// function. This function returns an [array]($array): Counters can have /// function. This function returns an [array]: Counters can have multiple
/// multiple levels (in the case of headings for sections, subsections, and so /// levels (in the case of headings for sections, subsections, and so on), and
/// on), and each item in the array corresponds to one level. /// each item in the array corresponds to one level.
/// ///
/// ```example /// ```example
/// #set heading(numbering: "1.") /// #set heading(numbering: "1.")
@ -49,8 +49,7 @@ use crate::World;
/// Often, we want to display the value of a counter in a more human-readable /// Often, we want to display the value of a counter in a more human-readable
/// way. To do that, we can call the [`display`]($counter.display) function on /// way. To do that, we can call the [`display`]($counter.display) function on
/// the counter. This function retrieves the current counter value and formats /// the counter. This function retrieves the current counter value and formats
/// it either with a provided or with an automatically inferred /// it either with a provided or with an automatically inferred [numbering].
/// [numbering]($numbering).
/// ///
/// ```example /// ```example
/// #set heading(numbering: "1.") /// #set heading(numbering: "1.")
@ -199,7 +198,7 @@ use crate::World;
/// ``` /// ```
/// ///
/// # Other kinds of state { #other-state } /// # Other kinds of state { #other-state }
/// The `counter` type is closely related to [state]($state) type. Read its /// The `counter` type is closely related to [state] type. Read its
/// documentation for more details on state management in Typst and why it /// documentation for more details on state management in Typst and why it
/// doesn't just use normal variables for counters. /// doesn't just use normal variables for counters.
#[ty(scope)] #[ty(scope)]
@ -410,7 +409,7 @@ impl Counter {
/// label, /// label,
/// - If this is an element function or selector, counts through its /// - If this is an element function or selector, counts through its
/// elements, /// elements,
/// - If this is the [`page`]($page) function, counts through pages. /// - If this is the [`page`] function, counts through pages.
key: CounterKey, key: CounterKey,
) -> Counter { ) -> Counter {
Self(key) Self(key)

View File

@ -5,21 +5,21 @@ use crate::introspection::Location;
/// Provides the current location in the document. /// Provides the current location in the document.
/// ///
/// You can think of `here` as a low-level building block that directly extracts /// You can think of `here` as a low-level building block that directly extracts
/// the current location from the active [context]($context). Some other /// the current location from the active [context]. Some other functions use it
/// functions use it internally: For instance, `{counter.get()}` is equivalent /// internally: For instance, `{counter.get()}` is equivalent to
/// to `{counter.at(here())}`. /// `{counter.at(here())}`.
/// ///
/// Within show rules on [locatable]($location/#locatable) elements, `{here()}` /// Within show rules on [locatable]($location/#locatable) elements, `{here()}`
/// will match the location of the shown element. /// will match the location of the shown element.
/// ///
/// If you want to display the current page number, refer to the documentation /// If you want to display the current page number, refer to the documentation
/// of the [`counter`]($counter) type. While `here` can be used to determine the /// of the [`counter`] type. While `here` can be used to determine the physical
/// physical page number, typically you want the logical page number that may, /// page number, typically you want the logical page number that may, for
/// for instance, have been reset after a preface. /// instance, have been reset after a preface.
/// ///
/// # Examples /// # Examples
/// Determining the current position in the document in combination with /// Determining the current position in the document in combination with
/// [`locate`]($locate): /// [`locate`]:
/// ```example /// ```example
/// #context [ /// #context [
/// I am located at /// I am located at
@ -27,7 +27,7 @@ use crate::introspection::Location;
/// ] /// ]
/// ``` /// ```
/// ///
/// Running a [query]($query) for elements before the current position: /// Running a [query] for elements before the current position:
/// ```example /// ```example
/// = Introduction /// = Introduction
/// = Background /// = Background
@ -40,8 +40,7 @@ use crate::introspection::Location;
/// ///
/// = Conclusion /// = Conclusion
/// ``` /// ```
/// Refer to the [`selector`]($selector) type for more details on before/after /// Refer to the [`selector`] type for more details on before/after selectors.
/// selectors.
#[func(contextual)] #[func(contextual)]
pub fn here( pub fn here(
/// The callsite context. /// The callsite context.

View File

@ -10,8 +10,8 @@ use crate::syntax::Span;
/// Determines the location of an element in the document. /// Determines the location of an element in the document.
/// ///
/// Takes a selector that must match exactly one element and returns that /// Takes a selector that must match exactly one element and returns that
/// element's [`location`]($location). This location can, in particular, be used /// element's [`location`]. This location can, in particular, be used to
/// to retrieve the physical [`page`]($location.page) number and /// retrieve the physical [`page`]($location.page) number and
/// [`position`]($location.position) (page, x, y) for that element. /// [`position`]($location.position) (page, x, y) for that element.
/// ///
/// # Examples /// # Examples
@ -27,7 +27,7 @@ use crate::syntax::Span;
/// ///
/// # Compatibility /// # Compatibility
/// In Typst 0.10 and lower, the `locate` function took a closure that made the /// In Typst 0.10 and lower, the `locate` function took a closure that made the
/// current location in the document available (like [`here`]($here) does now). /// current location in the document available (like [`here`] does now).
/// Compatibility with the old way will remain for a while to give package /// Compatibility with the old way will remain for a while to give package
/// authors time to upgrade. To that effect, `locate` detects whether it /// authors time to upgrade. To that effect, `locate` detects whether it
/// received a selector or a user-defined function and adjusts its semantics /// received a selector or a user-defined function and adjusts its semantics
@ -44,8 +44,8 @@ pub fn locate(
/// located. /// located.
/// ///
/// Especially useful in combination with /// Especially useful in combination with
/// - [`here`]($here) to locate the current context, /// - [`here`] to locate the current context,
/// - a [`location`]($location) retrieved from some queried element via the /// - a [`location`] retrieved from some queried element via the
/// [`location()`]($content.location) method on content. /// [`location()`]($content.location) method on content.
selector: LocateInput, selector: LocateInput,
) -> HintedStrResult<LocateOutput> { ) -> HintedStrResult<LocateOutput> {

View File

@ -11,17 +11,15 @@ use crate::model::Numbering;
/// ///
/// A location uniquely identifies an element in the document and lets you /// A location uniquely identifies an element in the document and lets you
/// access its absolute position on the pages. You can retrieve the current /// access its absolute position on the pages. You can retrieve the current
/// location with the [`here`]($here) function and the location of a queried /// location with the [`here`] function and the location of a queried or shown
/// or shown element with the [`location()`]($content.location) method on /// element with the [`location()`]($content.location) method on content.
/// content.
/// ///
/// # Locatable elements { #locatable } /// # Locatable elements { #locatable }
/// Currently, only a subset of element functions is locatable. Aside from /// Currently, only a subset of element functions is locatable. Aside from
/// headings and figures, this includes equations, references and all /// headings and figures, this includes equations, references and all elements
/// elements with an explicit label. As a result, you _can_ query for e.g. /// with an explicit label. As a result, you _can_ query for e.g. [`strong`]
/// [`strong`]($strong) elements, but you will find only those that have an /// elements, but you will find only those that have an explicit label attached
/// explicit label attached to them. This limitation will be resolved in the /// to them. This limitation will be resolved in the future.
/// future.
#[ty(scope)] #[ty(scope)]
#[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Location { pub struct Location {
@ -54,7 +52,7 @@ impl Location {
/// If you want to know the value of the page counter, use /// If you want to know the value of the page counter, use
/// `{counter(page).at(loc)}` instead. /// `{counter(page).at(loc)}` instead.
/// ///
/// Can be used with [`here`]($here) to retrieve the physical page position /// Can be used with [`here`] to retrieve the physical page position
/// of the current context: /// of the current context:
/// ```example /// ```example
/// #context [ /// #context [

View File

@ -6,11 +6,11 @@ use crate::realize::{Behave, Behaviour};
/// Exposes a value to the query system without producing visible content. /// Exposes a value to the query system without producing visible content.
/// ///
/// This element can be retrieved with the [`query`]($query) function and from /// This element can be retrieved with the [`query`] function and from the
/// the command line with [`typst query`]($reference/meta/query/#cli-queries). /// command line with [`typst query`]($reference/meta/query/#cli-queries). Its
/// Its purpose is to expose an arbitrary value to the introspection system. To /// purpose is to expose an arbitrary value to the introspection system. To
/// identify a metadata value among others, you can attach a [`label`]($label) /// identify a metadata value among others, you can attach a [`label`] to it and
/// to it and query for that label. /// query for that label.
/// ///
/// The `metadata` element is especially useful for command line queries because /// The `metadata` element is especially useful for command line queries because
/// it allows you to expose arbitrary values to the outside world. /// it allows you to expose arbitrary values to the outside world.

View File

@ -43,7 +43,7 @@ use crate::realize::{Behave, Behaviour};
/// of figures or headers which show the current chapter title. /// of figures or headers which show the current chapter title.
/// ///
/// Most of the functions are _contextual._ It is recommended to read the chapter /// Most of the functions are _contextual._ It is recommended to read the chapter
/// on [context]($context) before continuing here. /// on [context] before continuing here.
#[category] #[category]
pub static INTROSPECTION: Category; pub static INTROSPECTION: Category;

View File

@ -7,21 +7,18 @@ use crate::introspection::Location;
/// ///
/// The `query` functions lets you search your document for elements of a /// The `query` functions lets you search your document for elements of a
/// particular type or with a particular label. To use it, you first need to /// particular type or with a particular label. To use it, you first need to
/// retrieve the current document location with the [`locate`]($locate) /// ensure that [context] is available.
/// function.
///
/// You can get the location of the elements returned by `query` with
/// [`location`]($content.location).
/// ///
/// # Finding elements /// # Finding elements
/// In the example below, we create a custom page header that displays the text /// In the example below, we create a custom page header that displays the text
/// "Typst Academy" in small capitals and the current section title. On the /// "Typst Academy" in small capitals and the current section title. On the
/// first page, the section title is omitted because the header is before the /// first page, the section title is omitted because the header is before the
/// first section heading. /// first section heading.
/// ///
/// To realize this layout, we call `locate` and then query for all headings /// To realize this layout, we open a `context` and then query for all headings
/// after the current location. The function we pass to locate is called twice /// after the [current location]($here). The code within the context block
/// in this case: Once per page. /// runs twice: Once per page.
/// ///
/// - On the first page the query for all headings before the current location /// - On the first page the query for all headings before the current location
/// yields an empty array: There are no previous headings. We check for this /// yields an empty array: There are no previous headings. We check for this
@ -46,7 +43,7 @@ use crate::introspection::Location;
/// let academy = smallcaps[ /// let academy = smallcaps[
/// Typst Academy /// Typst Academy
/// ] /// ]
/// if elems == () { /// if elems.len() == 0 {
/// align(right, academy) /// align(right, academy)
/// } else { /// } else {
/// let body = elems.last().body /// let body = elems.last().body
@ -64,6 +61,9 @@ use crate::introspection::Location;
/// #lorem(15) /// #lorem(15)
/// ``` /// ```
/// ///
/// You can get the location of the elements returned by `query` with
/// [`location`]($content.location).
///
/// # A word of caution { #caution } /// # A word of caution { #caution }
/// To resolve all your queries, Typst evaluates and layouts parts of the /// To resolve all your queries, Typst evaluates and layouts parts of the
/// document multiple times. However, there is no guarantee that your queries /// document multiple times. However, there is no guarantee that your queries
@ -80,7 +80,7 @@ use crate::introspection::Location;
/// ///
/// In general, you should try not to write queries that affect themselves. The /// In general, you should try not to write queries that affect themselves. The
/// same words of caution also apply to other introspection features like /// same words of caution also apply to other introspection features like
/// [counters]($counter) and [state]($state). /// [counters]($counter) and [state].
/// ///
/// ```example /// ```example
/// = Real /// = Real
@ -95,7 +95,7 @@ use crate::introspection::Location;
/// You can also perform queries from the command line with the `typst query` /// You can also perform queries from the command line with the `typst query`
/// command. This command executes an arbitrary query on the document and /// command. This command executes an arbitrary query on the document and
/// returns the resulting elements in serialized form. Consider the following /// returns the resulting elements in serialized form. Consider the following
/// `example.typ` file which contains some invisible [metadata]($metadata): /// `example.typ` file which contains some invisible [metadata]:
/// ///
/// ```typ /// ```typ
/// #metadata("This is a note") <note> /// #metadata("This is a note") <note>

View File

@ -24,7 +24,7 @@ use crate::text::TextElem;
/// ``` /// ```
#[elem(Show)] #[elem(Show)]
pub struct AlignElem { pub struct AlignElem {
/// The [alignment]($alignment) along both axes. /// The [alignment] along both axes.
/// ///
/// ```example /// ```example
/// #set page(height: 6cm) /// #set page(height: 6cm)
@ -56,7 +56,7 @@ impl Show for Packed<AlignElem> {
} }
} }
/// Where to [align]($align) something along an axis. /// Where to [align] something along an axis.
/// ///
/// Possible values are: /// Possible values are:
/// - `start`: Aligns at the [start]($direction.start) of the [text /// - `start`: Aligns at the [start]($direction.start) of the [text

View File

@ -13,7 +13,7 @@ use crate::util::{Numeric, Scalar};
/// Each fractionally sized element gets space based on the ratio of its /// Each fractionally sized element gets space based on the ratio of its
/// fraction to the sum of all fractions. /// fraction to the sum of all fractions.
/// ///
/// For more details, also see the [h]($h) and [v]($v) functions and the /// For more details, also see the [h] and [v] functions and the
/// [grid function]($grid). /// [grid function]($grid).
/// ///
/// # Example /// # Example

View File

@ -11,7 +11,7 @@ use crate::syntax::Span;
/// (width and height). /// (width and height).
/// ///
/// The given function must accept a single parameter, `size`, which is a /// The given function must accept a single parameter, `size`, which is a
/// dictionary with keys `width` and `height`, both of type [`length`]($length). /// dictionary with keys `width` and `height`, both of type [`length`.
/// ///
/// ```example /// ```example
/// #let text = lorem(30) /// #let text = lorem(30)
@ -31,9 +31,8 @@ use crate::syntax::Span;
/// page it receives the page's dimensions minus its margins. This is mostly /// page it receives the page's dimensions minus its margins. This is mostly
/// useful in combination with [measurement]($measure). /// useful in combination with [measurement]($measure).
/// ///
/// You can also use this function to resolve [`ratio`]($ratio) to fixed /// You can also use this function to resolve [`ratio`] to fixed lengths. This
/// lengths. This might come in handy if you're building your own layout /// might come in handy if you're building your own layout abstractions.
/// abstractions.
/// ///
/// ```example /// ```example
/// #layout(size => { /// #layout(size => {
@ -51,8 +50,8 @@ pub fn layout(
/// A function to call with the outer container's size. Its return value is /// A function to call with the outer container's size. Its return value is
/// displayed in the document. /// displayed in the document.
/// ///
/// The container's size is given as a [dictionary]($dictionary) with the /// The container's size is given as a [dictionary] with the keys `width`
/// keys `width` and `height`. /// and `height`.
/// ///
/// This function is called once for each time the content returned by /// This function is called once for each time the content returned by
/// `layout` appears in the document. That makes it possible to generate /// `layout` appears in the document. That makes it possible to generate

View File

@ -37,7 +37,7 @@ use crate::util::Numeric;
/// # Fields /// # Fields
/// - `abs`: A length with just the absolute component of the current length /// - `abs`: A length with just the absolute component of the current length
/// (that is, excluding the `em` component). /// (that is, excluding the `em` component).
/// - `em`: The amount of `em` units in this length, as a [float]($float). /// - `em`: The amount of `em` units in this length, as a [float].
#[ty(scope, cast)] #[ty(scope, cast)]
#[derive(Default, Copy, Clone, Eq, PartialEq, Hash)] #[derive(Default, Copy, Clone, Eq, PartialEq, Hash)]
pub struct Length { pub struct Length {

View File

@ -10,12 +10,12 @@ use crate::syntax::Span;
/// that an infinite space is assumed, therefore the measured height/width may /// that an infinite space is assumed, therefore the measured height/width may
/// not necessarily match the final height/width of the measured content. If you /// not necessarily match the final height/width of the measured content. If you
/// want to measure in the current layout dimensions, you can combine `measure` /// want to measure in the current layout dimensions, you can combine `measure`
/// and [`layout`]($layout). /// and [`layout`].
/// ///
/// # Example /// # Example
/// The same content can have a different size depending on the styles that /// The same content can have a different size depending on the [context] that
/// are active when it is layouted. For example, in the example below /// it is placed into. For example, in the example below `[#content]` is of
/// `[#content]` is of course bigger when we increase the font size. /// course bigger when we increase the font size.
/// ///
/// ```example /// ```example
/// #let content = [Hello!] /// #let content = [Hello!]
@ -24,9 +24,7 @@ use crate::syntax::Span;
/// #content /// #content
/// ``` /// ```
/// ///
/// To do a meaningful measurement, you therefore first need to retrieve the /// For this reason, you can only measure when context is available.
/// active styles with the [`style`]($style) function. You can then pass them to
/// the `measure` function.
/// ///
/// ```example /// ```example
/// #let thing(body) = context { /// #let thing(body) = context {
@ -39,7 +37,7 @@ use crate::syntax::Span;
/// ``` /// ```
/// ///
/// The measure function returns a dictionary with the entries `width` and /// The measure function returns a dictionary with the entries `width` and
/// `height`, both of type [`length`]($length). /// `height`, both of type [`length`].
#[func(contextual)] #[func(contextual)]
pub fn measure( pub fn measure(
/// The engine. /// The engine.
@ -50,7 +48,8 @@ pub fn measure(
span: Span, span: Span,
/// The content whose size to measure. /// The content whose size to measure.
content: Content, content: Content,
/// The styles with which to layout the content. /// _Compatibility:_ This argument only exists for compatibility with
/// Typst 0.10 and lower and shouldn't be used anymore.
#[default] #[default]
styles: Option<Styles>, styles: Option<Styles>,
) -> SourceResult<Dict> { ) -> SourceResult<Dict> {

View File

@ -10,9 +10,9 @@ use crate::util::Numeric;
/// A length in relation to some known length. /// A length in relation to some known length.
/// ///
/// This type is a combination of a [length]($length) with a [ratio]($ratio). It /// This type is a combination of a [length] with a [ratio]. It results from
/// results from addition and subtraction of a length and a ratio. Wherever a /// addition and subtraction of a length and a ratio. Wherever a relative length
/// relative length is expected, you can also use a bare length or ratio. /// is expected, you can also use a bare length or ratio.
/// ///
/// # Example /// # Example
/// ```example /// ```example

View File

@ -11,7 +11,7 @@ use crate::World;
/// ///
/// By default, the file will be read as UTF-8 and returned as a [string]($str). /// By default, the file will be read as UTF-8 and returned as a [string]($str).
/// ///
/// If you specify `{encoding: none}`, this returns raw [bytes]($bytes) instead. /// If you specify `{encoding: none}`, this returns raw [bytes] instead.
/// ///
/// # Example /// # Example
/// ```example /// ```example

View File

@ -10,8 +10,8 @@ use crate::text::{Lang, Region, TextElem};
/// Cite a work from the bibliography. /// Cite a work from the bibliography.
/// ///
/// Before you starting citing, you need to add a [bibliography]($bibliography) /// Before you starting citing, you need to add a [bibliography] somewhere in
/// somewhere in your document. /// your document.
/// ///
/// # Example /// # Example
/// ```example /// ```example

View File

@ -103,7 +103,7 @@ use crate::visualize::ImageElem;
/// ``` /// ```
#[elem(scope, Locatable, Synthesize, Count, Show, ShowSet, Refable, Outlinable)] #[elem(scope, Locatable, Synthesize, Count, Show, ShowSet, Refable, Outlinable)]
pub struct FigureElem { pub struct FigureElem {
/// The content of the figure. Often, an [image]($image). /// The content of the figure. Often, an [image].
#[required] #[required]
pub body: Content, pub body: Content,
@ -143,12 +143,12 @@ pub struct FigureElem {
/// If set to `{auto}`, the figure will try to automatically determine its /// If set to `{auto}`, the figure will try to automatically determine its
/// kind based on the type of its body. Automatically detected kinds are /// kind based on the type of its body. Automatically detected kinds are
/// [tables]($table) and [code]($raw). In other cases, the inferred kind is /// [tables]($table) and [code]($raw). In other cases, the inferred kind is
/// that of an [image]($image). /// that of an [image].
/// ///
/// Setting this to something other than `{auto}` will override the /// Setting this to something other than `{auto}` will override the
/// automatic detection. This can be useful if /// automatic detection. This can be useful if
/// - you wish to create a custom figure type that is not an /// - you wish to create a custom figure type that is not an
/// [image]($image), a [table]($table) or [code]($raw), /// [image], a [table] or [code]($raw),
/// - you want to force the figure to use a specific counter regardless of /// - you want to force the figure to use a specific counter regardless of
/// its content. /// its content.
/// ///
@ -199,7 +199,7 @@ pub struct FigureElem {
#[default(Em::new(0.65).into())] #[default(Em::new(0.65).into())]
pub gap: Length, pub gap: Length,
/// Whether the figure should appear in an [`outline`]($outline) of figures. /// Whether the figure should appear in an [`outline`] of figures.
#[default(true)] #[default(true)]
pub outlined: bool, pub outlined: bool,

View File

@ -23,9 +23,9 @@ use crate::visualize::{LineElem, Stroke};
/// ///
/// To customize the appearance of the entry in the footnote listing, see /// To customize the appearance of the entry in the footnote listing, see
/// [`footnote.entry`]($footnote.entry). The footnote itself is realized as a /// [`footnote.entry`]($footnote.entry). The footnote itself is realized as a
/// normal superscript, so you can use a set rule on the [`super`]($super) /// normal superscript, so you can use a set rule on the [`super`] function to
/// function to customize it. You can also apply a show rule to customize /// customize it. You can also apply a show rule to customize only the footnote
/// only the footnote marker (superscript number) in the running text. /// marker (superscript number) in the running text.
/// ///
/// # Example /// # Example
/// ```example /// ```example
@ -56,8 +56,8 @@ pub struct FootnoteElem {
/// ///
/// By default, the footnote numbering continues throughout your document. /// By default, the footnote numbering continues throughout your document.
/// If you prefer per-page footnote numbering, you can reset the footnote /// If you prefer per-page footnote numbering, you can reset the footnote
/// [counter]($counter) in the page [header]($page.header). In the future, /// [counter] in the page [header]($page.header). In the future, there might
/// there might be a simpler way to achieve this. /// be a simpler way to achieve this.
/// ///
/// ```example /// ```example
/// #set footnote(numbering: "*") /// #set footnote(numbering: "*")

View File

@ -25,8 +25,8 @@ use crate::util::{option_eq, NonZeroExt};
/// [numbering pattern or function]($numbering). /// [numbering pattern or function]($numbering).
/// ///
/// Independently of the numbering, Typst can also automatically generate an /// Independently of the numbering, Typst can also automatically generate an
/// [outline]($outline) of all headings for you. To exclude one or more headings /// [outline] of all headings for you. To exclude one or more headings from this
/// from this outline, you can set the `outlined` parameter to `{false}`. /// outline, you can set the `outlined` parameter to `{false}`.
/// ///
/// # Example /// # Example
/// ```example /// ```example
@ -122,7 +122,7 @@ pub struct HeadingElem {
/// ``` /// ```
pub supplement: Smart<Option<Supplement>>, pub supplement: Smart<Option<Supplement>>,
/// Whether the heading should appear in the [outline]($outline). /// Whether the heading should appear in the [outline].
/// ///
/// Note that this property, if set to `{true}`, ensures the heading is also /// Note that this property, if set to `{true}`, ensures the heading is also
/// shown as a bookmark in the exported PDF's outline (when exporting to /// shown as a bookmark in the exported PDF's outline (when exporting to
@ -146,9 +146,9 @@ pub struct HeadingElem {
/// ///
/// The default value of `{auto}` indicates that the heading will only /// The default value of `{auto}` indicates that the heading will only
/// appear in the exported PDF's outline if its `outlined` property is set /// appear in the exported PDF's outline if its `outlined` property is set
/// to `{true}`, that is, if it would also be listed in Typst's /// to `{true}`, that is, if it would also be listed in Typst's [outline].
/// [outline]($outline). Setting this property to either `{true}` (bookmark) /// Setting this property to either `{true}` (bookmark) or `{false}` (don't
/// or `{false}` (don't bookmark) bypasses that behaviour. /// bookmark) bypasses that behaviour.
/// ///
/// ```example /// ```example
/// #heading[Normal heading] /// #heading[Normal heading]

View File

@ -40,16 +40,16 @@ pub struct LinkElem {
/// ///
/// - To link to another part of the document, `dest` can take one of three /// - To link to another part of the document, `dest` can take one of three
/// forms: /// forms:
/// - A [label]($label) attached to an element. If you also want automatic /// - A [label] attached to an element. If you also want automatic text
/// text for the link based on the element, consider using a /// for the link based on the element, consider using a
/// [reference]($ref) instead. /// [reference]($ref) instead.
/// ///
/// - A [location]($locate) resulting from a [`locate`]($locate) call or /// - A [`location`] (typically retrieved from [`here`], [`locate`] or
/// [`query`]($query). /// [`query`]).
/// ///
/// - A dictionary with a `page` key of type [integer]($int) and `x` and /// - A dictionary with a `page` key of type [integer]($int) and `x` and
/// `y` coordinates of type [length]($length). Pages are counted from /// `y` coordinates of type [length]. Pages are counted from one, and
/// one, and the coordinates are relative to the page's top left corner. /// the coordinates are relative to the page's top left corner.
/// ///
/// ```example /// ```example
/// = Introduction <intro> /// = Introduction <intro>

View File

@ -465,9 +465,9 @@ pub struct OutlineEntry {
/// located in. When `{none}`, empty space is inserted in that gap instead. /// located in. When `{none}`, empty space is inserted in that gap instead.
/// ///
/// Note that, when using show rules to override outline entries, it is /// Note that, when using show rules to override outline entries, it is
/// recommended to wrap the filling content in a [`box`]($box) with /// recommended to wrap the filling content in a [`box`] with fractional
/// fractional width. For example, `{box(width: 1fr, repeat[-])}` would show /// width. For example, `{box(width: 1fr, repeat[-])}` would show precisely
/// precisely as many `-` characters as necessary to fill a particular gap. /// as many `-` characters as necessary to fill a particular gap.
#[required] #[required]
pub fill: Option<Content>, pub fill: Option<Content>,

View File

@ -47,8 +47,8 @@ pub struct ParElem {
/// [text function's `hyphenate` property]($text.hyphenate) is set to /// [text function's `hyphenate` property]($text.hyphenate) is set to
/// `{auto}` and the current language is known. /// `{auto}` and the current language is known.
/// ///
/// Note that the current [alignment]($align) still has an effect on the /// Note that the current [alignment]($align.alignment) still has an effect
/// placement of the last line except if it ends with a /// on the placement of the last line except if it ends with a
/// [justified line break]($linebreak.justify). /// [justified line break]($linebreak.justify).
#[ghost] #[ghost]
#[default(false)] #[default(false)]
@ -85,8 +85,8 @@ pub struct ParElem {
/// ///
/// By typographic convention, paragraph breaks are indicated either by some /// By typographic convention, paragraph breaks are indicated either by some
/// space between paragraphs or by indented first lines. Consider reducing /// space between paragraphs or by indented first lines. Consider reducing
/// the [paragraph spacing]($block.spacing) to the [`leading`] when /// the [paragraph spacing]($block.spacing) to the [`leading`]($par.leading)
/// using this property (e.g. using /// when using this property (e.g. using
/// `[#show par: set block(spacing: 0.65em)]`). /// `[#show par: set block(spacing: 0.65em)]`).
#[ghost] #[ghost]
pub first_line_indent: Length, pub first_line_indent: Length,

View File

@ -63,8 +63,7 @@ pub struct QuoteElem {
/// Whether double quotes should be added around this quote. /// Whether double quotes should be added around this quote.
/// ///
/// The double quotes used are inferred from the `quotes` property on /// The double quotes used are inferred from the `quotes` property on
/// [smartquote]($smartquote), which is affected by the `lang` property on /// [smartquote], which is affected by the `lang` property on [text].
/// [text]($text).
/// ///
/// - `{true}`: Wrap this quote in double quotes. /// - `{true}`: Wrap this quote in double quotes.
/// - `{false}`: Do not wrap this quote in double quotes. /// - `{false}`: Do not wrap this quote in double quotes.

View File

@ -18,8 +18,7 @@ use crate::text::TextElem;
/// Produces a textual reference to a label. For example, a reference to a /// Produces a textual reference to a label. For example, a reference to a
/// heading will yield an appropriate string such as "Section 1" for a reference /// heading will yield an appropriate string such as "Section 1" for a reference
/// to the first heading. The references are also links to the respective /// to the first heading. The references are also links to the respective
/// element. Reference syntax can also be used to [cite]($cite) from a /// element. Reference syntax can also be used to [cite] from a bibliography.
/// bibliography.
/// ///
/// Referenceable elements include [headings]($heading), [figures]($figure), /// Referenceable elements include [headings]($heading), [figures]($figure),
/// [equations]($math.equation), and [footnotes]($footnote). To create a custom /// [equations]($math.equation), and [footnotes]($footnote). To create a custom
@ -28,7 +27,7 @@ use crate::text::TextElem;
/// might be a more direct way to define a custom referenceable element. /// might be a more direct way to define a custom referenceable element.
/// ///
/// If you just want to link to a labelled element and not get an automatic /// If you just want to link to a labelled element and not get an automatic
/// textual reference, consider using the [`link`]($link) function instead. /// textual reference, consider using the [`link`] function instead.
/// ///
/// # Example /// # Example
/// ```example /// ```example
@ -96,7 +95,7 @@ pub struct RefElem {
/// The target label that should be referenced. /// The target label that should be referenced.
/// ///
/// Can be a label that is defined in the document or an entry from the /// Can be a label that is defined in the document or an entry from the
/// [`bibliography`]($bibliography). /// [`bibliography`].
#[required] #[required]
pub target: Label, pub target: Label,

View File

@ -35,7 +35,7 @@ use crate::visualize::{Paint, Stroke};
/// more information. /// more information.
/// ///
/// To give a table a caption and make it [referenceable]($ref), put it into a /// To give a table a caption and make it [referenceable]($ref), put it into a
/// [figure]($figure). /// [figure].
/// ///
/// # Example /// # Example
/// ///
@ -165,7 +165,7 @@ pub struct TableElem {
#[borrowed] #[borrowed]
pub align: Celled<Smart<Alignment>>, pub align: Celled<Smart<Alignment>>,
/// How to [stroke]($stroke) the cells. /// How to [stroke] the cells.
/// ///
/// Strokes can be disabled by setting this to `{none}`. /// Strokes can be disabled by setting this to `{none}`.
/// ///

View File

@ -22,7 +22,7 @@ use crate::visualize::{styled_rect, Color, FixedStroke, Geometry, Paint, Stroke}
/// ``` /// ```
#[elem(Show)] #[elem(Show)]
pub struct UnderlineElem { pub struct UnderlineElem {
/// How to [stroke]($stroke) the line. /// How to [stroke] the line.
/// ///
/// If set to `{auto}`, takes on the text's color and a thickness defined in /// If set to `{auto}`, takes on the text's color and a thickness defined in
/// the current font. /// the current font.
@ -108,7 +108,7 @@ impl Show for Packed<UnderlineElem> {
/// ``` /// ```
#[elem(Show)] #[elem(Show)]
pub struct OverlineElem { pub struct OverlineElem {
/// How to [stroke]($stroke) the line. /// How to [stroke] the line.
/// ///
/// If set to `{auto}`, takes on the text's color and a thickness defined in /// If set to `{auto}`, takes on the text's color and a thickness defined in
/// the current font. /// the current font.
@ -200,7 +200,7 @@ impl Show for Packed<OverlineElem> {
/// ``` /// ```
#[elem(title = "Strikethrough", Show)] #[elem(title = "Strikethrough", Show)]
pub struct StrikeElem { pub struct StrikeElem {
/// How to [stroke]($stroke) the line. /// How to [stroke] the line.
/// ///
/// If set to `{auto}`, takes on the text's color and a thickness defined in /// If set to `{auto}`, takes on the text's color and a thickness defined in
/// the current font. /// the current font.

View File

@ -155,9 +155,9 @@ pub struct TextElem {
/// available either in an italic or oblique style, the difference between /// available either in an italic or oblique style, the difference between
/// italic and oblique style is rarely observable. /// italic and oblique style is rarely observable.
/// ///
/// If you want to emphasize your text, you should do so using the /// If you want to emphasize your text, you should do so using the [emph]
/// [emph]($emph) function instead. This makes it easy to adapt the style /// function instead. This makes it easy to adapt the style later if you
/// later if you change your mind about how to signify the emphasis. /// change your mind about how to signify the emphasis.
/// ///
/// ```example /// ```example
/// #text(font: "Linux Libertine", style: "italic")[Italic] /// #text(font: "Linux Libertine", style: "italic")[Italic]
@ -172,9 +172,8 @@ pub struct TextElem {
/// that is closest in weight. /// that is closest in weight.
/// ///
/// If you want to strongly emphasize your text, you should do so using the /// If you want to strongly emphasize your text, you should do so using the
/// [strong]($strong) function instead. This makes it easy to adapt the /// [strong] function instead. This makes it easy to adapt the style later
/// style later if you change your mind about how to signify the strong /// if you change your mind about how to signify the strong emphasis.
/// emphasis.
/// ///
/// ```example /// ```example
/// #set text(font: "IBM Plex Sans") /// #set text(font: "IBM Plex Sans")

View File

@ -211,10 +211,9 @@ pub struct RawElem {
/// Applying a theme only affects the color of specifically highlighted /// Applying a theme only affects the color of specifically highlighted
/// text. It does not consider the theme's foreground and background /// text. It does not consider the theme's foreground and background
/// properties, so that you retain control over the color of raw text. You /// properties, so that you retain control over the color of raw text. You
/// can apply the foreground color yourself with the [`text`]($text) /// can apply the foreground color yourself with the [`text`] function and
/// function and the background with a [filled block]($block.fill). You /// the background with a [filled block]($block.fill). You could also use
/// could also use the [`xml`]($xml) function to extract these properties /// the [`xml`] function to extract these properties from the theme.
/// from the theme.
/// ///
/// ````example /// ````example
/// #set raw(theme: "halcyon.tmTheme") /// #set raw(theme: "halcyon.tmTheme")
@ -542,7 +541,7 @@ cast! {
/// A highlighted line of raw text. /// A highlighted line of raw text.
/// ///
/// This is a helper element that is synthesized by [`raw`]($raw) elements. /// This is a helper element that is synthesized by [`raw`] elements.
/// ///
/// It allows you to access various properties of the line, such as the line /// It allows you to access various properties of the line, such as the line
/// number, the raw non-highlighted text, the highlighted text, and whether it /// number, the raw non-highlighted text, the highlighted text, and whether it

View File

@ -67,10 +67,9 @@ pub struct SmartQuoteElem {
/// - [string]($str): a string consisting of two characters containing the /// - [string]($str): a string consisting of two characters containing the
/// opening and closing double quotes (characters here refer to Unicode /// opening and closing double quotes (characters here refer to Unicode
/// grapheme clusters) /// grapheme clusters)
/// - [array]($array): an array containing the opening and closing double /// - [array]: an array containing the opening and closing double quotes
/// quotes /// - [dictionary]: an array containing the double and single quotes, each
/// - [dictionary]($dictionary): an array containing the double and single /// specified as either `{auto}`, string, or array
/// quotes, each specified as either `{auto}`, string, or array
/// ///
/// ```example /// ```example
/// #set text(lang: "de") /// #set text(lang: "de")

View File

@ -290,12 +290,12 @@ impl Color {
/// ///
/// A linear Oklab color is represented internally by an array of four /// A linear Oklab color is represented internally by an array of four
/// components: /// components:
/// - lightness ([`ratio`]($ratio)) /// - lightness ([`ratio`])
/// - a ([`float`]($float) or [`ratio`]($ratio). /// - a ([`float`] or [`ratio`].
/// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`) /// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`)
/// - b ([`float`]($float) or [`ratio`]($ratio). /// - b ([`float`] or [`ratio`].
/// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`) /// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`)
/// - alpha ([`ratio`]($ratio)) /// - alpha ([`ratio`])
/// ///
/// These components are also available using the /// These components are also available using the
/// [`components`]($color.components) method. /// [`components`]($color.components) method.
@ -349,11 +349,11 @@ impl Color {
/// ///
/// A linear Oklch color is represented internally by an array of four /// A linear Oklch color is represented internally by an array of four
/// components: /// components:
/// - lightness ([`ratio`]($ratio)) /// - lightness ([`ratio`])
/// - chroma ([`float`]($float) or [`ratio`]($ratio). /// - chroma ([`float`] or [`ratio`].
/// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`) /// Ratios are relative to `{0.4}`; meaning `{50%}` is equal to `{0.2}`)
/// - hue ([`angle`]($angle)) /// - hue ([`angle`])
/// - alpha ([`ratio`]($ratio)) /// - alpha ([`ratio`])
/// ///
/// These components are also available using the /// These components are also available using the
/// [`components`]($color.components) method. /// [`components`]($color.components) method.
@ -412,10 +412,10 @@ impl Color {
/// ///
/// A linear RGB(A) color is represented internally by an array of four /// A linear RGB(A) color is represented internally by an array of four
/// components: /// components:
/// - red ([`ratio`]($ratio)) /// - red ([`ratio`])
/// - green ([`ratio`]($ratio)) /// - green ([`ratio`])
/// - blue ([`ratio`]($ratio)) /// - blue ([`ratio`])
/// - alpha ([`ratio`]($ratio)) /// - alpha ([`ratio`])
/// ///
/// These components are also available using the /// These components are also available using the
/// [`components`]($color.components) method. /// [`components`]($color.components) method.
@ -469,10 +469,10 @@ impl Color {
/// The color is specified in the sRGB color space. /// The color is specified in the sRGB color space.
/// ///
/// An RGB(A) color is represented internally by an array of four components: /// An RGB(A) color is represented internally by an array of four components:
/// - red ([`ratio`]($ratio)) /// - red ([`ratio`])
/// - green ([`ratio`]($ratio)) /// - green ([`ratio`])
/// - blue ([`ratio`]($ratio)) /// - blue ([`ratio`])
/// - alpha ([`ratio`]($ratio)) /// - alpha ([`ratio`])
/// ///
/// These components are also available using the [`components`]($color.components) /// These components are also available using the [`components`]($color.components)
/// method. /// method.
@ -544,10 +544,10 @@ impl Color {
/// the color. /// the color.
/// ///
/// A CMYK color is represented internally by an array of four components: /// A CMYK color is represented internally by an array of four components:
/// - cyan ([`ratio`]($ratio)) /// - cyan ([`ratio`])
/// - magenta ([`ratio`]($ratio)) /// - magenta ([`ratio`])
/// - yellow ([`ratio`]($ratio)) /// - yellow ([`ratio`])
/// - key ([`ratio`]($ratio)) /// - key ([`ratio`])
/// ///
/// These components are also available using the /// These components are also available using the
/// [`components`]($color.components) method. /// [`components`]($color.components) method.
@ -603,10 +603,10 @@ impl Color {
/// while keeping perceived hue. /// while keeping perceived hue.
/// ///
/// An HSL color is represented internally by an array of four components: /// An HSL color is represented internally by an array of four components:
/// - hue ([`angle`]($angle)) /// - hue ([`angle`])
/// - saturation ([`ratio`]($ratio)) /// - saturation ([`ratio`])
/// - lightness ([`ratio`]($ratio)) /// - lightness ([`ratio`])
/// - alpha ([`ratio`]($ratio)) /// - alpha ([`ratio`])
/// ///
/// These components are also available using the /// These components are also available using the
/// [`components`]($color.components) method. /// [`components`]($color.components) method.
@ -662,10 +662,10 @@ impl Color {
/// while keeping perceived hue. /// while keeping perceived hue.
/// ///
/// An HSV color is represented internally by an array of four components: /// An HSV color is represented internally by an array of four components:
/// - hue ([`angle`]($angle)) /// - hue ([`angle`])
/// - saturation ([`ratio`]($ratio)) /// - saturation ([`ratio`])
/// - value ([`ratio`]($ratio)) /// - value ([`ratio`])
/// - alpha ([`ratio`]($ratio)) /// - alpha ([`ratio`])
/// ///
/// These components are also available using the /// These components are also available using the
/// [`components`]($color.components) method. /// [`components`]($color.components) method.

View File

@ -82,11 +82,10 @@ use crate::visualize::{Color, ColorSpace, WeightedColor};
/// Typst determines the ancestor container as follows: /// Typst determines the ancestor container as follows:
/// - For shapes that are placed at the root/top level of the document, the /// - For shapes that are placed at the root/top level of the document, the
/// closest ancestor is the page itself. /// closest ancestor is the page itself.
/// - For other shapes, the ancestor is the innermost [`block`]($block) or /// - For other shapes, the ancestor is the innermost [`block`] or [`box`] that
/// [`box`]($box) that contains the shape. This includes the boxes and blocks /// contains the shape. This includes the boxes and blocks that are implicitly
/// that are implicitly created by show rules and elements. For example, a /// created by show rules and elements. For example, a [`rotate`] will not
/// [`rotate`]($rotate) will not affect the parent of a gradient, but a /// affect the parent of a gradient, but a [`grid`] will.
/// [`grid`]($grid) will.
/// ///
/// # Color spaces and interpolation /// # Color spaces and interpolation
/// Gradients can be interpolated in any color space. By default, gradients are /// Gradients can be interpolated in any color space. By default, gradients are
@ -708,9 +707,9 @@ impl Gradient {
/// Sample the gradient at a given position. /// Sample the gradient at a given position.
/// ///
/// The position is either a position along the gradient (a [ratio]($ratio) /// The position is either a position along the gradient (a [ratio] between
/// between `{0%}` and `{100%}`) or an [angle]($angle). Any value outside /// `{0%}` and `{100%}`) or an [angle]. Any value outside of this range will
/// of this range will be clamped. /// be clamped.
#[func] #[func]
pub fn sample( pub fn sample(
&self, &self,

View File

@ -41,7 +41,7 @@ pub struct LineElem {
/// respected if `end` is `none`. /// respected if `end` is `none`.
pub angle: Angle, pub angle: Angle,
/// How to [stroke]($stroke) the line. /// How to [stroke] the line.
/// ///
/// ```example /// ```example
/// #set line(length: 100%) /// #set line(length: 100%)

View File

@ -28,7 +28,7 @@ use crate::foundations::{category, Category, Scope};
/// ///
/// If you want to create more advanced drawings or plots, also have a look at /// If you want to create more advanced drawings or plots, also have a look at
/// the [CetZ](https://github.com/johannes-wolf/cetz) package as well as more /// the [CetZ](https://github.com/johannes-wolf/cetz) package as well as more
/// specialized [packages]($packages) for your use case. /// specialized [packages] for your use case.
#[category] #[category]
pub static VISUALIZE: Category; pub static VISUALIZE: Category;

View File

@ -37,7 +37,7 @@ pub struct PathElem {
/// rule](https://en.wikipedia.org/wiki/Nonzero-rule). /// rule](https://en.wikipedia.org/wiki/Nonzero-rule).
pub fill: Option<Paint>, pub fill: Option<Paint>,
/// How to [stroke]($stroke) the path. This can be: /// How to [stroke] the path. This can be:
/// ///
/// Can be set to `{none}` to disable the stroke or to `{auto}` for a /// Can be set to `{none}` to disable the stroke or to `{auto}` for a
/// stroke of `{1pt}` black if and if only if no fill is given. /// stroke of `{1pt}` black if and if only if no fill is given.
@ -56,8 +56,7 @@ pub struct PathElem {
/// ///
/// Each vertex can be defined in 3 ways: /// Each vertex can be defined in 3 ways:
/// ///
/// - A regular point, as given to the [`line`]($line) or /// - A regular point, as given to the [`line`] or [`polygon`] function.
/// [`polygon`]($polygon) function.
/// - An array of two points, the first being the vertex and the second /// - An array of two points, the first being the vertex and the second
/// being the control point. The control point is expressed relative to /// being the control point. The control point is expressed relative to
/// the vertex and is mirrored to get the second control point. The given /// the vertex and is mirrored to get the second control point. The given

View File

@ -90,11 +90,10 @@ use crate::World;
/// Typst determines the ancestor container as follows: /// Typst determines the ancestor container as follows:
/// - For shapes that are placed at the root/top level of the document, the /// - For shapes that are placed at the root/top level of the document, the
/// closest ancestor is the page itself. /// closest ancestor is the page itself.
/// - For other shapes, the ancestor is the innermost [`block`]($block) or /// - For other shapes, the ancestor is the innermost [`block`] or [`box`] that
/// [`box`]($box) that contains the shape. This includes the boxes and blocks /// contains the shape. This includes the boxes and blocks that are implicitly
/// that are implicitly created by show rules and elements. For example, a /// created by show rules and elements. For example, a [`rotate`] will not
/// [`rotate`]($rotate) will not affect the parent of a gradient, but a /// affect the parent of a gradient, but a [`grid`] will.
/// [`grid`]($grid) will.
#[ty(scope, cast)] #[ty(scope, cast)]
#[derive(Debug, Clone, Eq, PartialEq, Hash)] #[derive(Debug, Clone, Eq, PartialEq, Hash)]
pub struct Pattern(Arc<Repr>); pub struct Pattern(Arc<Repr>);

View File

@ -38,7 +38,7 @@ pub struct PolygonElem {
/// [non-zero winding rule](https://en.wikipedia.org/wiki/Nonzero-rule). /// [non-zero winding rule](https://en.wikipedia.org/wiki/Nonzero-rule).
pub fill: Option<Paint>, pub fill: Option<Paint>,
/// How to [stroke]($stroke) the polygon. This can be: /// How to [stroke] the polygon. This can be:
/// ///
/// Can be set to `{none}` to disable the stroke or to `{auto}` for a /// Can be set to `{none}` to disable the stroke or to `{auto}` for a
/// stroke of `{1pt}` black if and if only if no fill is given. /// stroke of `{1pt}` black if and if only if no fill is given.

View File

@ -47,7 +47,7 @@ pub struct RectElem {
/// - `{none}` to disable stroking /// - `{none}` to disable stroking
/// - `{auto}` for a stroke of `{1pt + black}` if and if only if no fill is /// - `{auto}` for a stroke of `{1pt + black}` if and if only if no fill is
/// given. /// given.
/// - Any kind of [stroke]($stroke) /// - Any kind of [stroke]
/// - A dictionary describing the stroke for each side inidvidually. The /// - A dictionary describing the stroke for each side inidvidually. The
/// dictionary can contain the following keys in order of precedence: /// dictionary can contain the following keys in order of precedence:
/// - `top`: The top stroke. /// - `top`: The top stroke.

View File

@ -39,10 +39,9 @@ use crate::visualize::{Color, Gradient, Paint, Pattern};
/// - A stroke combined from color and thickness using the `+` operator as in /// - A stroke combined from color and thickness using the `+` operator as in
/// `{2pt + red}`. /// `{2pt + red}`.
/// ///
/// For full control, you can also provide a [dictionary]($dictionary) or a /// For full control, you can also provide a [dictionary] or a `{stroke}` object
/// `{stroke}` object to any function that expects a stroke. The dictionary's /// to any function that expects a stroke. The dictionary's keys may include any
/// keys may include any of the parameters for the constructor function, shown /// of the parameters for the constructor function, shown below.
/// below.
/// ///
/// # Fields /// # Fields
/// On a stroke object, you can access any of the fields listed in the /// On a stroke object, you can access any of the fields listed in the
@ -139,11 +138,12 @@ impl Stroke {
/// - `{"dash-dotted"}` /// - `{"dash-dotted"}`
/// - `{"densely-dash-dotted"}` /// - `{"densely-dash-dotted"}`
/// - `{"loosely-dash-dotted"}` /// - `{"loosely-dash-dotted"}`
/// - An [array]($array) with alternating lengths for dashes and gaps. You can /// - An [array] with alternating lengths for dashes and gaps. You can
/// also use the string `{"dot"}` for a length equal to the line thickness. /// also use the string `{"dot"}` for a length equal to the line
/// - A [dictionary]($dictionary) with the keys `array` (same as the array /// thickness.
/// above), and `phase` (of type [length]($length)), which defines where in /// - A [dictionary] with the keys `array` (same as the array above),
/// the pattern to start drawing. /// and `phase` (of type [length]), which defines where in the pattern
/// to start drawing.
/// ///
/// If set to `{auto}`, the value is inherited, defaulting to `{none}`. /// If set to `{auto}`, the value is inherited, defaulting to `{none}`.
/// ///

View File

@ -53,8 +53,8 @@ description: |
Chinese, French, and Russian Chinese, French, and Russian
- Changed default [figure supplement]($figure.supplement) for Russian to - Changed default [figure supplement]($figure.supplement) for Russian to
short form short form
- Fixed [CJK-Latin-spacing]($text.cjk-latin-spacing) before line breaks - Fixed [CJK-Latin-spacing]($text.cjk-latin-spacing) before line breaks and in
and in [`locate`]($locate) calls [`locate`] calls
- Fixed line breaking at the end of links - Fixed line breaking at the end of links
- Math - Math
@ -68,13 +68,13 @@ description: |
- Scripting - Scripting
- Any non-identifier dictionary key is now interpreted as an expression: For - Any non-identifier dictionary key is now interpreted as an expression: For
instance, `{((key): value)}` will create a dictionary with a dynamic key instance, `{((key): value)}` will create a dictionary with a dynamic key
- The [`stroke`]($stroke) type now has a constructor that converts a value to - The [`stroke`] type now has a constructor that converts a value to a stroke
a stroke or creates one from its parts or creates one from its parts
- Added constructor for [`arguments`]($arguments) type - Added constructor for [`arguments`] type
- Added [`calc.div-euclid`]($calc.div-euclid) and - Added [`calc.div-euclid`]($calc.div-euclid) and
[`calc.rem-euclid`]($calc.rem-euclid) functions [`calc.rem-euclid`]($calc.rem-euclid) functions
- Fixed equality of [`arguments`]($arguments) - Fixed equality of [`arguments`]
- Fixed [`repr`]($repr) of [`cmyk`]($color.cmyk) colors - Fixed [`repr`]of [`cmyk`]($color.cmyk) colors
- Fixed crashes with provided elements like figure captions, outline entries, - Fixed crashes with provided elements like figure captions, outline entries,
and footnote entries and footnote entries
@ -117,10 +117,10 @@ description: |
of just a string of just a string
- The [`number-align`]($enum.number-align) parameter on numbered lists now - The [`number-align`]($enum.number-align) parameter on numbered lists now
also accepts vertical alignments also accepts vertical alignments
- Fixed selectors on [quote]($quote) elements - Fixed selectors on [quote] elements
- Fixed parsing of `[#return]` expression in markup - Fixed parsing of `[#return]` expression in markup
- Fixed bug where inline equations were displayed in equation outlines - Fixed bug where inline equations were displayed in equation outlines
- Fixed potential CRLF issue in [`raw`]($raw) blocks - Fixed potential CRLF issue in [`raw`] blocks
- Fixed a bug where Chinese numbering couldn't exceed the number 255 - Fixed a bug where Chinese numbering couldn't exceed the number 255
- Development - Development
@ -138,11 +138,11 @@ description: |
- Added new [`form`]($cite.form) argument to the `cite` function to produce - Added new [`form`]($cite.form) argument to the `cite` function to produce
different forms of citations (e.g. for producing a citation suitable for different forms of citations (e.g. for producing a citation suitable for
inclusion in prose) inclusion in prose)
- The [`cite`]($cite) function now takes only a single label/key instead of - The [`cite`] function now takes only a single label/key instead of allowing
allowing multiple. Adjacent citations are merged and formatted according to multiple. Adjacent citations are merged and formatted according to the
the citation style's rules automatically. This works both with the reference citation style's rules automatically. This works both with the reference
syntax and explicit calls to the `cite` function. (**Breaking change**) syntax and explicit calls to the `cite` function. (**Breaking change**)
- The `cite` function now takes a [label]($label) instead of a string - The `cite` function now takes a [label] instead of a string
(**Breaking change**) (**Breaking change**)
- Added [`full`]($bibliography.full) argument to bibliography function to - Added [`full`]($bibliography.full) argument to bibliography function to
print the full bibliography even if not all works were cited print the full bibliography even if not all works were cited
@ -172,8 +172,8 @@ description: |
stroke widths stroke widths
- Added support for properly clipping [boxes]($box.clip) and - Added support for properly clipping [boxes]($box.clip) and
[blocks]($block.clip) with a border radius [blocks]($block.clip) with a border radius
- Added `background` parameter to [`overline`]($overline), - Added `background` parameter to [`overline`], [`underline`], and [`strike`]
[`underline`]($underline), and [`strike`]($strike) functions functions
- Fixed inaccurate color embedding in PDFs - Fixed inaccurate color embedding in PDFs
- Fixed ICC profile handling for images embedded in PDFs - Fixed ICC profile handling for images embedded in PDFs
@ -182,8 +182,8 @@ description: |
[spacing]($text.cjk-latin-spacing) between CJK and Latin text (enabled by [spacing]($text.cjk-latin-spacing) between CJK and Latin text (enabled by
default) default)
- Added support for automatic adjustment of more CJK punctuation - Added support for automatic adjustment of more CJK punctuation
- Added [`quote`]($quote) element for inserting inline and block quotes with - Added [`quote`] element for inserting inline and block quotes with optional
optional attributions attributions
- Added [`raw.line`]($raw.line) element for customizing the display of - Added [`raw.line`]($raw.line) element for customizing the display of
individual lines of raw text, e.g. to add line numbers while keeping proper individual lines of raw text, e.g. to add line numbers while keeping proper
syntax highlighting syntax highlighting
@ -212,8 +212,8 @@ description: |
- Fixed spacing around [placed]($place) elements - Fixed spacing around [placed]($place) elements
- Fixed coalescing of [`above`]($block.above) and [`below`]($block.below) - Fixed coalescing of [`above`]($block.above) and [`below`]($block.below)
spacing if given in em units and the font sizes differ spacing if given in em units and the font sizes differ
- Fixed handling of `extent` parameter of [`underline`]($underline), - Fixed handling of `extent` parameter of [`underline`], [`overline`], and
[`overline`]($overline), and [`strike`]($strike) functions [`strike`] functions
- Fixed crash for [floating placed elements]($place.float) with no specified - Fixed crash for [floating placed elements]($place.float) with no specified
vertical alignment vertical alignment
- Partially fixed a bug with citations in footnotes - Partially fixed a bug with citations in footnotes
@ -290,12 +290,11 @@ description: |
PNG or SVG export PNG or SVG export
- Miscellaneous Improvements - Miscellaneous Improvements
- Added [`version`]($version) type and `sys.version` constant specifying the - Added [`version`] type and `sys.version` constant specifying the current
current compiler version. Can be used to gracefully support multiple compiler version. Can be used to gracefully support multiple versions.
versions.
- The U+2212 MINUS SIGN is now used when displaying a numeric value, in the - The U+2212 MINUS SIGN is now used when displaying a numeric value, in the
[`repr`]($repr) of any numeric value and to replace a normal hyphen in text [`repr`] of any numeric value and to replace a normal hyphen in text mode
mode when before a digit. This improves, in particular, how negative integer when before a digit. This improves, in particular, how negative integer
values are displayed in math mode. values are displayed in math mode.
- Added support for specifying a default value instead of failing for - Added support for specifying a default value instead of failing for
`remove` function in [array]($array.remove) and `remove` function in [array]($array.remove) and
@ -329,9 +328,9 @@ description: |
- Plugins can be shipped as part of [packages]($scripting/#packages) - Plugins can be shipped as part of [packages]($scripting/#packages)
- Plugins work just the same in the web app - Plugins work just the same in the web app
- Types are now first-class values (**Breaking change**) - Types are now first-class values (**Breaking change**)
- A [type]($type) is now itself a value - A [type] is now itself a value
- Some types can be called like functions (those that have a constructor), - Some types can be called like functions (those that have a constructor),
e.g. [`int`]($int) and [`str`]($str) e.g. [`int`] and [`str`]
- Type checks are now of the form `{type(10) == int}` instead of the old - Type checks are now of the form `{type(10) == int}` instead of the old
`{type(10) == "integer"}`. [Compatibility]($type/#compatibility) with the `{type(10) == "integer"}`. [Compatibility]($type/#compatibility) with the
old way will remain for a while to give package authors time to upgrade, old way will remain for a while to give package authors time to upgrade,
@ -339,7 +338,7 @@ description: |
- Methods are now syntax sugar for calling a function scoped to a type, - Methods are now syntax sugar for calling a function scoped to a type,
meaning that `{"hello".len()}` is equivalent to `{str.len("hello")}` meaning that `{"hello".len()}` is equivalent to `{str.len("hello")}`
- Added support for [`import`]($scripting/#modules) renaming with `as` - Added support for [`import`]($scripting/#modules) renaming with `as`
- Added a [`duration`]($duration) type - Added a [`duration`] type
- Added support for [CBOR]($cbor) encoding and decoding - Added support for [CBOR]($cbor) encoding and decoding
- Added encoding and decoding functions from and to bytes for data formats: - Added encoding and decoding functions from and to bytes for data formats:
[`json.decode`]($json.decode), [`json.encode`]($json.encode), and similar [`json.decode`]($json.decode), [`json.encode`]($json.encode), and similar
@ -347,9 +346,9 @@ description: |
- Added [`array.intersperse`]($array.intersperse) function - Added [`array.intersperse`]($array.intersperse) function
- Added [`str.rev`]($str.rev) function - Added [`str.rev`]($str.rev) function
- Added `calc.tau` constant - Added `calc.tau` constant
- Made [bytes]($bytes) joinable and addable - Made [bytes] joinable and addable
- Made [`array.zip`]($array.zip) function variadic - Made [`array.zip`]($array.zip) function variadic
- Fixed bug with [`eval`]($eval) when the `mode` was set to `{"math"}` - Fixed bug with [`eval`] when the `mode` was set to `{"math"}`
- Fixed bug with [`ends-with`]($str.ends-with) function on strings - Fixed bug with [`ends-with`]($str.ends-with) function on strings
- Fixed bug with destructuring in combination with break, continue, and return - Fixed bug with destructuring in combination with break, continue, and return
- Fixed argument types of [hyperbolic functions]($calc.cosh), they don't allow - Fixed argument types of [hyperbolic functions]($calc.cosh), they don't allow
@ -365,11 +364,11 @@ description: |
[page numbering]($page.numbering) style in the PDF [page numbering]($page.numbering) style in the PDF
- Text and Layout - Text and Layout
- Added [`highlight`]($highlight) function for highlighting text with a - Added [`highlight`] function for highlighting text with a
background color background color
- Added [`polygon.regular`]($polygon.regular) function for drawing a regular - Added [`polygon.regular`]($polygon.regular) function for drawing a regular
polygon polygon
- Added support for tabs in [`raw`]($raw) elements alongside - Added support for tabs in [`raw`] elements alongside
[`tab-width`]($raw.tab-size) parameter [`tab-width`]($raw.tab-size) parameter
- The layout engine now tries to prevent "runts" (final lines consisting of - The layout engine now tries to prevent "runts" (final lines consisting of
just a single word) just a single word)
@ -514,18 +513,16 @@ description: |
- Added `inv` method to [2d alignments]($align.alignment) - Added `inv` method to [2d alignments]($align.alignment)
- Added `start` argument to [`enumerate`]($array.enumerate) method on arrays - Added `start` argument to [`enumerate`]($array.enumerate) method on arrays
- Added [`color.mix`]($color.mix) function - Added [`color.mix`]($color.mix) function
- Added `mode` and `scope` arguments to [`eval`]($eval) function - Added `mode` and `scope` arguments to [`eval`] function
- Added [`bytes`]($bytes) type for holding large byte buffers - Added [`bytes`] type for holding large byte buffers
- Added [`encoding`]($read.encoding) argument to read function to read a - Added [`encoding`]($read.encoding) argument to read function to read a
file as bytes instead of a string file as bytes instead of a string
- Added [`image.decode`]($image.decode) function for decoding an image - Added [`image.decode`]($image.decode) function for decoding an image
directly from a string or bytes directly from a string or bytes
- Added [`bytes`]($bytes) function for converting a string or an array of - Added [`bytes`] function for converting a string or an array of integers
integers to bytes to bytes
- Added [`array`]($array) function for converting bytes to an array of - Added [`array`] function for converting bytes to an array of integers
integers - Added support for converting bytes to a string with the [`str`] function
- Added support for converting bytes to a string with the [`str`]($str)
function
- Tooling and Diagnostics - Tooling and Diagnostics
- Added support for compiler warnings - Added support for compiler warnings
@ -560,15 +557,15 @@ description: |
whether a heading becomes part of the PDF outline whether a heading becomes part of the PDF outline
- Added [`caption-pos`]($figure.caption.position) argument to control the - Added [`caption-pos`]($figure.caption.position) argument to control the
position of a figure's caption position of a figure's caption
- Added [`metadata`]($metadata) function for exposing an arbitrary value to - Added [`metadata`] function for exposing an arbitrary value to the
the introspection system introspection system
- Fixed that a [`state`]($state) was identified by the pair `(key, init)` - Fixed that a [`state`] was identified by the pair `(key, init)` instead of
instead of just its `key` just its `key`
- Improved indent logic of [enumerations]($enum). Instead of requiring at - Improved indent logic of [enumerations]($enum). Instead of requiring at
least as much indent as the end of the marker, they now require only one least as much indent as the end of the marker, they now require only one
more space indent than the start of the marker. As a result, even long more space indent than the start of the marker. As a result, even long
markers like `12.` work with just 2 spaces of indent. markers like `12.` work with just 2 spaces of indent.
- Fixed bug with indent logic of [`raw`]($raw) blocks - Fixed bug with indent logic of [`raw`] blocks
- Fixed a parsing bug with dictionaries - Fixed a parsing bug with dictionaries
- Development - Development
@ -626,10 +623,10 @@ description: |
- Added [`outline.entry`]($outline.entry) to customize outline entries with - Added [`outline.entry`]($outline.entry) to customize outline entries with
show rules show rules
- Added some hints for error messages - Added some hints for error messages
- Added some missing syntaxes for [`raw`]($raw) highlighting - Added some missing syntaxes for [`raw`] highlighting
- Improved rendering of rotated images in PNG export and web app - Improved rendering of rotated images in PNG export and web app
- Made [footnotes]($footnote) reusable and referenceable - Made [footnotes]($footnote) reusable and referenceable
- Fixed bug with citations and bibliographies in [`locate`]($locate) - Fixed bug with citations and bibliographies in [`locate`]
- Fixed inconsistent tense in documentation - Fixed inconsistent tense in documentation
- Development - Development
@ -641,8 +638,8 @@ description: |
## Version 0.5.0 (June 9, 2023) { #v0.5.0 } ## Version 0.5.0 (June 9, 2023) { #v0.5.0 }
- Text and Layout - Text and Layout
- Added [`raw`]($raw) syntax highlighting for many more languages - Added [`raw`] syntax highlighting for many more languages
- Added support for Korean [numbering]($numbering) - Added support for Korean [numbering]
- Added basic i18n for a few more languages (NL, SV, DA) - Added basic i18n for a few more languages (NL, SV, DA)
- Improved line breaking for East Asian languages - Improved line breaking for East Asian languages
- Expanded functionality of outline [`indent`]($outline.indent) property - Expanded functionality of outline [`indent`]($outline.indent) property
@ -651,7 +648,7 @@ description: |
- Fixed bug with handling of footnotes in lists, tables, and figures - Fixed bug with handling of footnotes in lists, tables, and figures
- Fixed a bug with CJK punctuation adjustment - Fixed a bug with CJK punctuation adjustment
- Fixed a crash with rounded rectangles - Fixed a crash with rounded rectangles
- Fixed alignment of [`line`]($line) elements - Fixed alignment of [`line`] elements
- Math - Math
- **Breaking change:** The syntax rules for mathematical - **Breaking change:** The syntax rules for mathematical
@ -668,12 +665,12 @@ description: |
- Fixed a crash in the [`attach`]($math.attach) function - Fixed a crash in the [`attach`]($math.attach) function
- Scripting - Scripting
- Added new [`datetime`]($datetime) type and - Added new [`datetime`] type and [`datetime.today`]($datetime.today) to
[`datetime.today`]($datetime.today) to retrieve the current date retrieve the current date
- Added [`str.from-unicode`]($str.from-unicode) and - Added [`str.from-unicode`]($str.from-unicode) and
[`str.to-unicode`]($str.to-unicode) functions [`str.to-unicode`]($str.to-unicode) functions
- Added [`fields`]($content.fields) method on content - Added [`fields`]($content.fields) method on content
- Added `base` parameter to [`str`]($str) function - Added `base` parameter to [`str`] function
- Added [`calc.exp`]($calc.exp) and [`calc.ln`]($calc.ln) - Added [`calc.exp`]($calc.exp) and [`calc.ln`]($calc.ln)
- Improved accuracy of [`calc.pow`]($calc.pow) and [`calc.log`]($calc.log) for - Improved accuracy of [`calc.pow`]($calc.pow) and [`calc.log`]($calc.log) for
specific bases specific bases
@ -695,7 +692,7 @@ description: |
- Improved error message for failed length comparisons - Improved error message for failed length comparisons
- Fixed a bug with images not showing up in Apple Preview - Fixed a bug with images not showing up in Apple Preview
- Fixed multiple bugs with the PDF outline - Fixed multiple bugs with the PDF outline
- Fixed citations and other searchable elements in [`hide`]($hide) - Fixed citations and other searchable elements in [`hide`]
- Fixed bugs with [reference supplements]($ref.supplement) - Fixed bugs with [reference supplements]($ref.supplement)
- Fixed Nix flake - Fixed Nix flake
@ -704,7 +701,7 @@ description: |
## Version 0.4.0 (May 20, 2023) { #v0.4.0 } ## Version 0.4.0 (May 20, 2023) { #v0.4.0 }
- Footnotes - Footnotes
- Implemented support for footnotes - Implemented support for footnotes
- The [`footnote`]($footnote) function inserts a footnote - The [`footnote`] function inserts a footnote
- The [`footnote.entry`]($footnote.entry) function can be used to customize - The [`footnote.entry`]($footnote.entry) function can be used to customize
the footnote listing the footnote listing
- The `{"chicago-notes"}` [citation style]($cite.style) is now available - The `{"chicago-notes"}` [citation style]($cite.style) is now available
@ -714,7 +711,7 @@ description: |
- Now shows default values for optional arguments - Now shows default values for optional arguments
- Added richer outlines in "On this Page" - Added richer outlines in "On this Page"
- Added initial support for search keywords: "Table of Contents" will now find - Added initial support for search keywords: "Table of Contents" will now find
the [outline]($outline) function. Suggestions for more keywords are welcome! the [outline] function. Suggestions for more keywords are welcome!
- Fixed issue with search result ranking - Fixed issue with search result ranking
- Fixed many more small issues - Fixed many more small issues
@ -736,8 +733,8 @@ description: |
- Scripting - Scripting
- Added function scopes: A function can now hold related definitions in its - Added function scopes: A function can now hold related definitions in its
own scope, similar to a module. The new [`assert.eq`]($assert.eq) function, own scope, similar to a module. The new [`assert.eq`]($assert.eq) function,
for instance, is part of the [`assert`]($assert) function's scope. Note that for instance, is part of the [`assert`] function's scope. Note that function
function scopes are currently only available for built-in functions. scopes are currently only available for built-in functions.
- Added [`assert.eq`]($assert.eq) and [`assert.ne`]($assert.ne) functions for - Added [`assert.eq`]($assert.eq) and [`assert.ne`]($assert.ne) functions for
simpler equality and inequality assertions with more helpful error messages simpler equality and inequality assertions with more helpful error messages
- Exposed [list]($list.item), [enum]($enum.item), and [term list]($terms.item) - Exposed [list]($list.item), [enum]($enum.item), and [term list]($terms.item)
@ -811,8 +808,8 @@ description: |
grace period. grace period.
- A lone underscore is not a valid identifier anymore, it can now only be used - A lone underscore is not a valid identifier anymore, it can now only be used
in patterns in patterns
- Removed `before` and `after` arguments from [`query`]($query). This is now - Removed `before` and `after` arguments from [`query`]. This is now handled
handled through flexible [selectors]($selector) combinator methods through flexible [selectors]($selector) combinator methods
- Added support for [attachments]($math.attach) (sub-, superscripts) that - Added support for [attachments]($math.attach) (sub-, superscripts) that
precede the base symbol. The `top` and `bottom` arguments have been renamed precede the base symbol. The `top` and `bottom` arguments have been renamed
to `t` and `b`. to `t` and `b`.
@ -824,7 +821,7 @@ description: |
- Added support for [destructuring]($scripting/#bindings) in argument lists - Added support for [destructuring]($scripting/#bindings) in argument lists
and assignments and assignments
- Added [`alt`]($image.alt) text argument to image function - Added [`alt`]($image.alt) text argument to image function
- Added [`toml`]($toml) function for loading data from a TOML file - Added [`toml`] function for loading data from a TOML file
- Added [`zip`]($array.zip), [`sum`]($array.sum), and - Added [`zip`]($array.zip), [`sum`]($array.sum), and
[`product`]($array.product) methods for arrays [`product`]($array.product) methods for arrays
- Added `fact`, `perm`, `binom`, `gcd`, `lcm`, `atan2`, `quo`, `trunc`, and - Added `fact`, `perm`, `binom`, `gcd`, `lcm`, `atan2`, `quo`, `trunc`, and
@ -839,8 +836,8 @@ description: |
- Locations are now a valid kind of selector - Locations are now a valid kind of selector
- Added a few symbols for algebra - Added a few symbols for algebra
- Added Spanish smart quote support - Added Spanish smart quote support
- Added [`selector`]($selector) function to turn a selector-like value into a - Added [`selector`] function to turn a selector-like value into a selector on
selector on which combinator methods can be called which combinator methods can be called
- Improved some error messages - Improved some error messages
- The outline and bibliography headings can now be styled with show-set rules - The outline and bibliography headings can now be styled with show-set rules
- Operations on numbers now produce an error instead of overflowing - Operations on numbers now produce an error instead of overflowing
@ -886,9 +883,9 @@ description: |
- Added [unpacking syntax]($scripting/#bindings) for let bindings, which - Added [unpacking syntax]($scripting/#bindings) for let bindings, which
allows things like `{let (1, 2) = array}` allows things like `{let (1, 2) = array}`
- Added [`enumerate`]($array.enumerate) method - Added [`enumerate`]($array.enumerate) method
- Added [`path`]($path) function for drawing Bézier paths - Added [`path`] function for drawing Bézier paths
- Added [`layout`]($layout) function to access the size of the surrounding - Added [`layout`] function to access the size of the surrounding page or
page or container container
- Added `key` parameter to [`sorted`]($array.sorted) method - Added `key` parameter to [`sorted`]($array.sorted) method
- Command line interface - Command line interface
@ -904,7 +901,7 @@ description: |
(AR, NB, CS, NN, PL, SL, ES, UA, VI) (AR, NB, CS, NN, PL, SL, ES, UA, VI)
- Added a few numbering patterns (Ihora, Chinese) - Added a few numbering patterns (Ihora, Chinese)
- Added `sinc` [operator]($math.op) - Added `sinc` [operator]($math.op)
- Fixed bug where math could not be hidden with [`hide`]($hide) - Fixed bug where math could not be hidden with [`hide`]
- Fixed sizing issues with box, block, and shapes - Fixed sizing issues with box, block, and shapes
- Fixed some translations - Fixed some translations
- Fixed inversion of "R" in [`cal`]($math.cal) and [`frak`]($math.frak) styles - Fixed inversion of "R" in [`cal`]($math.cal) and [`frak`]($math.frak) styles
@ -912,7 +909,7 @@ description: |
- Fixed supplements of references to headings - Fixed supplements of references to headings
- Fixed syntax highlighting of identifiers in certain scenarios - Fixed syntax highlighting of identifiers in certain scenarios
- [Ratios]($ratio) can now be multiplied with more types and be converted to - [Ratios]($ratio) can now be multiplied with more types and be converted to
[floats]($float) with the [`float`]($float) function [floats]($float) with the [`float`] function
<contributors from="v0.1.0" to="v0.2.0" /> <contributors from="v0.1.0" to="v0.2.0" />
@ -937,8 +934,8 @@ description: |
gives access to the automatically resolved kind, supplement, and counter gives access to the automatically resolved kind, supplement, and counter
- Bibliography improvements - Bibliography improvements
- The [`bibliography`]($bibliography) now also accepts multiple bibliography - The [`bibliography`] now also accepts multiple bibliography paths (as an
paths (as an array) array)
- Parsing of BibLaTeX files is now more permissive (accepts non-numeric - Parsing of BibLaTeX files is now more permissive (accepts non-numeric
edition, pages, volumes, dates, and Jabref-style comments; fixed edition, pages, volumes, dates, and Jabref-style comments; fixed
abbreviation parsing) abbreviation parsing)
@ -946,7 +943,7 @@ description: |
- Fixed APA bibliography ordering - Fixed APA bibliography ordering
- Drawing additions - Drawing additions
- Added [`polygon`]($polygon) function for drawing polygons - Added [`polygon`] function for drawing polygons
- Added support for clipping in [boxes]($box.clip) and [blocks]($block.clip) - Added support for clipping in [boxes]($box.clip) and [blocks]($block.clip)
- Command line interface - Command line interface
@ -957,12 +954,12 @@ description: |
- Added `--open` flag to directly open the PDF - Added `--open` flag to directly open the PDF
- Miscellaneous improvements - Miscellaneous improvements
- Added [`yaml`]($yaml) function to load data from YAML files - Added [`yaml`] function to load data from YAML files
- Added basic i18n for a few more languages (IT, RU, ZH, FR, PT) - Added basic i18n for a few more languages (IT, RU, ZH, FR, PT)
- Added numbering support for Hebrew - Added numbering support for Hebrew
- Added support for [integers]($int) with base 2, 8, and 16 - Added support for [integers]($int) with base 2, 8, and 16
- Added symbols for double bracket and laplace operator - Added symbols for double bracket and laplace operator
- The [`link`]($link) function now accepts [labels]($label) - The [`link`] function now accepts [labels]($label)
- The link syntax now allows more characters - The link syntax now allows more characters
- Improved justification of Japanese and Chinese text - Improved justification of Japanese and Chinese text
- Calculation functions behave more consistently w.r.t to non-real results - Calculation functions behave more consistently w.r.t to non-real results
@ -976,7 +973,7 @@ description: |
- Fixed invalid parsing of language tag in raw block with a single backtick - Fixed invalid parsing of language tag in raw block with a single backtick
- Fixed bugs with displaying counters and state - Fixed bugs with displaying counters and state
- Fixed crash related to page counter - Fixed crash related to page counter
- Fixed crash when [`symbol`]($symbol) function was called without arguments - Fixed crash when [`symbol`] function was called without arguments
- Fixed crash in bibliography generation - Fixed crash in bibliography generation
- Fixed access to label of certain content elements - Fixed access to label of certain content elements
- Fixed line number in error message for CSV parsing - Fixed line number in error message for CSV parsing
@ -1005,7 +1002,7 @@ description: |
- Numberings now allow zeros. To reset a counter, you can write - Numberings now allow zeros. To reset a counter, you can write
`[#counter(..).update(0)]` `[#counter(..).update(0)]`
- Added documentation for `{page()}` and `{position()}` methods on - Added documentation for `{page()}` and `{position()}` methods on
[`location`]($location) type [`location`] type
- Added symbols for double, triple, and quadruple dot accent - Added symbols for double, triple, and quadruple dot accent
- Added smart quotes for Norwegian Bokmål - Added smart quotes for Norwegian Bokmål
- Added Nix flake - Added Nix flake
@ -1014,8 +1011,7 @@ description: |
- Fixed parsing of unbalanced delimiters in fractions: `[$1/(2 (x)$]` - Fixed parsing of unbalanced delimiters in fractions: `[$1/(2 (x)$]`
- Fixed unexpected parsing of numbers as enumerations, e.g. in `[1.2]` - Fixed unexpected parsing of numbers as enumerations, e.g. in `[1.2]`
- Fixed combination of page fill and header - Fixed combination of page fill and header
- Fixed compiler crash if [`repeat`]($repeat) is used in page with automatic - Fixed compiler crash if [`repeat`] is used in page with automatic width
width
- Fixed [matrices]($math.mat) with explicit delimiter - Fixed [matrices]($math.mat) with explicit delimiter
- Fixed [`indent`]($terms.indent) property of term lists - Fixed [`indent`]($terms.indent) property of term lists
- Numerous documentation fixes - Numerous documentation fixes
@ -1035,57 +1031,57 @@ description: |
- `[$ A = pi r^2 $ <area>]` - `[$ A = pi r^2 $ <area>]`
- Introspection system for interactions between different parts of the document - Introspection system for interactions between different parts of the document
- [`counter`]($counter) function - [`counter`] function
- Access and modify counters for pages, headings, figures, and equations - Access and modify counters for pages, headings, figures, and equations
- Define and use your own custom counters - Define and use your own custom counters
- Time travel: Find out what the counter value was or will be at some other - Time travel: Find out what the counter value was or will be at some other
point in the document (e.g. when you're building a list of figures, you point in the document (e.g. when you're building a list of figures, you
can determine the value of the figure counter at any given figure). can determine the value of the figure counter at any given figure).
- Counters count in layout order and not in code order - Counters count in layout order and not in code order
- [`state`]($state) function - [`state`] function
- Manage arbitrary state across your document - Manage arbitrary state across your document
- Time travel: Find out the value of your state at any position in the - Time travel: Find out the value of your state at any position in the
document document
- State is modified in layout order and not in code order - State is modified in layout order and not in code order
- [`query`]($query) function - [`query`] function
- Find all occurrences of an element or a label, either in the whole - Find all occurrences of an element or a label, either in the whole
document or before/after some location document or before/after some location
- Link to elements, find out their position on the pages and access their - Link to elements, find out their position on the pages and access their
fields fields
- Example use cases: Custom list of figures or page header with current - Example use cases: Custom list of figures or page header with current
chapter title chapter title
- [`locate`]($locate) function - [`locate`] function
- Determines the location of itself in the final layout - Determines the location of itself in the final layout
- Can be accessed to get the `page` and `x`, `y` coordinates - Can be accessed to get the `page` and `x`, `y` coordinates
- Can be used with counters and state to find out their values at that - Can be used with counters and state to find out their values at that
location location
- Can be used with queries to find elements before or after its location - Can be used with queries to find elements before or after its location
- New [`measure`]($measure) function - New [`measure`] function
- Measure the layouted size of elements - Measure the layouted size of elements
- To be used in combination with the new [`style`]($style) function that lets - To be used in combination with the new [`style`] function that lets you
you generate different content based on the style context something is generate different content based on the style context something is inserted
inserted into (because that affects the measured size of content) into (because that affects the measured size of content)
- Exposed content representation - Exposed content representation
- Content is not opaque anymore - Content is not opaque anymore
- Content can be compared for equality - Content can be compared for equality
- The tree of content elements can be traversed with code - The tree of content elements can be traversed with code
- Can be observed in hover tooltips or with [`repr`]($repr) - Can be observed in hover tooltips or with [`repr`]
- New [methods]($content) on content: `func`, `has`, `at`, and `location` - New [methods]($content) on content: `func`, `has`, `at`, and `location`
- All optional fields on elements are now settable - All optional fields on elements are now settable
- More uniform field names (`heading.title` becomes `heading.body`, - More uniform field names (`heading.title` becomes `heading.body`,
`list.items` becomes `list.children`, and a few more changes) `list.items` becomes `list.children`, and a few more changes)
- Further improvements - Further improvements
- Added [`figure`]($figure) function - Added [`figure`] function
- Added [`numbering`]($math.equation.numbering) parameter on equation function - Added [`numbering`]($math.equation.numbering) parameter on equation function
- Added [`numbering`]($page.numbering) and - Added [`numbering`]($page.numbering) and
[`number-align`]($page.number-align) parameters on page function [`number-align`]($page.number-align) parameters on page function
- The page function's [`header`]($page.header) and [`footer`]($page.footer) - The page function's [`header`]($page.header) and [`footer`]($page.footer)
parameters do not take functions anymore. If you want to customize them parameters do not take functions anymore. If you want to customize them
based on the page number, use the new [`numbering`]($page.numbering) based on the page number, use the new [`numbering`]($page.numbering)
parameter or [`counter`]($counter) function instead. parameter or [`counter`] function instead.
- Added [`footer-descent`]($page.footer-descent) and - Added [`footer-descent`]($page.footer-descent) and
[`header-ascent`]($page.header-ascent) parameters [`header-ascent`]($page.header-ascent) parameters
- Better default alignment in header and footer - Better default alignment in header and footer
@ -1097,7 +1093,7 @@ description: |
- Renamed paragraph `indent` to [`first-line-indent`]($par.first-line-indent) - Renamed paragraph `indent` to [`first-line-indent`]($par.first-line-indent)
- More accurate [logarithm]($calc.log) when base is `2` or `10` - More accurate [logarithm]($calc.log) when base is `2` or `10`
- Improved some error messages - Improved some error messages
- Fixed layout of [`terms`]($terms) list - Fixed layout of [`terms`] list
- Web app improvements - Web app improvements
- Added template gallery - Added template gallery
@ -1124,9 +1120,9 @@ description: |
- Lots of new math fonts available - Lots of new math fonts available
- Removed Latin Modern fonts in favor of New Computer Modern family - Removed Latin Modern fonts in favor of New Computer Modern family
- Removed unnecessary smallcaps fonts which are already accessible through the - Removed unnecessary smallcaps fonts which are already accessible through the
corresponding main font and the [`smallcaps`]($smallcaps) function corresponding main font and the [`smallcaps`] function
- Improved default spacing for headings - Improved default spacing for headings
- Added [`panic`]($panic) function - Added [`panic`] function
- Added [`clusters`]($str.clusters) and [`codepoints`]($str.codepoints) methods - Added [`clusters`]($str.clusters) and [`codepoints`]($str.codepoints) methods
for strings for strings
- Support for multiple authors in [`set document`]($document.author) - Support for multiple authors in [`set document`]($document.author)
@ -1139,14 +1135,14 @@ description: |
- Improved incremental compilation for user-defined functions - Improved incremental compilation for user-defined functions
## February 15, 2023 { #_ } ## February 15, 2023 { #_ }
- [Box]($box) and [block]($block) have gained `fill`, `stroke`, `radius`, and - [Box]($box) and [block] have gained `fill`, `stroke`, `radius`, and `inset`
`inset` properties properties
- Blocks may now be explicitly sized, fixed-height blocks can still break across - Blocks may now be explicitly sized, fixed-height blocks can still break across
pages pages
- Blocks can now be configured to be [`breakable`]($block.breakable) or not - Blocks can now be configured to be [`breakable`]($block.breakable) or not
- [Numbering style]($enum.numbering) can now be configured for nested enums - [Numbering style]($enum.numbering) can now be configured for nested enums
- [Markers]($list.marker) can now be configured for nested lists - [Markers]($list.marker) can now be configured for nested lists
- The [`eval`]($eval) function now expects code instead of markup and returns an - The [`eval`] function now expects code instead of markup and returns an
arbitrary value. Markup can still be evaluated by surrounding the string with arbitrary value. Markup can still be evaluated by surrounding the string with
brackets. brackets.
- PDFs generated by Typst now contain XMP metadata - PDFs generated by Typst now contain XMP metadata
@ -1156,8 +1152,8 @@ description: |
## February 12, 2023 { #_ } ## February 12, 2023 { #_ }
- Shapes, images, and transformations (move/rotate/scale/repeat) are now - Shapes, images, and transformations (move/rotate/scale/repeat) are now
block-level. To integrate them into a paragraph, use a [`box`]($box) as with block-level. To integrate them into a paragraph, use a [`box`] as with other
other elements. elements.
- A colon is now required in an "everything" show rule: Write `{show: it => ..}` - A colon is now required in an "everything" show rule: Write `{show: it => ..}`
instead of `{show it => ..}`. This prevents intermediate states that ruin your instead of `{show it => ..}`. This prevents intermediate states that ruin your
whole document. whole document.
@ -1170,14 +1166,14 @@ description: |
- Fixed bug where columns jump to next page - Fixed bug where columns jump to next page
- Fixed bug where list items have no leading - Fixed bug where list items have no leading
- Fixed relative sizing in lists, squares and grid auto columns - Fixed relative sizing in lists, squares and grid auto columns
- Fixed relative displacement in [`place`]($place) function - Fixed relative displacement in [`place`] function
- Fixed that lines don't have a size - Fixed that lines don't have a size
- Fixed bug where `{set document(..)}` complains about being after content - Fixed bug where `{set document(..)}` complains about being after content
- Fixed parsing of `{not in}` operation - Fixed parsing of `{not in}` operation
- Fixed hover tooltips in math - Fixed hover tooltips in math
- Fixed bug where a heading show rule may not contain a pagebreak when an - Fixed bug where a heading show rule may not contain a pagebreak when an
outline is present outline is present
- Added [`baseline`]($box.baseline) property on [`box`]($box) - Added [`baseline`]($box.baseline) property on [`box`]
- Added [`tg`]($math.op) and [`ctg`]($math.op) operators in math - Added [`tg`]($math.op) and [`ctg`]($math.op) operators in math
- Added delimiter setting for [`cases`]($math.cases) function - Added delimiter setting for [`cases`]($math.cases) function
- Parentheses are now included when accepting a function autocompletion - Parentheses are now included when accepting a function autocompletion

View File

@ -25,7 +25,7 @@ provide instant previews.
In the following, we will cover some of the most common questions a user In the following, we will cover some of the most common questions a user
switching from LaTeX will have when composing a document in Typst. If you prefer switching from LaTeX will have when composing a document in Typst. If you prefer
a step-by-step introduction to Typst, check out our [tutorial]($tutorial). a step-by-step introduction to Typst, check out our [tutorial].
## How do I create a new, empty document? { #getting-started } ## How do I create a new, empty document? { #getting-started }
That's easy. You just create a new, empty text file (the file extension is That's easy. You just create a new, empty text file (the file extension is
@ -65,20 +65,20 @@ Emphasis (usually rendered as italic text) is expressed by enclosing text in
Here is a list of common markup commands used in LaTeX and their Typst Here is a list of common markup commands used in LaTeX and their Typst
equivalents. You can also check out the [full syntax cheat sheet]($syntax). equivalents. You can also check out the [full syntax cheat sheet]($syntax).
| Element | LaTeX | Typst | See | Element | LaTeX | Typst | See |
|:-----------------|:--------------------------|:-----------------------|:-------------------- |:-----------------|:--------------------------|:-----------------------|:-----------|
| Strong emphasis | `\textbf{strong}` | `[*strong*]` | [`strong`]($strong) | | Strong emphasis | `\textbf{strong}` | `[*strong*]` | [`strong`] |
| Emphasis | `\emph{emphasis}` | `[_emphasis_]` | [`emph`]($emph) | | Emphasis | `\emph{emphasis}` | `[_emphasis_]` | [`emph`] |
| Monospace / code | `\texttt{print(1)}` | ``[`print(1)`]`` | [`raw`]($raw) | | Monospace / code | `\texttt{print(1)}` | ``[`print(1)`]`` | [`raw`] |
| Link | `\url{https://typst.app}` | `[https://typst.app/]` | [`link`]($link) | | Link | `\url{https://typst.app}` | `[https://typst.app/]` | [`link`] |
| Label | `\label{intro}` | `[<intro>]` | [`label`]($label) | | Label | `\label{intro}` | `[<intro>]` | [`label`] |
| Reference | `\ref{intro}` | `[@intro]` | [`ref`]($ref) | | Reference | `\ref{intro}` | `[@intro]` | [`ref`] |
| Citation | `\cite{humphrey97}` | `[@humphrey97]` | [`cite`]($cite) | | Citation | `\cite{humphrey97}` | `[@humphrey97]` | [`cite`] |
| Bullet list | `itemize` environment | `[- List]` | [`list`]($list) | | Bullet list | `itemize` environment | `[- List]` | [`list`] |
| Numbered list | `enumerate` environment | `[+ List]` | [`enum`]($enum) | | Numbered list | `enumerate` environment | `[+ List]` | [`enum`] |
| Term list | `description` environment | `[/ Term: List]` | [`terms`]($terms) | | Term list | `description` environment | `[/ Term: List]` | [`terms`] |
| Figure | `figure` environment | `figure` function | [`figure`]($figure) | | Figure | `figure` environment | `figure` function | [`figure`] |
| Table | `table` environment | `table` function | [`table`]($table) | | Table | `table` environment | `table` function | [`table`] |
| Equation | `$x$`, `align` / `equation` environments | `[$x$]`, `[$ x = y $]` | [`equation`]($math.equation) | | Equation | `$x$`, `align` / `equation` environments | `[$x$]`, `[$ x = y $]` | [`equation`]($math.equation) |
[Lists]($list) do not rely on environments in Typst. Instead, they have [Lists]($list) do not rely on environments in Typst. Instead, they have
@ -147,12 +147,12 @@ And finally a little loop:
] ]
``` ```
A function call always involves the name of the function ([`rect`]($rect), A function call always involves the name of the function ([`rect`],
[`underline`]($underline), [`calc.max`]($calc.max), [`range`]($array.range)) [`underline`], [`calc.max`]($calc.max), [`range`]($array.range)) followed by
followed by parentheses (as opposed to LaTeX where the square brackets and curly parentheses (as opposed to LaTeX where the square brackets and curly braces are
braces are optional if the macro requires no arguments). The expected list of optional if the macro requires no arguments). The expected list of arguments
arguments passed within those parentheses depends on the concrete function and passed within those parentheses depends on the concrete function and is
is specified in the [reference]($reference). specified in the [reference].
### Arguments ### Arguments
A function can have multiple arguments. Some arguments are positional, i.e., you A function can have multiple arguments. Some arguments are positional, i.e., you
@ -177,10 +177,10 @@ Named arguments are similar to how some LaTeX environments are configured, for
example, you would type `\begin{enumerate}[label={\alph*)}]` to start a list example, you would type `\begin{enumerate}[label={\alph*)}]` to start a list
with the labels `a)`, `b)`, and so on. with the labels `a)`, `b)`, and so on.
Often, you want to provide some [content]($content) to a function. For example, Often, you want to provide some [content] to a function. For example, the LaTeX
the LaTeX command `\underline{Alternative A}` would translate to command `\underline{Alternative A}` would translate to
`[#underline([Alternative A])]` in Typst. The square brackets indicate that a `[#underline([Alternative A])]` in Typst. The square brackets indicate that a
value is [content]($content). Within these brackets, you can use normal markup. value is [content]. Within these brackets, you can use normal markup.
However, that's a lot of parentheses for a pretty simple construct. This is why However, that's a lot of parentheses for a pretty simple construct. This is why
you can also move trailing content arguments after the parentheses (and omit the you can also move trailing content arguments after the parentheses (and omit the
parentheses if they would end up empty). parentheses if they would end up empty).
@ -283,11 +283,11 @@ You can achieve the effects of LaTeX commands like `\textbf`, `\textsf`,
`\rmfamily`, `\mdseries`, and `\itshape` with the [`font`]($text.font), `\rmfamily`, `\mdseries`, and `\itshape` with the [`font`]($text.font),
[`style`]($text.style), and [`weight`]($text.weight) arguments of the `text` [`style`]($text.style), and [`weight`]($text.weight) arguments of the `text`
function. The text function can be used in a set rule (declaration style) or function. The text function can be used in a set rule (declaration style) or
with a content argument. To replace `\textsc`, you can use the with a content argument. To replace `\textsc`, you can use the [`smallcaps`]
[`smallcaps`]($smallcaps) function, which renders its content argument as function, which renders its content argument as smallcaps. Should you want to
smallcaps. Should you want to use it declaration style (like `\scshape`), you use it declaration style (like `\scshape`), you can use an
can use an [_everything_ show rule]($styling/#show-rules) that applies the [_everything_ show rule]($styling/#show-rules) that applies the function to the
function to the rest of the scope: rest of the scope:
```example ```example
#show: smallcaps #show: smallcaps
@ -434,22 +434,22 @@ is built right-in. Below, we compiled a table with frequently loaded packages
and their corresponding Typst functions. and their corresponding Typst functions.
| LaTeX Package | Typst Alternative | | LaTeX Package | Typst Alternative |
|:--------------------------------|:------------------------------------------------------------- | |:--------------------------------|:-------------------------------------------|
| graphicx, svg | [`image`]($image) function | | graphicx, svg | [`image`] function |
| tabularx | [`table`]($table), [`grid`]($grid) functions | | tabularx | [`table`], [`grid`] functions |
| fontenc, inputenc, unicode-math | Just start writing! | | fontenc, inputenc, unicode-math | Just start writing! |
| babel, polyglossia | [`text`]($text.lang) function: `[#set text(lang: "zh")]` | | babel, polyglossia | [`text`]($text.lang) function: `[#set text(lang: "zh")]` |
| amsmath | [Math mode]($category/math) | | amsmath | [Math mode]($category/math) |
| amsfonts, amssymb | [`sym`]($category/symbols) module and [syntax]($syntax/#math) | | amsfonts, amssymb | [`sym`]($category/symbols) module and [syntax]($syntax/#math) |
| geometry, fancyhdr | [`page`]($page) function | | geometry, fancyhdr | [`page`] function |
| xcolor | [`text`]($text.fill) function: `[#set text(fill: rgb("#0178A4"))]` | | xcolor | [`text`]($text.fill) function: `[#set text(fill: rgb("#0178A4"))]` |
| hyperref | [`link`]($link) function | | hyperref | [`link`] function |
| bibtex, biblatex, natbib | [`cite`]($cite), [`bibliography`]($bibliography) functions | | bibtex, biblatex, natbib | [`cite`], [`bibliography`] functions |
| lstlisting, minted | [`raw`]($raw) function and syntax | | lstlisting, minted | [`raw`] function and syntax |
| parskip | [`block`]($block.spacing) and [`par`]($par.first-line-indent) functions | | parskip | [`block`]($block.spacing) and [`par`]($par.first-line-indent) functions |
| csquotes | Set the [`text`]($text.lang) language and type `["]` or `[']` | | csquotes | Set the [`text`]($text.lang) language and type `["]` or `[']` |
| caption | [`figure`]($figure) function | | caption | [`figure`] function |
| enumitem | [`list`]($list), [`enum`]($enum), [`terms`]($terms) functions | | enumitem | [`list`], [`enum`], [`terms`] functions |
Although _many_ things are built-in, not everything can be. That's why Typst has Although _many_ things are built-in, not everything can be. That's why Typst has
a built-in [package manager]($packages) where the community can share their a built-in [package manager]($packages) where the community can share their
@ -606,8 +606,7 @@ a reusable template?
## Bibliographies ## Bibliographies
Typst includes a fully-featured bibliography system that is compatible with Typst includes a fully-featured bibliography system that is compatible with
BibTeX files. You can continue to use your `.bib` literature libraries by BibTeX files. You can continue to use your `.bib` literature libraries by
loading them with the [`bibliography`]($bibliography) function. Another loading them with the [`bibliography`] function. Another possibility is to use
possibility is to use
[Typst's YAML-based native format](https://github.com/typst/hayagriva/blob/main/docs/file-format.md). [Typst's YAML-based native format](https://github.com/typst/hayagriva/blob/main/docs/file-format.md).
Typst uses the Citation Style Language to define and process citation and Typst uses the Citation Style Language to define and process citation and
@ -619,13 +618,14 @@ your own.
You can cite an entry in your bibliography or reference a label in your document You can cite an entry in your bibliography or reference a label in your document
with the same syntax: `[@key]` (this would reference an entry called `key`). with the same syntax: `[@key]` (this would reference an entry called `key`).
Alternatively, you can use the [`cite`]($cite) function. Alternatively, you can use the [`cite`] function.
Alternative forms for your citation, such as year only and citations for natural Alternative forms for your citation, such as year only and citations for natural
use in prose (cf. `\citet` and `\textcite`) are available with use in prose (cf. `\citet` and `\textcite`) are available with
[`[#cite(<key>, form: "prose")]`]($cite.form). [`[#cite(<key>, form: "prose")]`]($cite.form).
You can find more information on the documentation page of the [`bibliography`]($bibliography) function. You can find more information on the documentation page of the [`bibliography`]
function.
## Installation ## Installation
You have two ways to use Typst: In [our web app](https://typst.app/signup/) or You have two ways to use Typst: In [our web app](https://typst.app/signup/) or

View File

@ -185,14 +185,13 @@ conditionally remove the header on the first page:
#lorem(150) #lorem(150)
``` ```
This example may look intimidating, but let's break it down: We are telling This example may look intimidating, but let's break it down: By using the
Typst that the header depends on the current [location]($locate). The `loc` `{context}` keyword, we are telling Typst that the header depends on where we
value allows other functions to find out where on the page we currently are. We are in the document. We then ask Typst if the page [counter] is larger than one
then ask Typst if the page [counter]($counter) is larger than one at our current at our (context-dependant) current position. The page counter starts at one, so
position. The page counter starts at one, so we are skipping the header on a we are skipping the header on a single page. Counters may have multiple levels.
single page. Counters may have multiple levels. This feature is used for items This feature is used for items like headings, but the page counter will always
like headings, but the page counter will always have a single level, so we can have a single level, so we can just look at the first one.
just look at the first one.
You can, of course, add an `else` to this example to add a different header to You can, of course, add an `else` to this example to add a different header to
the first page instead. the first page instead.
@ -201,8 +200,8 @@ the first page instead.
The technique described in the previous section can be adapted to perform more The technique described in the previous section can be adapted to perform more
advanced tasks using Typst's labels. For example, pages with big tables could advanced tasks using Typst's labels. For example, pages with big tables could
omit their headers to help keep clutter down. We will mark our tables with a omit their headers to help keep clutter down. We will mark our tables with a
`<big-table>` [label]($label) and use the [query system]($query) to find out if `<big-table>` [label] and use the [query system]($query) to find out if such a
such a label exists on the current page: label exists on the current page:
```typ ```typ
>>> #set page("a5", margin: (x: 2.5cm, y: 3cm)) >>> #set page("a5", margin: (x: 2.5cm, y: 3cm))
@ -334,10 +333,9 @@ This page has a custom footer.
``` ```
In this example, we use the number of pages to create an array of In this example, we use the number of pages to create an array of
[circles]($circle). The circles are wrapped in a [box]($box) so they can all [circles]($circle). The circles are wrapped in a [box] so they can all appear on
appear on the same line because they are blocks and would otherwise create the same line because they are blocks and would otherwise create paragraph
paragraph breaks. The length of this [array]($array) depends on the current page breaks. The length of this [array] depends on the current page number.
number.
We then insert the circles at the right side of the footer, with 1pt of space We then insert the circles at the right side of the footer, with 1pt of space
between them. The join method of an array will attempt to between them. The join method of an array will attempt to
@ -354,8 +352,8 @@ want to start with the first page only after the title page. Or maybe you need
to skip a few page numbers because you will insert pages into the final printed to skip a few page numbers because you will insert pages into the final printed
product. product.
The right way to modify the page number is to manipulate the page The right way to modify the page number is to manipulate the page [counter]. The
[counter]($counter). The simplest manipulation is to set the counter back to 1. simplest manipulation is to set the counter back to 1.
```typ ```typ
#counter(page).update(1) #counter(page).update(1)
@ -373,8 +371,8 @@ In this example, we skip five pages. `n` is the current value of the page
counter and `n + 5` is the return value of our function. counter and `n + 5` is the return value of our function.
In case you need to retrieve the actual page number instead of the value of the In case you need to retrieve the actual page number instead of the value of the
page counter, you can use the [`page`]($locate) method on the argument of the page counter, you can use the [`page`]($location.page) method on the return
`{locate}` closure: value of the [`here`] function:
```example ```example
#counter(page).update(n => n + 5) #counter(page).update(n => n + 5)
@ -384,8 +382,8 @@ page counter, you can use the [`page`]($locate) method on the argument of the
#context here().page() #context here().page()
``` ```
You can also obtain the page numbering pattern from the `{locate}` closure You can also obtain the page numbering pattern from the location returned by
parameter with the [`page-numbering`]($locate) method. `here` with the [`page-numbering`]($location.page-numbering) method.
## Add columns { #columns } ## Add columns { #columns }
Add columns to your document to fit more on a page while maintaining legible Add columns to your document to fit more on a page while maintaining legible

View File

@ -53,11 +53,10 @@ properly reacts to the current surroundings.
#value #value
``` ```
Crucially, upon creation, `value` becomes opaque [content]($content) that we Crucially, upon creation, `value` becomes opaque [content] that we cannot peek
cannot peek into. It can only be resolved when placed somewhere because only into. It can only be resolved when placed somewhere because only then the
then the context is known. The body of a context expression may be evaluated context is known. The body of a context expression may be evaluated zero, one,
zero, one, or multiple times, depending on how many different places it is put or multiple times, depending on how many different places it is put into.
into.
## Location context ## Location context
Context can not only give us access to set rule values. It can also let us know Context can not only give us access to set rule values. It can also let us know
@ -89,20 +88,19 @@ resolved numbers. Thus, we get the following result:
#context counter(heading).get() #context counter(heading).get()
``` ```
For more flexibility, we can also use the [`here`]($here) function to directly For more flexibility, we can also use the [`here`] function to directly extract
extract the current [location]($location) from the context. The example below the current [location] from the context. The example below
demonstrates this: demonstrates this:
- We first have `{counter(heading).get()}`, which resolves to `{(2,)}` as - We first have `{counter(heading).get()}`, which resolves to `{(2,)}` as
before. before.
- We then use the more powerful [`counter.at`]($counter.at) with - We then use the more powerful [`counter.at`] with [`here`], which in
[`here`]($here), which in combination is equivalent to `get`, and thus get combination is equivalent to `get`, and thus get `{(2,)}`.
`{(2,)}`. - Finally, we use `at` with a [label] to retrieve the value of the counter at a
- Finally, we use `at` with a [label]($label) to retrieve the value of the _different_ location in the document, in our case that of the introduction
counter at a _different_ location in the document, in our case that of the heading. This yields `{(1,)}`. Typst's context system gives us time travel
introduction heading. This yields `{(1,)}`. Typst's context system gives us abilities and lets us retrieve the values of any counters and states at _any_
time travel abilities and lets us retrieve the values of any counters and location in the document.
states at _any_ location in the document.
```example ```example
#set heading(numbering: "1.") #set heading(numbering: "1.")
@ -121,10 +119,10 @@ demonstrates this:
``` ```
As mentioned before, we can also use context to get the physical position of As mentioned before, we can also use context to get the physical position of
elements on the pages. We do this with the [`locate`]($locate) function, which elements on the pages. We do this with the [`locate`] function, which works
works similarly to `counter.at`: It takes a location or other similarly to `counter.at`: It takes a location or other [selector] that resolves
[selector]($selector) that resolves to a unique element (could also be a label) to a unique element (could also be a label) and returns the position on the
and returns the position on the pages for that element. pages for that element.
```example ```example
Background is at: \ Background is at: \
@ -139,7 +137,7 @@ Background is at: \
``` ```
There are other functions that make use of the location context, most There are other functions that make use of the location context, most
prominently [`query`]($query). Take a look at the prominently [`query`]. Take a look at the
[introspection]($category/introspection) category for more details on those. [introspection]($category/introspection) category for more details on those.
## Nested contexts ## Nested contexts

View File

@ -9,8 +9,8 @@
details: | details: |
Alternate typefaces within formulas. Alternate typefaces within formulas.
These functions are distinct from the [`text`]($text) function because math These functions are distinct from the [`text`] function because math fonts
fonts contain multiple variants of each letter. contain multiple variants of each letter.
- name: styles - name: styles
title: Styles title: Styles
@ -20,8 +20,8 @@
details: | details: |
Alternate letterforms within formulas. Alternate letterforms within formulas.
These functions are distinct from the [`text`]($text) function because math These functions are distinct from the [`text`] function because math fonts
fonts contain multiple variants of each letter. contain multiple variants of each letter.
- name: sizes - name: sizes
title: Sizes title: Sizes
@ -131,10 +131,10 @@
This module defines the following items: This module defines the following items:
- The `sys.version` constant (of type [`version`]($version)) that specifies - The `sys.version` constant (of type [`version`]) that specifies
the currently active Typst compiler version. the currently active Typst compiler version.
- The `sys.inputs` [dictionary]($dictionary), which makes external inputs - The `sys.inputs` [dictionary], which makes external inputs
available to the project. An input specified in the command line as available to the project. An input specified in the command line as
`--input key=value` becomes available under `sys.inputs.key` as `--input key=value` becomes available under `sys.inputs.key` as
`{"value"}`. To include spaces in the value, it may be enclosed with `{"value"}`. To include spaces in the value, it may be enclosed with

View File

@ -46,9 +46,9 @@ _blocks:_
With content blocks, you can handle markup/content as a programmatic value, With content blocks, you can handle markup/content as a programmatic value,
store it in variables and pass it to [functions]($function). Content store it in variables and pass it to [functions]($function). Content
blocks are delimited by square brackets and can contain arbitrary markup. A blocks are delimited by square brackets and can contain arbitrary markup. A
content block results in a value of type [content]($content). An content block results in a value of type [content]. An arbitrary number of
arbitrary number of content blocks can be passed as trailing arguments to content blocks can be passed as trailing arguments to functions. That is,
functions. That is, `{list([A], [B])}` is equivalent to `{list[A][B]}`. `{list([A], [B])}` is equivalent to `{list[A][B]}`.
Content and code blocks can be nested arbitrarily. In the example below, Content and code blocks can be nested arbitrarily. In the example below,
`{[hello ]}` is joined with the output of `{a + [ the ] + b}` yielding `{[hello ]}` is joined with the output of `{a + [ the ] + b}` yielding
@ -189,14 +189,14 @@ together into one larger array.
For loops can iterate over a variety of collections: For loops can iterate over a variety of collections:
- `{for value in array {..}}` \ - `{for value in array {..}}` \
Iterates over the items in the [array]($array). The destructuring syntax Iterates over the items in the [array]. The destructuring syntax described in
described in [Let binding]($scripting/#bindings) can also be used here. [Let binding]($scripting/#bindings) can also be used here.
- `{for pair in dict {..}}` \ - `{for pair in dict {..}}` \
Iterates over the key-value pairs of the [dictionary]($dictionary). Iterates over the key-value pairs of the [dictionary]. The pairs can also be
The pairs can also be destructured by using `{for (key, value) in dict {..}}`. destructured by using `{for (key, value) in dict {..}}`. It is more efficient
It is more efficient than `{for pair in dict.pairs() {..}}` because it doesn't than `{for pair in dict.pairs() {..}}` because it doesn't create a temporary
create a temporary array of all key-value pairs. array of all key-value pairs.
- `{for letter in "abc" {..}}` \ - `{for letter in "abc" {..}}` \
Iterates over the characters of the [string]($str). Technically, it iterates Iterates over the characters of the [string]($str). Technically, it iterates
@ -205,9 +205,9 @@ For loops can iterate over a variety of collections:
codepoints, like a flag emoji. codepoints, like a flag emoji.
- `{for byte in bytes("😀") {..}}` \ - `{for byte in bytes("😀") {..}}` \
Iterates over the [bytes]($bytes), which can be converted from a [string]($str) Iterates over the [bytes], which can be converted from a [string]($str) or
or [read]($read) from a file without encoding. Each byte value is an [read] from a file without encoding. Each byte value is an [integer]($int)
[integer]($int) between `{0}` and `{255}`. between `{0}` and `{255}`.
To control the execution of the loop, Typst provides the `{break}` and To control the execution of the loop, Typst provides the `{break}` and
`{continue}` statements. The former performs an early exit from the loop while `{continue}` statements. The former performs an early exit from the loop while
@ -233,10 +233,10 @@ The body of a loop can be a code or content block:
## Fields ## Fields
You can use _dot notation_ to access fields on a value. The value in question You can use _dot notation_ to access fields on a value. The value in question
can be either: can be either:
- a [dictionary]($dictionary) that has the specified key, - a [dictionary] that has the specified key,
- a [symbol]($symbol) that has the specified modifier, - a [symbol] that has the specified modifier,
- a [module]($module) containing the specified definition, - a [module] containing the specified definition,
- [content]($content) consisting of an element that has the specified field. The - [content] consisting of an element that has the specified field. The
available fields match the arguments of the available fields match the arguments of the
[element function]($function/#element-functions) that were given when the [element function]($function/#element-functions) that were given when the
element was constructed. element was constructed.
@ -253,8 +253,8 @@ can be either:
## Methods ## Methods
A _method call_ is a convenient way to call a function that is scoped to a A _method call_ is a convenient way to call a function that is scoped to a
value's [type]($type). For example, we can call the [`str.len`]($str.len) value's [type]. For example, we can call the [`str.len`]($str.len) function in
function in the following two equivalent ways: the following two equivalent ways:
```example ```example
#str.len("abc") is the same as #str.len("abc") is the same as
@ -291,14 +291,12 @@ module can refer to the content and definitions of another module in multiple
ways: ways:
- **Including:** `{include "bar.typ"}` \ - **Including:** `{include "bar.typ"}` \
Evaluates the file at the path `bar.typ` and returns the resulting Evaluates the file at the path `bar.typ` and returns the resulting [content].
[content]($content).
- **Import:** `{import "bar.typ"}` \ - **Import:** `{import "bar.typ"}` \
Evaluates the file at the path `bar.typ` and inserts the resulting Evaluates the file at the path `bar.typ` and inserts the resulting [module]
[module]($module) into the current scope as `bar` (filename without into the current scope as `bar` (filename without extension). You can use the
extension). You can use the `as` keyword to rename the imported module: `as` keyword to rename the imported module: `{import "bar.typ" as baz}`
`{import "bar.typ" as baz}`
- **Import items:** `{import "bar.typ": a, b}` \ - **Import items:** `{import "bar.typ": a, b}` \
Evaluates the file at the path `bar.typ`, extracts the values of the variables Evaluates the file at the path `bar.typ`, extracts the values of the variables
@ -327,8 +325,7 @@ and a version.
``` ```
The `preview` namespace contains packages shared by the community. You can find The `preview` namespace contains packages shared by the community. You can find
a searchable list of available community packages in the [packages]($packages) a searchable list of available community packages in the [packages] section.
section.
If you are using Typst locally, you can also create your own system-local If you are using Typst locally, you can also create your own system-local
packages. For more details on this, see the packages. For more details on this, see the

View File

@ -62,11 +62,10 @@ a _set-if_ rule.
## Show rules ## Show rules
With show rules, you can deeply customize the look of a type of element. The With show rules, you can deeply customize the look of a type of element. The
most basic form of show rule is a _show-set rule._ Such a rule is written as the most basic form of show rule is a _show-set rule._ Such a rule is written as the
`{show}` keyword followed by a [selector]($selector), a colon and then a set `{show}` keyword followed by a [selector], a colon and then a set rule. The most
rule. The most basic form of selector is an basic form of selector is an [element function]($function/#element-functions).
[element function]($function/#element-functions). This lets the set rule only This lets the set rule only apply to the selected element. In the example below,
apply to the selected element. In the example below, headings become dark blue headings become dark blue while all other text stays black.
while all other text stays black.
```example ```example
#show heading: set text(navy) #show heading: set text(navy)
@ -79,11 +78,11 @@ With show-set rules you can mix and match properties from different functions to
achieve many different effects. But they still limit you to what is predefined achieve many different effects. But they still limit you to what is predefined
in Typst. For maximum flexibility, you can instead write a show rule that in Typst. For maximum flexibility, you can instead write a show rule that
defines how to format an element from scratch. To write such a show rule, defines how to format an element from scratch. To write such a show rule,
replace the set rule after the colon with an arbitrary [function]($function). replace the set rule after the colon with an arbitrary [function]. This function
This function receives the element in question and can return arbitrary content. receives the element in question and can return arbitrary content. The available
The available [fields]($scripting/#fields) on the element passed to the function [fields]($scripting/#fields) on the element passed to the function again match
again match the parameters of the respective element function. Below, we define the parameters of the respective element function. Below, we define a show rule
a show rule that formats headings for a fantasy encyclopedia. that formats headings for a fantasy encyclopedia.
```example ```example
#set heading(numbering: "(I)") #set heading(numbering: "(I)")

View File

@ -36,20 +36,20 @@ more about their syntax and usage.
| Name | Example | See | | Name | Example | See |
| ------------------ | ------------------------ | ---------------------------- | | ------------------ | ------------------------ | ---------------------------- |
| Paragraph break | Blank line | [`parbreak`]($parbreak) | | Paragraph break | Blank line | [`parbreak`] |
| Strong emphasis | `[*strong*]` | [`strong`]($strong) | | Strong emphasis | `[*strong*]` | [`strong`] |
| Emphasis | `[_emphasis_]` | [`emph`]($emph) | | Emphasis | `[_emphasis_]` | [`emph`] |
| Raw text | ``[`print(1)`]`` | [`raw`]($raw) | | Raw text | ``[`print(1)`]`` | [`raw`] |
| Link | `[https://typst.app/]` | [`link`]($link) | | Link | `[https://typst.app/]` | [`link`] |
| Label | `[<intro>]` | [`label`]($label) | | Label | `[<intro>]` | [`label`] |
| Reference | `[@intro]` | [`ref`]($ref) | | Reference | `[@intro]` | [`ref`] |
| Heading | `[= Heading]` | [`heading`]($heading) | | Heading | `[= Heading]` | [`heading`] |
| Bullet list | `[- item]` | [`list`]($list) | | Bullet list | `[- item]` | [`list`] |
| Numbered list | `[+ item]` | [`enum`]($enum) | | Numbered list | `[+ item]` | [`enum`] |
| Term list | `[/ Term: description]` | [`terms`]($terms) | | Term list | `[/ Term: description]` | [`terms`] |
| Math | `[$x^2$]` | [Math]($category/math) | | Math | `[$x^2$]` | [Math]($category/math) |
| Line break | `[\]` | [`linebreak`]($linebreak) | | Line break | `[\]` | [`linebreak`] |
| Smart quote | `['single' or "double"]` | [`smartquote`]($smartquote) | | Smart quote | `['single' or "double"]` | [`smartquote`] |
| Symbol shorthand | `[~, ---]` | [Symbols]($category/symbols/sym) | | Symbol shorthand | `[~, ---]` | [Symbols]($category/symbols/sym) |
| Code expression | `[#rect(width: 1cm)]` | [Scripting]($scripting/#expressions) | | Code expression | `[#rect(width: 1cm)]` | [Scripting]($scripting/#expressions) |
| Character escape | `[Tweet at us \#ad]` | [Below](#escapes) | | Character escape | `[Tweet at us \#ad]` | [Below](#escapes) |
@ -70,7 +70,7 @@ follows:
| Bottom attachment | `[$x_1$]` | [`attach`]($category/math/attach) | | Bottom attachment | `[$x_1$]` | [`attach`]($category/math/attach) |
| Top attachment | `[$x^2$]` | [`attach`]($category/math/attach) | | Top attachment | `[$x^2$]` | [`attach`]($category/math/attach) |
| Fraction | `[$1 + (a+b)/5$]` | [`frac`]($math.frac) | | Fraction | `[$1 + (a+b)/5$]` | [`frac`]($math.frac) |
| Line break | `[$x \ y$]` | [`linebreak`]($linebreak) | | Line break | `[$x \ y$]` | [`linebreak`] |
| Alignment point | `[$x &= 2 \ &= 3$]` | [Math]($category/math) | | Alignment point | `[$x &= 2 \ &= 3$]` | [Math]($category/math) |
| Variable access | `[$#x$, $pi$]` | [Math]($category/math) | | Variable access | `[$#x$, $pi$]` | [Math]($category/math) |
| Field access | `[$arrow.r.long$]` | [Scripting]($scripting/#fields) | | Field access | `[$arrow.r.long$]` | [Scripting]($scripting/#fields) |

View File

@ -5,10 +5,10 @@ description: |
--- ---
# Reference # Reference
This reference documentation is a comprehensive guide to all of Typst's This reference documentation is a comprehensive guide to all of Typst's syntax,
syntax, concepts, types, and functions. If you are completely new to Typst, we concepts, types, and functions. If you are completely new to Typst, we recommend
recommend starting with the [tutorial]($tutorial) and then coming back to starting with the [tutorial] and then coming back to the reference to learn more
the reference to learn more about Typst's features as you need them. about Typst's features as you need them.
## Language ## Language
The reference starts with a language part that gives an overview over The reference starts with a language part that gives an overview over

View File

@ -12,7 +12,7 @@ this roadmap will only list larger, more fundamental ones.
Are you missing something on the roadmap? Typst relies on your feedback as a Are you missing something on the roadmap? Typst relies on your feedback as a
user to plan for and prioritize new features. Get started by filing a new issue user to plan for and prioritize new features. Get started by filing a new issue
on [GitHub](https://github.com/typst/typst/issues) or discuss your feature on [GitHub](https://github.com/typst/typst/issues) or discuss your feature
request with the [community]($community). request with the [community].
## Language and Compiler ## Language and Compiler
- **Structure and Styling** - **Structure and Styling**

View File

@ -59,9 +59,27 @@ impl Html {
| md::Options::ENABLE_STRIKETHROUGH | md::Options::ENABLE_STRIKETHROUGH
| md::Options::ENABLE_HEADING_ATTRIBUTES; | md::Options::ENABLE_HEADING_ATTRIBUTES;
// Convert `[foo]` to `[foo]($foo)`.
let mut link = |broken: md::BrokenLink| {
assert_eq!(
broken.link_type,
md::LinkType::Shortcut,
"unsupported link type: {:?}",
broken.link_type,
);
Some((
format!("${}", broken.reference.trim_matches('`')).into(),
broken.reference.into_string().into(),
))
};
let ids = Arena::new(); let ids = Arena::new();
let mut handler = Handler::new(text, resolver, nesting, &ids); let mut handler = Handler::new(text, resolver, nesting, &ids);
let mut events = md::Parser::new_ext(text, options).peekable(); let mut events =
md::Parser::new_with_broken_link_callback(text, options, Some(&mut link))
.peekable();
let iter = std::iter::from_fn(|| loop { let iter = std::iter::from_fn(|| loop {
let mut event = events.next()?; let mut event = events.next()?;
handler.peeked = events.peek().and_then(|event| match event { handler.peeked = events.peek().and_then(|event| match event {
@ -199,7 +217,13 @@ impl<'a> Handler<'a> {
// Rewrite links. // Rewrite links.
md::Event::Start(md::Tag::Link(ty, dest, _)) => { md::Event::Start(md::Tag::Link(ty, dest, _)) => {
assert!( assert!(
matches!(ty, md::LinkType::Inline | md::LinkType::Reference), matches!(
ty,
md::LinkType::Inline
| md::LinkType::Reference
| md::LinkType::ShortcutUnknown
| md::LinkType::Autolink
),
"unsupported link type: {ty:?}", "unsupported link type: {ty:?}",
); );

View File

@ -92,7 +92,8 @@ pub fn provide(resolver: &dyn Resolver) -> Vec<PageModel> {
/// Resolve consumer dependencies. /// Resolve consumer dependencies.
pub trait Resolver { pub trait Resolver {
/// Try to resolve a link that the system cannot resolve itself. /// Try to resolve a link. If this returns `None`, the system will try to
/// resolve the link itself.
fn link(&self, link: &str) -> Option<String>; fn link(&self, link: &str) -> Option<String>;
/// Produce an URL for an image file. /// Produce an URL for an image file.

View File

@ -85,7 +85,7 @@ and emphasized text, respectively. However, having a special symbol for
everything we want to insert into our document would soon become cryptic and everything we want to insert into our document would soon become cryptic and
unwieldy. For this reason, Typst reserves markup symbols only for the most unwieldy. For this reason, Typst reserves markup symbols only for the most
common things. Everything else is inserted with _functions._ For our image to common things. Everything else is inserted with _functions._ For our image to
show up on the page, we use Typst's [`image`]($image) function. show up on the page, we use Typst's [`image`] function.
```example ```example
#image("glacier.jpg") #image("glacier.jpg")
@ -116,9 +116,9 @@ page's width. We also could have specified an absolute value like `{1cm}` or
`{0.7in}`. `{0.7in}`.
Just like text, the image is now aligned at the left side of the page by Just like text, the image is now aligned at the left side of the page by
default. It's also lacking a caption. Let's fix that by using the default. It's also lacking a caption. Let's fix that by using the [figure]
[figure]($figure) function. This function takes the figure's contents as a function. This function takes the figure's contents as a positional argument and
positional argument and an optional caption as a named argument. an optional caption as a named argument.
Within the argument list of the `figure` function, Typst is already in code Within the argument list of the `figure` function, Typst is already in code
mode. This means, you now have to remove the hash before the image function call. mode. This means, you now have to remove the hash before the image function call.
@ -178,8 +178,8 @@ valid kind of content.
## Adding a bibliography { #bibliography } ## Adding a bibliography { #bibliography }
As you write up your report, you need to back up some of your claims. You can As you write up your report, you need to back up some of your claims. You can
add a bibliography to your document with the [`bibliography`]($bibliography) add a bibliography to your document with the [`bibliography`] function. This
function. This function expects a path to a bibliography file. function expects a path to a bibliography file.
Typst's native bibliography format is Typst's native bibliography format is
[Hayagriva](https://github.com/typst/hayagriva/blob/main/docs/file-format.md), [Hayagriva](https://github.com/typst/hayagriva/blob/main/docs/file-format.md),
@ -300,8 +300,7 @@ emphasize text, write lists, insert images, align content, and typeset
mathematical expressions. You also learned about Typst's functions. There are mathematical expressions. You also learned about Typst's functions. There are
many more kinds of content that Typst lets you insert into your document, such many more kinds of content that Typst lets you insert into your document, such
as [tables]($table), [shapes]($category/visualize), and [code blocks]($raw). You as [tables]($table), [shapes]($category/visualize), and [code blocks]($raw). You
can peruse the [reference]($reference) to learn more about these and other can peruse the [reference] to learn more about these and other features.
features.
For the moment, you have completed writing your report. You have already saved a For the moment, you have completed writing your report. You have already saved a
PDF by clicking on the download button in the top right corner. However, you PDF by clicking on the download button in the top right corner. However, you

View File

@ -11,11 +11,10 @@ your report using Typst's styling system.
## Set rules ## Set rules
As we have seen in the previous chapter, Typst has functions that _insert_ As we have seen in the previous chapter, Typst has functions that _insert_
content (e.g. the [`image`]($image) function) and others that _manipulate_ content (e.g. the [`image`] function) and others that _manipulate_ content that
content that they received as arguments (e.g. the [`align`]($align) function). they received as arguments (e.g. the [`align`] function). The first impulse you
The first impulse you might have when you want, for example, to justify the might have when you want, for example, to justify the report, could be to look
report, could be to look for a function that does that and wrap the complete for a function that does that and wrap the complete document in it.
document in it.
```example ```example
#par(justify: true)[ #par(justify: true)[
@ -38,9 +37,9 @@ do in Typst, there is special syntax for it: Instead of putting the content
inside of the argument list, you can write it in square brackets directly after inside of the argument list, you can write it in square brackets directly after
the normal arguments, saving on punctuation. the normal arguments, saving on punctuation.
As seen above, that works. The [`par`]($par) function justifies all paragraphs As seen above, that works. The [`par`] function justifies all paragraphs within
within it. However, wrapping the document in countless functions and applying it. However, wrapping the document in countless functions and applying styles
styles selectively and in-situ can quickly become cumbersome. selectively and in-situ can quickly become cumbersome.
Fortunately, Typst has a more elegant solution. With _set rules,_ you can apply Fortunately, Typst has a more elegant solution. With _set rules,_ you can apply
style properties to all occurrences of some kind of content. You write a set style properties to all occurrences of some kind of content. You write a set
@ -89,13 +88,12 @@ Back to set rules: When writing a rule, you choose the function depending on
what type of element you want to style. Here is a list of some functions that what type of element you want to style. Here is a list of some functions that
are commonly used in set rules: are commonly used in set rules:
- [`text`]($text) to set font family, size, color, and other properties of text - [`text`] to set font family, size, color, and other properties of text
- [`page`]($page) to set the page size, margins, headers, enable columns, and - [`page`] to set the page size, margins, headers, enable columns, and footers
footers - [`par`] to justify paragraphs, set line spacing, and more
- [`par`]($par) to justify paragraphs, set line spacing, and more - [`heading`] to set the appearance of headings and enable numbering
- [`heading`]($heading) to set the appearance of headings and enable numbering - [`document`] to set the metadata contained in the PDF output, such as title
- [`document`]($document) to set the metadata contained in the PDF output, such and author
as title and author
Not all function parameters can be set. In general, only parameters that tell Not all function parameters can be set. In general, only parameters that tell
a function _how_ to do something can be set, not those that tell it _what_ to a function _how_ to do something can be set, not those that tell it _what_ to
@ -149,24 +147,24 @@ behaviour of these natural structures.
There are a few things of note here. There are a few things of note here.
First is the [`page`]($page) set rule. It receives two arguments: the page size First is the [`page`] set rule. It receives two arguments: the page size and
and margins for the page. The page size is a string. Typst accepts margins for the page. The page size is a string. Typst accepts [many standard
[many standard page sizes,]($page.paper) but you can also specify a custom page page sizes,]($page.paper) but you can also specify a custom page size. The
size. The margins are specified as a [dictionary.]($dictionary) Dictionaries are margins are specified as a [dictionary.]($dictionary) Dictionaries are a
a collection of key-value pairs. In this case, the keys are `x` and `y`, and the collection of key-value pairs. In this case, the keys are `x` and `y`, and the
values are the horizontal and vertical margins, respectively. We could also have values are the horizontal and vertical margins, respectively. We could also have
specified separate margins for each side by passing a dictionary with the keys specified separate margins for each side by passing a dictionary with the keys
`{left}`, `{right}`, `{top}`, and `{bottom}`. `{left}`, `{right}`, `{top}`, and `{bottom}`.
Next is the set [`text`]($text) set rule. Here, we set the font size to `{10pt}` Next is the set [`text`] set rule. Here, we set the font size to `{10pt}` and
and font family to `{"New Computer Modern"}`. The Typst app comes with many font family to `{"New Computer Modern"}`. The Typst app comes with many fonts
fonts that you can try for your document. When you are in the text function's that you can try for your document. When you are in the text function's argument
argument list, you can discover the available fonts in the autocomplete panel. list, you can discover the available fonts in the autocomplete panel.
We have also set the spacing between lines (a.k.a. leading): It is specified as We have also set the spacing between lines (a.k.a. leading): It is specified as
a [length]($length) value, and we used the `em` unit to specify the leading a [length] value, and we used the `em` unit to specify the leading relative to
relative to the size of the font: `{1em}` is equivalent to the current font size the size of the font: `{1em}` is equivalent to the current font size (which
(which defaults to `{11pt}`). defaults to `{11pt}`).
Finally, we have bottom aligned our image by adding a vertical alignment to our Finally, we have bottom aligned our image by adding a vertical alignment to our
center alignment. Vertical and horizontal alignments can be combined with the center alignment. Vertical and horizontal alignments can be combined with the
@ -174,8 +172,7 @@ center alignment. Vertical and horizontal alignments can be combined with the
## A hint of sophistication { #sophistication } ## A hint of sophistication { #sophistication }
To structure our document more clearly, we now want to number our headings. We To structure our document more clearly, we now want to number our headings. We
can do this by setting the `numbering` parameter of the [`heading`]($heading) can do this by setting the `numbering` parameter of the [`heading`] function.
function.
```example ```example
>>> #set text(font: "New Computer Modern") >>> #set text(font: "New Computer Modern")
@ -210,9 +207,9 @@ for our headings:
#lorem(15) #lorem(15)
``` ```
This example also uses the [`lorem`]($lorem) function to generate some This example also uses the [`lorem`] function to generate some placeholder text.
placeholder text. This function takes a number as an argument and generates that This function takes a number as an argument and generates that many words of
many words of _Lorem Ipsum_ text. _Lorem Ipsum_ text.
<div class="info-box"> <div class="info-box">

View File

@ -125,17 +125,17 @@ supervisor, we'll add our own and their name.
) )
``` ```
The two author blocks are laid out next to each other. We use the The two author blocks are laid out next to each other. We use the [`grid`]
[`grid`]($grid) function to create this layout. With a grid, we can control function to create this layout. With a grid, we can control exactly how large
exactly how large each column is and which content goes into which cell. The each column is and which content goes into which cell. The `columns` argument
`columns` argument takes an array of [relative lengths]($relative) or takes an array of [relative lengths]($relative) or [fractions]($fraction). In
[fractions]($fraction). In this case, we passed it two equal fractional sizes, this case, we passed it two equal fractional sizes, telling it to split the
telling it to split the available space into two equal columns. We then passed available space into two equal columns. We then passed two content arguments to
two content arguments to the grid function. The first with our own details, and the grid function. The first with our own details, and the second with our
the second with our supervisors'. We again use the `align` function to center supervisors'. We again use the `align` function to center the content within the
the content within the column. The grid takes an arbitrary number of content column. The grid takes an arbitrary number of content arguments specifying the
arguments specifying the cells. Rows are added automatically, but they can also cells. Rows are added automatically, but they can also be manually sized with
be manually sized with the `rows` argument. the `rows` argument.
Now, let's add the abstract. Remember that the conference wants the abstract to Now, let's add the abstract. Remember that the conference wants the abstract to
be set ragged and centered. be set ragged and centered.
@ -248,11 +248,10 @@ on another title, we can easily change it in one place.
## Adding columns and headings { #columns-and-headings } ## Adding columns and headings { #columns-and-headings }
The paper above unfortunately looks like a wall of lead. To fix that, let's add The paper above unfortunately looks like a wall of lead. To fix that, let's add
some headings and switch our paper to a two-column layout. The some headings and switch our paper to a two-column layout. The [`columns`]
[`columns`]($columns) function takes a number and content, and layouts the function takes a number and content, and layouts the content into the specified
content into the specified number of columns. Since we want everything after the number of columns. Since we want everything after the abstract to be in two
abstract to be in two columns, we need to apply the column function to our whole columns, we need to apply the column function to our whole document.
document.
Instead of wrapping the whole document in a giant function call, we can use an Instead of wrapping the whole document in a giant function call, we can use an
"everything" show rule. To write such a show rule, put a colon directly behind "everything" show rule. To write such a show rule, put a colon directly behind
@ -386,8 +385,7 @@ function that gets passed the heading as a parameter. That parameter can be used
as content but it also has some fields like `title`, `numbers`, and `level` from as content but it also has some fields like `title`, `numbers`, and `level` from
which we can compose a custom look. Here, we are center-aligning, setting the which we can compose a custom look. Here, we are center-aligning, setting the
font weight to `{"regular"}` because headings are bold by default, and use the font weight to `{"regular"}` because headings are bold by default, and use the
[`smallcaps`]($smallcaps) function to render the heading's title in small [`smallcaps`] function to render the heading's title in small capitals.
capitals.
The only remaining problem is that all headings look the same now. The The only remaining problem is that all headings look the same now. The
"Motivation" and "Problem Statement" subsections ought to be italic run in "Motivation" and "Problem Statement" subsections ought to be italic run in
@ -479,7 +477,8 @@ Let's review the conference's style guide:
- The paper contains a single-column abstract and two-column main text ✓ - The paper contains a single-column abstract and two-column main text ✓
- The abstract should be centered ✓ - The abstract should be centered ✓
- The main text should be justified ✓ - The main text should be justified ✓
- First level section headings should be centered, rendered in small caps and in 13pt ✓ - First level section headings should be centered, rendered in small caps and in
13pt ✓
- Second level headings are run-ins, italicized and have the same size as the - Second level headings are run-ins, italicized and have the same size as the
body text ✓ body text ✓
- Finally, the pages should be US letter sized, numbered in the center and the - Finally, the pages should be US letter sized, numbered in the center and the
@ -496,7 +495,9 @@ the conference! The finished paper looks like this:
## Review ## Review
You have now learned how to create headers and footers, how to use functions and You have now learned how to create headers and footers, how to use functions and
scopes to locally override styles, how to create more complex layouts with the [`grid`]($grid) function and how to write show rules for individual functions, and the whole document. You also learned how to use the scopes to locally override styles, how to create more complex layouts with the
[`grid`] function and how to write show rules for individual functions, and the
whole document. You also learned how to use the
[`where` selector]($styling/#show-rules) to filter the headings by their level. [`where` selector]($styling/#show-rules) to filter the headings by their level.
The paper was a great success! You've met a lot of like-minded researchers at The paper was a great success! You've met a lot of like-minded researchers at

View File

@ -195,17 +195,17 @@ Next, we copy the code that generates title, abstract and authors from the
previous chapter into the template, replacing the fixed details with the previous chapter into the template, replacing the fixed details with the
parameters. parameters.
The new `authors` parameter expects an [array]($array) of The new `authors` parameter expects an [array] of [dictionaries]($dictionary)
[dictionaries]($dictionary) with the keys `name`, `affiliation` and `email`. with the keys `name`, `affiliation` and `email`. Because we can have an
Because we can have an arbitrary number of authors, we dynamically determine if arbitrary number of authors, we dynamically determine if we need one, two or
we need one, two or three columns for the author list. First, we determine the three columns for the author list. First, we determine the number of authors
number of authors using the [`.len()`]($array.len) method on the `authors` using the [`.len()`]($array.len) method on the `authors` array. Then, we set the
array. Then, we set the number of columns as the minimum of this count and number of columns as the minimum of this count and three, so that we never
three, so that we never create more than three columns. If there are more than create more than three columns. If there are more than three authors, a new row
three authors, a new row will be inserted instead. For this purpose, we have will be inserted instead. For this purpose, we have also added a `row-gutter`
also added a `row-gutter` parameter to the `grid` function. Otherwise, the rows parameter to the `grid` function. Otherwise, the rows would be too close
would be too close together. To extract the details about the authors from the together. To extract the details about the authors from the dictionary, we use
dictionary, we use the [field access syntax]($scripting/#fields). the [field access syntax]($scripting/#fields).
We still have to provide an argument to the grid for each author: Here is where We still have to provide an argument to the grid for each author: Here is where
the array's [`map` method]($array.map) comes in handy. It takes a function as an the array's [`map` method]($array.map) comes in handy. It takes a function as an