Tweak docs (#5089)

This commit is contained in:
Laurenz 2024-10-03 15:20:48 +02:00 committed by GitHub
parent 0343e038d3
commit cbd251f474
No known key found for this signature in database
GPG Key ID: B5690EEEBB952194
30 changed files with 375 additions and 201 deletions

View File

@ -913,7 +913,11 @@ impl Array {
/// If the same key occurs multiple times, the last value is selected.
///
/// ```example
/// (("apples", 2), ("peaches", 3), ("apples", 5)).to-dict()
/// #(
/// ("apples", 2),
/// ("peaches", 3),
/// ("apples", 5),
/// ).to-dict()
/// ```
#[func]
pub fn to_dict(self) -> StrResult<Dict> {
@ -938,14 +942,15 @@ impl Array {
/// Reduces the elements to a single one, by repeatedly applying a reducing
/// operation.
///
/// If the array is empty, returns `none`, otherwise, returns the
/// result of the reduction.
/// If the array is empty, returns `{none}`, otherwise, returns the result
/// of the reduction.
///
/// The reducing function is a closure with two arguments: an 'accumulator', and an element.
/// The reducing function is a closure with two arguments: an "accumulator",
/// and an element.
///
/// For arrays with at least one element, this is the same as `array.fold`
/// with the first element of the array as the initial accumulator value, folding
/// every subsequent element into it.
/// For arrays with at least one element, this is the same as [`array.fold`]
/// with the first element of the array as the initial accumulator value,
/// folding every subsequent element into it.
#[func]
pub fn reduce(
self,

View File

@ -12,63 +12,81 @@ use crate::World;
/// A fixed-point decimal number type.
///
/// This type should be used when highly precise arithmetic operations are
/// needed, such as for finance. Typical operations between `{decimal}`
/// numbers, such as addition, multiplication, and [power]($calc.pow) to an
/// integer, will be highly precise due to their fixed-point representation.
/// Note, however, that multiplication and division may not preserve all digits
/// in some edge cases: while they are considered precise, digits past the
/// limits specified below are rounded off and lost, so some loss of precision
/// beyond the maximum representable digits is possible. Note that this
/// behavior can be observed not only when dividing, but also when multiplying
/// by numbers between 0 and 1, as both operations can push a number's
/// fractional digits beyond the limits described below, leading to rounding.
/// When those two operations do not surpass the digit limits, they are fully
/// precise.
///
/// # Limits
/// A `{decimal}` number has a limit of 28 to 29 significant base-10 digits.
/// This includes the sum of digits before and after the decimal point. As
/// such, numbers with more fractional digits have a smaller range. The maximum
/// and minimum `{decimal}` numbers have a value of
/// `{79228162514264337593543950335}` and `{-79228162514264337593543950335}`
/// respectively. In contrast with [`{float}`]($float), this type does not
/// support infinity or NaN, so overflowing or underflowing operations will
/// raise an error.
///
/// # Construction and casts
/// To create a decimal number, use the `{decimal(string)}` constructor, such
/// as with `{decimal("3.141592653")}` **(note the double quotes!)**. This
/// constructor preserves all given fractional digits, provided they are
/// representable as per the limits above (otherwise, an error is raised). One
/// may also convert any [integer]($int) to a decimal with the
/// `{decimal(int)}` constructor, e.g. `{decimal(59)}`. However, note that
/// constructing a decimal from a [floating-point number]($float), while
/// supported, **is an imprecise conversion and therefore discouraged.** A
/// warning will be raised if Typst detects that there was an accidental
/// `{float}` to `{decimal}` cast through its constructor (e.g. if writing
/// `{decimal(3.14)}` - note the lack of double quotes, indicating this is
/// an accidental `{float}` cast and therefore imprecise). The precision of a
/// `{float}` to `{decimal}` cast can be slightly improved by rounding the
/// result to 15 digits with [`calc.round`]($calc.round), but there are still
/// no precision guarantees for that kind of conversion.
///
/// In order to guard against accidental loss of precision, built-in operations
/// between `{float}` and `{decimal}` are not supported and will raise an
/// error. Certain `calc` functions, such as trigonometric functions and power
/// between two real numbers, are also only supported for `{float}` (although
/// raising `{decimal}` to integer exponents is supported). You can opt into
/// potentially imprecise operations with the `{float(decimal)}` constructor,
/// which casts the `{decimal}` number into a `{float}`, allowing for
/// operations without precision guarantees.
/// This type should be used for precise arithmetic operations on numbers
/// represented in base 10. A typical use case is representing currency.
///
/// # Example
/// ```example
/// #decimal("3.14159265358979323846264338") \
/// #(decimal("0.000000000000000000001") + decimal("0.000000000000000000002"))
/// #(decimal("0.00002") * decimal("49.25652565")) \
/// #(decimal("1") / 2048)
/// Decimal: #(decimal("0.1") + decimal("0.2")) \
/// Float: #(0.1 + 0.2)
/// ```
///
/// # Construction and casts
/// To create a decimal number, use the `{decimal(string)}` constructor, such as
/// in `{decimal("3.141592653")}` **(note the double quotes!)**. This
/// constructor preserves all given fractional digits, provided they are
/// representable as per the limits specified below (otherwise, an error is
/// raised).
///
/// You can also convert any [integer]($int) to a decimal with the
/// `{decimal(int)}` constructor, e.g. `{decimal(59)}`. However, note that
/// constructing a decimal from a [floating-point number]($float), while
/// supported, **is an imprecise conversion and therefore discouraged.** A
/// warning will be raised if Typst detects that there was an accidental `float`
/// to `decimal` cast through its constructor (e.g. if writing `{decimal(3.14)}`
/// - note the lack of double quotes, indicating this is an accidental `float`
/// cast and therefore imprecise).
///
/// The precision of a `float` to `decimal` cast can be slightly improved by
/// rounding the result to 15 digits with [`calc.round`]($calc.round), but there
/// are still no precision guarantees for that kind of conversion.
///
/// # Operations
/// Basic arithmetic operations are supported on two decimals and on pairs of
/// decimals and integers.
///
/// Built-in operations between `float` and `decimal` are not supported in order
/// to guard against accidental loss of precision. They will raise an error
/// instead.
///
/// Certain `calc` functions, such as trigonometric functions and power between
/// two real numbers, are also only supported for `float` (although raising
/// `decimal` to integer exponents is supported). You can opt into potentially
/// imprecise operations with the `{float(decimal)}` constructor, which casts
/// the `decimal` number into a `float`, allowing for operations without
/// precision guarantees.
///
/// # Displaying decimals
/// To display a decimal, simply insert the value into the document. To only
/// display a certain number of digits, [round]($calc.round) the decimal first.
/// Localized formatting of decimals and other numbers is not yet supported, but
/// planned for the future.
///
/// You can convert decimals to strings using the [`str`] constructor. This way,
/// you can post-process the displayed representation, e.g. to replace the
/// period with a comma (as a stand-in for proper built-in localization to
/// languages that use the comma).
///
/// # Precision and limits
/// A `decimal` number has a limit of 28 to 29 significant base-10 digits. This
/// includes the sum of digits before and after the decimal point. As such,
/// numbers with more fractional digits have a smaller range. The maximum and
/// minimum `decimal` numbers have a value of `{79228162514264337593543950335}`
/// and `{-79228162514264337593543950335}` respectively. In contrast with
/// [`float`], this type does not support infinity or NaN, so overflowing or
/// underflowing operations will raise an error.
///
/// Typical operations between `decimal` numbers, such as addition,
/// multiplication, and [power]($calc.pow) to an integer, will be highly precise
/// due to their fixed-point representation. Note, however, that multiplication
/// and division may not preserve all digits in some edge cases: while they are
/// considered precise, digits past the limits specified below are rounded off
/// and lost, so some loss of precision beyond the maximum representable digits
/// is possible. Note that this behavior can be observed not only when dividing,
/// but also when multiplying by numbers between 0 and 1, as both operations can
/// push a number's fractional digits beyond the limits described below, leading
/// to rounding. When those two operations do not surpass the digit limits, they
/// are fully precise.
#[ty(scope, cast)]
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct Decimal(rust_decimal::Decimal);
@ -216,26 +234,27 @@ impl Decimal {
#[scope]
impl Decimal {
/// Converts a value to a `{decimal}`.
/// Converts a value to a `decimal`.
///
/// It is recommended to use a string to construct the decimal number, or
/// an [integer]($int) (if desired). The string must contain a number in
/// the format `"3.14159"` (or `"-3.141519"` for negative numbers). The
/// fractional digits are fully preserved; if that's not possible due to
/// the limit of significant digits (around 28 to 29) having been reached,
/// an error is raised as the given decimal number wouldn't be
/// representable. For example, `{decimal("1.222222222222222")}` is a valid
/// decimal number.
/// It is recommended to use a string to construct the decimal number, or an
/// [integer]($int) (if desired). The string must contain a number in the
/// format `{"3.14159"}` (or `{"-3.141519"}` for negative numbers). The
/// fractional digits are fully preserved; if that's not possible due to the
/// limit of significant digits (around 28 to 29) having been reached, an
/// error is raised as the given decimal number wouldn't be representable.
///
/// While this constructor can be used with
/// [floating-point numbers]($float) to cast them to `{decimal}`, doing so
/// is **discouraged** as **this cast is inherently imprecise.** It is easy
/// to accidentally perform this cast by writing `{decimal(1.234)}` (note
/// the lack of double quotes), which is why Typst will emit a warning in
/// that case. Please write `{decimal("1.234")}` instead for that
/// particular case (initialization of a constant decimal). Also note that
/// floats equal to NaN and infinity cannot be cast to decimals and will
/// raise an error.
/// While this constructor can be used with [floating-point numbers]($float)
/// to cast them to `decimal`, doing so is **discouraged** as **this cast is
/// inherently imprecise.** It is easy to accidentally perform this cast by
/// writing `{decimal(1.234)}` (note the lack of double quotes), which is
/// why Typst will emit a warning in that case. Please write
/// `{decimal("1.234")}` instead for that particular case (initialization of
/// a constant decimal). Also note that floats equal to NaN and infinity
/// cannot be cast to decimals and will raise an error.
///
/// ```example
/// #decimal("1.222222222222222")
/// ```
#[func(constructor)]
pub fn construct(
engine: &mut Engine,

View File

@ -35,8 +35,11 @@ use crate::utils::PicoStr;
/// the heading and thus attaches to the heading's text.
///
/// ```typ
/// = Intro <a> // Equivalent to `#heading[Intro] <a>`.
/// = Concl #label("b") // Equivalent to `#heading[Concl #label("b")]`.
/// // Equivalent to `#heading[Introduction] <a>`.
/// = Introduction <a>
///
/// // Equivalent to `#heading[Conclusion #label("b")]`.
/// = Conclusion #label("b")
/// ```
///
/// Currently, labels can only be attached to elements in markup mode, not in

View File

@ -14,7 +14,9 @@ use crate::text::TextElem;
/// Aligns content horizontally and vertically.
///
/// # Example
/// Let's start with centering our content horizontally:
/// ```example
/// #set page(height: 120pt)
/// #set align(center)
///
/// Centered text, a sight to see \
@ -22,6 +24,46 @@ use crate::text::TextElem;
/// Not left nor right, it stands alone \
/// A work of art, a visual throne
/// ```
///
/// To center something vertically, use _horizon_ alignment:
/// ```example
/// #set page(height: 120pt)
/// #set align(horizon)
///
/// Vertically centered, \
/// the stage had entered, \
/// a new paragraph.
/// ```
///
/// # Combining alignments
/// You can combine two alignments with the `+` operator. Let's also only apply
/// this to one piece of content by using the function form instead of a set
/// rule:
/// ```example
/// #set page(height: 120pt)
/// Though left in the beginning ...
///
/// #align(right + bottom)[
/// ... they were right in the end, \
/// and with addition had gotten, \
/// the paragraph to the bottom!
/// ]
/// ```
///
/// # Nested alignment
/// You can use varying alignments for layout containers and the elements within
/// them. This way, you can create intricate layouts:
///
/// ```example
/// #align(center, block[
/// #set align(left)
/// Though centered together \
/// alone \
/// we \
/// are \
/// left.
/// ])
/// ```
#[elem(Show)]
pub struct AlignElem {
/// The [alignment] along both axes.

View File

@ -423,6 +423,16 @@ pub struct BlockElem {
/// at the bottom of the page.
///
/// Marking a block as sticky makes it unbreakable.
///
/// ```example
/// >>> #set page(height: 140pt)
/// // Disable stickiness of headings.
/// #show heading: set block(sticky: false)
/// #lorem(20)
///
/// = Chapter
/// #lorem(10)
/// ```
#[default(false)]
pub sticky: bool,

View File

@ -170,11 +170,15 @@ pub struct GridElem {
/// The gaps between rows and columns.
///
/// If there are more gutters than defined sizes, the last gutter is repeated.
/// If there are more gutters than defined sizes, the last gutter is
/// repeated.
///
/// This is a shorthand to set `column-gutter` and `row-gutter` to the same
/// value.
#[external]
pub gutter: TrackSizings,
/// The gaps between columns. Takes precedence over `gutter`.
/// The gaps between columns.
#[parse(
let gutter = args.named("gutter")?;
args.named("column-gutter")?.or_else(|| gutter.clone())
@ -182,7 +186,7 @@ pub struct GridElem {
#[borrowed]
pub column_gutter: TrackSizings,
/// The gaps between rows. Takes precedence over `gutter`.
/// The gaps between rows.
#[parse(args.named("row-gutter")?.or_else(|| gutter.clone()))]
#[borrowed]
pub row_gutter: TrackSizings,

View File

@ -30,6 +30,10 @@ use crate::syntax::Span;
/// ])
/// ```
///
/// Note that the `layout` function forces its contents into a [block]-level
/// container, so placement relative to the page or pagebreaks are not possible
/// within it.
///
/// If the `layout` call is placed inside a box with a width of `{800pt}` and a
/// height of `{400pt}`, then the specified function will be given the argument
/// `{(width: 800pt, height: 400pt)}`. If it is placed directly into the page, it

View File

@ -45,17 +45,15 @@ pub struct PadElem {
#[parse(args.named("bottom")?.or(y))]
pub bottom: Rel<Length>,
/// The horizontal padding. Both `left` and `right` take precedence over
/// this.
/// A shorthand to set `left` and `right` to the same value.
#[external]
pub x: Rel<Length>,
/// The vertical padding. Both `top` and `bottom` take precedence over this.
/// A shorthand to set `top` and `bottom` to the same value.
#[external]
pub y: Rel<Length>,
/// The padding for all sides. All other parameters take precedence over
/// this.
/// A shorthand to set all four sides to the same value.
#[external]
pub rest: Rel<Length>,

View File

@ -41,9 +41,11 @@ use crate::visualize::{Color, Paint};
#[elem(Construct)]
pub struct PageElem {
/// A standard paper size to set width and height.
///
/// This is just a shorthand for setting `width` and `height` and, as such,
/// cannot be retrieved in a context expression.
#[external]
#[default(Paper::A4)]
#[ghost]
pub paper: Paper,
/// The width of the page.

View File

@ -39,8 +39,7 @@ use crate::layout::{Alignment, Em, Length, Rel};
/// )
/// ```
///
/// # Effect on the position of other elements
///
/// # Effect on the position of other elements { #effect-on-other-elements }
/// Overlaid elements don't take space in the flow of content, but a `place`
/// call inserts an invisible block-level element in the flow. This can
/// affect the layout by breaking the current paragraph. To avoid this,
@ -53,6 +52,7 @@ use crate::layout::{Alignment, Em, Length, Rel};
/// to the following word:
///
/// ```example
/// >>> #set page(height: 70pt)
/// #let annotate(..args) = {
/// box(place(..args))
/// sym.zwj
@ -64,7 +64,7 @@ use crate::layout::{Alignment, Em, Length, Rel};
/// ```
///
/// The zero-width weak spacing serves to discard spaces between the function
/// call and the next word in markup.
/// call and the next word.
#[elem(scope)]
pub struct PlaceElem {
/// Relative to which position in the parent container to place the content.
@ -89,6 +89,18 @@ pub struct PlaceElem {
///
/// Note that parent-scoped placement is currently only supported if `float`
/// is `{true}`. This may change in the future.
///
/// ```example
/// #set page(height: 150pt, columns: 2)
/// #place(
/// top + center,
/// scope: "parent",
/// float: true,
/// rect(width: 80%, fill: aqua),
/// )
///
/// #lorem(25)
/// ```
pub scope: PlacementScope,
/// Whether the placed element has floating layout.
@ -174,24 +186,18 @@ pub enum PlacementScope {
/// into the next section.
///
/// ```example
/// #set page(height: 165pt, width: 150pt)
///
/// Some introductory text: #lorem(15)
/// >>> #set page(height: 160pt, width: 150pt)
/// #lorem(15)
///
/// #figure(
/// rect(
/// width: 100%,
/// height: 64pt,
/// [I float with a caption!],
/// ),
/// rect(width: 100%, height: 50pt),
/// placement: auto,
/// caption: [A self-describing figure],
/// caption: [A rectangle],
/// )
///
/// #place.flush()
///
/// Some conclusive text that must occur
/// after the figure.
/// This text appears after the figure.
/// ```
#[elem]
pub struct FlushElem {}

View File

@ -182,6 +182,14 @@ fn layout_rotate(
/// ```
#[elem(Show)]
pub struct ScaleElem {
/// The scaling factor for both axes, as a positional argument. This is just
/// an optional shorthand notation for setting `x` and `y` to the same
/// value.
#[external]
#[positional]
#[default(Smart::Custom(ScaleAmount::Ratio(Ratio::one())))]
pub factor: Smart<ScaleAmount>,
/// The horizontal scaling factor.
///
/// The body will be mirrored horizontally if the parameter is negative.
@ -342,7 +350,9 @@ cast! {
///
/// # Example
/// ```example
/// #skew(ax: -12deg)[This is some fake italic text.]
/// #skew(ax: -12deg)[
/// This is some fake italic text.
/// ]
/// ```
#[elem(Show)]
pub struct SkewElem {

View File

@ -167,6 +167,8 @@ pub struct MatElem {
/// The gap between rows and columns.
///
/// This is a shorthand to set `row-gap` and `column-gap` to the same value.
///
/// ```example
/// #set math.mat(gap: 1em)
/// $ mat(1, 2; 3, 4) $
@ -174,7 +176,7 @@ pub struct MatElem {
#[external]
pub gap: Rel<Length>,
/// The gap between rows. Takes precedence over `gap`.
/// The gap between rows.
///
/// ```example
/// #set math.mat(row-gap: 1em)
@ -188,7 +190,7 @@ pub struct MatElem {
#[default(DEFAULT_ROW_GAP.into())]
pub row_gap: Rel<Length>,
/// The gap between columns. Takes precedence over `gap`.
/// The gap between columns.
///
/// ```example
/// #set math.mat(column-gap: 1em)

View File

@ -33,7 +33,8 @@ pub struct StretchElem {
#[required]
pub body: Content,
/// The size to stretch to, relative to the glyph's current size.
/// The size to stretch to, relative to the maximum size of the glyph and
/// its attachments.
pub size: Smart<Rel<Length>>,
}

View File

@ -9,7 +9,7 @@ use crate::utils::LazyHash;
/// ```example
/// $ bold(A) := B^+ $
/// ```
#[func]
#[func(keywords = ["mathbf"])]
pub fn bold(
/// The content to style.
body: Content,
@ -22,7 +22,7 @@ pub fn bold(
/// ```example
/// $ upright(A) != A $
/// ```
#[func]
#[func(keywords = ["mathup"])]
pub fn upright(
/// The content to style.
body: Content,
@ -33,7 +33,7 @@ pub fn upright(
/// Italic font style in math.
///
/// For roman letters and greek lowercase letters, this is already the default.
#[func]
#[func(keywords = ["mathit"])]
pub fn italic(
/// The content to style.
body: Content,
@ -44,7 +44,7 @@ pub fn italic(
/// Serif (roman) font style in math.
///
/// This is already the default.
#[func]
#[func(keywords = ["mathrm"])]
pub fn serif(
/// The content to style.
body: Content,
@ -57,7 +57,7 @@ pub fn serif(
/// ```example
/// $ sans(A B C) $
/// ```
#[func(title = "Sans Serif")]
#[func(title = "Sans Serif", keywords = ["mathsf"])]
pub fn sans(
/// The content to style.
body: Content,
@ -70,7 +70,28 @@ pub fn sans(
/// ```example
/// Let $cal(P)$ be the set of ...
/// ```
#[func(title = "Calligraphic")]
///
/// This corresponds both to LaTeX's `\mathcal` and `\mathscr` as both of these
/// styles share the same Unicode codepoints. Switching between the styles is
/// thus only possible if supported by the font via
/// [font features]($text.features).
///
/// For the default math font, the roundhand style is available through the
/// `ss01` feature. Therefore, you could define your own version of `\mathscr`
/// like this:
///
/// ```example
/// #let scr(it) = text(
/// features: ("ss01",),
/// box($cal(it)$),
/// )
///
/// We establish $cal(P) != scr(P)$.
/// ```
///
/// (The box is not conceptually necessary, but unfortunately currently needed
/// due to limitations in Typst's text style handling in math.)
#[func(title = "Calligraphic", keywords = ["mathcal", "mathscr"])]
pub fn cal(
/// The content to style.
body: Content,
@ -83,7 +104,7 @@ pub fn cal(
/// ```example
/// $ frak(P) $
/// ```
#[func(title = "Fraktur")]
#[func(title = "Fraktur", keywords = ["mathfrak"])]
pub fn frak(
/// The content to style.
body: Content,
@ -96,7 +117,7 @@ pub fn frak(
/// ```example
/// $ mono(x + y = z) $
/// ```
#[func(title = "Monospace")]
#[func(title = "Monospace", keywords = ["mathtt"])]
pub fn mono(
/// The content to style.
body: Content,
@ -114,7 +135,7 @@ pub fn mono(
/// $ bb(N) = NN $
/// $ f: NN -> RR $
/// ```
#[func(title = "Blackboard Bold")]
#[func(title = "Blackboard Bold", keywords = ["mathbb"])]
pub fn bb(
/// The content to style.
body: Content,
@ -129,7 +150,7 @@ pub fn bb(
/// ```example
/// $sum_i x_i/2 = display(sum_i x_i/2)$
/// ```
#[func(title = "Display Size")]
#[func(title = "Display Size", keywords = ["displaystyle"])]
pub fn display(
/// The content to size.
body: Content,
@ -151,7 +172,7 @@ pub fn display(
/// $ sum_i x_i/2
/// = inline(sum_i x_i/2) $
/// ```
#[func(title = "Inline Size")]
#[func(title = "Inline Size", keywords = ["textstyle"])]
pub fn inline(
/// The content to size.
body: Content,
@ -172,7 +193,7 @@ pub fn inline(
/// ```example
/// $sum_i x_i/2 = script(sum_i x_i/2)$
/// ```
#[func(title = "Script Size")]
#[func(title = "Script Size", keywords = ["scriptstyle"])]
pub fn script(
/// The content to size.
body: Content,
@ -194,7 +215,7 @@ pub fn script(
/// ```example
/// $sum_i x_i/2 = sscript(sum_i x_i/2)$
/// ```
#[func(title = "Script-Script Size")]
#[func(title = "Script-Script Size", keywords = ["scriptscriptstyle"])]
pub fn sscript(
/// The content to size.
body: Content,

View File

@ -83,7 +83,8 @@ pub struct EnumElem {
/// In markup mode, the value of this parameter is determined based on
/// whether items are separated with a blank line. If items directly follow
/// each other, this is set to `{true}`; if items are separated by a blank
/// line, this is set to `{false}`.
/// line, this is set to `{false}`. The markup-defined tightness cannot be
/// overridden with set rules.
///
/// ```example
/// + If an enum has a lot of text, and

View File

@ -133,12 +133,25 @@ pub struct FigureElem {
/// ```
pub placement: Option<Smart<VAlignment>>,
/// Relative to which containing scope something is placed.
/// Relative to which containing scope the figure is placed.
///
/// Set this to `{"parent"}` to create a full-width figure in a two-column
/// document.
///
/// Has no effect if `placement` is `{none}`.
///
/// ```example
/// #set page(height: 250pt, columns: 2)
///
/// = Introduction
/// #figure(
/// placement: bottom,
/// scope: "parent",
/// caption: [A glacier],
/// image("glacier.jpg", width: 60%),
/// )
/// #lorem(60)
/// ```
pub scope: PlacementScope,
/// The figure's caption.

View File

@ -55,7 +55,8 @@ pub struct ListElem {
/// In markup mode, the value of this parameter is determined based on
/// whether items are separated with a blank line. If items directly follow
/// each other, this is set to `{true}`; if items are separated by a blank
/// line, this is set to `{false}`.
/// line, this is set to `{false}`. The markup-defined tightness cannot be
/// overridden with set rules.
///
/// ```example
/// - If a list has a lot of text, and

View File

@ -48,7 +48,7 @@ pub struct ParElem {
/// By setting top edge, bottom edge, and leading, you can also configure a
/// consistent baseline-to-baseline distance. You could, for instance, set
/// the leading to `{1em}`, the top-edge to `{0.8em}`, and the bottom-edge
/// to `-{0.2em}` to get a baseline gap of exactly `{2em}`. The exact
/// to `{-0.2em}` to get a baseline gap of exactly `{2em}`. The exact
/// distribution of the top- and bottom-edge values affects the bounds of
/// the first and last line.
#[resolve]

View File

@ -133,8 +133,9 @@ pub struct TableElem {
#[borrowed]
pub rows: TrackSizings,
/// The gaps between rows and columns. See the [grid documentation]($grid)
/// for more information on gutters.
/// The gaps between rows and columns. This is a shorthand for setting
/// `column-gutter` and `row-gutter` to the same value. See the [grid
/// documentation]($grid) for more information on gutters.
#[external]
pub gutter: TrackSizings,
@ -679,15 +680,17 @@ pub struct TableVLine {
///
/// ```example
/// >>> #set page(width: auto)
/// >>> #show table.cell.where(y: 0): strong
/// >>> #set table(
/// >>> stroke: (x, y) => if y == 0 {
/// >>> (bottom: 0.7pt + black)
/// >>> },
/// >>> align: (x, y) =>
/// >>> if x > 0 { center }
/// >>> else { left }
/// >>> )
/// #show table.cell.where(y: 0): strong
/// #set table(
/// stroke: (x, y) => if y == 0 {
/// (bottom: 0.7pt + black)
/// },
/// align: (x, y) => (
/// if x > 0 { center }
/// else { left }
/// )
/// )
///
/// #table(
/// columns: 3,
/// table.header(

View File

@ -35,7 +35,8 @@ pub struct TermsElem {
/// In markup mode, the value of this parameter is determined based on
/// whether items are separated with a blank line. If items directly follow
/// each other, this is set to `{true}`; if items are separated by a blank
/// line, this is set to `{false}`.
/// line, this is set to `{false}`. The markup-defined tightness cannot be
/// overridden with set rules.
///
/// ```example
/// / Fact: If a term list has a lot

View File

@ -56,6 +56,12 @@ type ThemeArgType = Smart<Option<EcoString>>;
/// also trimmed.
/// ````
///
/// You can also construct a [`raw`] element programmatically from a string (and
/// provide the language tag via the optional [`lang`]($raw.lang) argument).
/// ```example
/// #raw("fn " + "main() {}", lang: "rust")
/// ```
///
/// # Syntax
/// This function also has dedicated syntax. You can enclose text in 1 or 3+
/// backticks (`` ` ``) to make it raw. Two backticks produce empty raw text.

View File

@ -7,17 +7,8 @@ use crate::text::TextElem;
///
/// # Example
/// ```example
/// #set par(justify: true)
/// #set heading(numbering: "I.")
///
/// #show heading: it => {
/// set block(below: 10pt)
/// set text(weight: "regular")
/// align(center, smallcaps(it))
/// }
///
/// = Introduction
/// #lorem(40)
/// Hello \
/// #smallcaps[Hello]
/// ```
///
/// # Smallcaps fonts
@ -33,6 +24,25 @@ use crate::text::TextElem;
///
/// In the future, this function will support synthesizing smallcaps from normal
/// letters, but this is not yet implemented.
///
/// # Smallcaps headings
/// You can use a [show rule]($styling/#show-rules) to apply smallcaps
/// formatting to all your headings. In the example below, we also center-align
/// our headings and disable the standard bold font.
///
/// ```example
/// #set par(justify: true)
/// #set heading(numbering: "I.")
///
/// #show heading: smallcaps
/// #show heading: set align(center)
/// #show heading: set text(
/// weight: "regular"
/// )
///
/// = Introduction
/// #lorem(40)
/// ```
#[elem(title = "Small Capitals", Show)]
pub struct SmallcapsElem {
/// The content to display in small capitals.

View File

@ -34,11 +34,11 @@ use crate::World;
/// A raster or vector graphic.
///
/// Supported formats are PNG, JPEG, GIF and SVG.
/// You can wrap the image in a [`figure`] to give it a number and caption.
///
/// _Note:_ Work on SVG export is ongoing and there might be visual inaccuracies
/// in the resulting PDF. Make sure to double-check embedded SVG images. If you
/// have an issue, also feel free to report it on [GitHub][gh-svg].
/// Like most elements, images are _block-level_ by default and thus do not
/// integrate themselves into adjacent paragraphs. To force an image to become
/// inline, put it into a [`box`].
///
/// # Example
/// ```example
@ -50,8 +50,6 @@ use crate::World;
/// ],
/// )
/// ```
///
/// [gh-svg]: https://github.com/typst/typst/issues?q=is%3Aopen+is%3Aissue+label%3Asvg
#[elem(scope, Show, LocalName, Figurable)]
pub struct ImageElem {
/// Path to an image file
@ -75,6 +73,9 @@ pub struct ImageElem {
pub data: Readable,
/// The image's format. Detected automatically by default.
///
/// Supported formats are PNG, JPEG, GIF, and SVG. Using a PDF as an image
/// is [not currently supported](https://github.com/typst/typst/issues/145).
pub format: Smart<ImageFormat>,
/// The width of the image.

View File

@ -35,7 +35,25 @@ pub struct PathElem {
/// rectangle with both fill and stroke, you have to configure both.
pub fill: Option<Paint>,
/// The rule used to fill the path.
/// The drawing rule used to fill the path.
///
/// ```example
/// // We use `.with` to get a new
/// // function that has the common
/// // arguments pre-applied.
/// #let star = path.with(
/// fill: red,
/// closed: true,
/// (25pt, 0pt),
/// (10pt, 50pt),
/// (50pt, 20pt),
/// (0pt, 20pt),
/// (40pt, 50pt),
/// )
///
/// #star(fill-rule: "non-zero")
/// #star(fill-rule: "even-odd")
/// ```
#[default]
pub fill_rule: FillRule,

View File

@ -34,7 +34,9 @@ pub struct PolygonElem {
/// rectangle with both fill and stroke, you have to configure both.
pub fill: Option<Paint>,
/// The rule used to fill the polygon.
/// The drawing rule used to fill the polygon.
///
/// See the [path documentation]($path.fill-rule) for an example.
#[default]
pub fill_rule: FillRule,

View File

@ -25,6 +25,18 @@ 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
a step-by-step introduction to Typst, check out our [tutorial].
## Installation
You have two ways to use Typst: In [our web app](https://typst.app/signup/) or
by [installing the compiler](https://github.com/typst/typst/releases) on your
computer. When you use the web app, we provide a batteries-included
collaborative editor and run Typst in your browser, no installation required.
If you choose to use Typst on your computer instead, you can download the
compiler as a single, small binary which any user can run, no root privileges
required. Unlike LaTeX, packages are downloaded when you first use them and
then cached locally, keeping your Typst installation lean. You can use your own
editor and decide where to store your files with the local compiler.
## 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
`.typ`). No boilerplate is needed to get started. Simply start by writing your
@ -452,10 +464,10 @@ and their corresponding Typst functions.
| enumitem | [`list`], [`enum`], [`terms`] functions |
Although _many_ things are built-in, not everything can be. That's why Typst has
a built-in [package manager]($universe) where the community can share their
creations and automations. Let's take, for instance, the _cetz_ package: This
package allows you to create complex drawings and plots. To use cetz in your
document, you can just write:
its own [package ecosystem]($universe) where the community share its creations
and automations. Let's take, for instance, the _cetz_ package: This package
allows you to create complex drawings and plots. To use cetz in your document,
you can just write:
```typ
#import "@preview/cetz:0.2.1"
@ -464,15 +476,15 @@ document, you can just write:
(The `@preview` is a _namespace_ that is used while the package manager is still
in its early and experimental state. It will be replaced in the future.)
Aside from the official package repository, you might also want to check out the
Aside from the official package hub, you might also want to check out the
[awesome-typst repository](https://github.com/qjcg/awesome-typst), which
compiles a curated list of resources created for Typst.
If you need to load functions and variables from another file within your
project, for example to use a template, you can use the same
[`{import}`]($scripting/#modules) statement with a file name rather than a
[`import`]($scripting/#modules) statement with a file name rather than a
package specification. To instead include the textual content of another file,
you can use an [`{include}`]($scripting/#modules) statement. It will retrieve
you can use an [`include`]($scripting/#modules) statement. It will retrieve
the content of the specified file and put it in your document.
## How do I input maths? { #maths }
@ -626,28 +638,15 @@ use in prose (cf. `\citet` and `\textcite`) are available with
You can find more information on the documentation page of the [`bibliography`]
function.
## Installation
You have two ways to use Typst: In [our web app](https://typst.app/signup/) or
by [installing the compiler](https://github.com/typst/typst/releases) on your
computer. When you use the web app, we provide a batteries-included
collaborative editor and run Typst in your browser, no installation required.
If you choose to use Typst on your computer instead, you can download the
compiler as a single, small binary which any user can run, no root privileges
required. Unlike LaTeX, packages are downloaded when you first use them and
then cached locally, keeping your Typst installation lean. You can use your own
editor and decide where to store your files with the local compiler.
## What limitations does Typst currently have compared to LaTeX? { #limitations }
Although Typst can be a LaTeX replacement for many today, there are still
features that Typst does not (yet) support. Here is a list of them which, where
applicable, contains possible workarounds.
- **Native charts and plots.** LaTeX users often create charts along with their
documents in PGF/TikZ. Typst does not yet include tools to draw diagrams, but
the community is stepping up with solutions such as
[`cetz`](https://github.com/johannes-wolf/typst-canvas). You can add those
to your document to get started with drawing diagrams.
- **Well-established plotting ecosystem.** LaTeX users often create elaborate
charts along with their documents in PGF/TikZ. The Typst ecosystem does not
yet offer the same breadth of available options, but the ecosystem around the
[`cetz`](https://github.com/cetz-package/cetz) package is catching up quickly.
- **Change page margins without a pagebreak.** In LaTeX, margins can always be
adjusted, even without a pagebreak. To change margins in Typst, you use the
@ -661,12 +660,3 @@ applicable, contains possible workarounds.
tools](https://cloudconvert.com/pdf-to-svg) or
[Inkscape](https://inkscape.org/). The web app will automatically convert PDF
files to SVG files upon uploading them.
- **Page break optimization.** LaTeX runs some smart algorithms to not only
optimize line but also page breaks. While Typst tries to avoid widows and
orphans, it uses less sophisticated algorithms to determine page breaks. You
can insert custom page breaks in Typst using `[#pagebreak(weak: true)]` before
submitting your document. The argument `weak` ensures that no double page
break will be created if this spot would be a natural page break anyways. You
can also use `[#v(1fr)]` to distribute space on your page. It works quite
similar to LaTeX's `\vfill`.

View File

@ -38,7 +38,7 @@ in your template.
number-align: center,
)
#rect(fill: aqua)
#rect(fill: aqua.lighten(40%))
```
This example visualizes the dimensions for page content, headers, and footers.

View File

@ -59,12 +59,12 @@ context is known. The body of a context expression may be evaluated zero, one,
or multiple times, depending on how many different places it is put into.
## Location context
Context cannot only give us access to set rule values. It can also let us know
_where_ in the document we currently are, relative to other elements, and
absolutely on the pages. We can use this information to create very flexible
interactions between different document parts. This underpins features like
heading numbering, the table of contents, or page headers dependent on section
headings.
We've already seen that context gives us access to set rule values. But it can
do more: It also lets us know _where_ in the document we currently are, relative
to other elements, and absolutely on the pages. We can use this information to
create very flexible interactions between different document parts. This
underpins features like heading numbering, the table of contents, or page
headers dependent on section headings.
Some functions like [`counter.get`]($counter.get) implicitly access the current
location. In the example below, we want to retrieve the value of the heading

View File

@ -249,14 +249,15 @@ fn category_page(resolver: &dyn Resolver, category: Category) -> PageModel {
let mut skip = HashSet::new();
if category == MATH {
// Already documented in the text category.
skip.insert("text");
skip = GROUPS
.iter()
.filter(|g| g.category == category.name())
.flat_map(|g| &g.filter)
.map(|s| s.as_str())
.collect();
// Already documented in the text category.
skip.insert("text");
}
// Add values and types.

View File

@ -87,10 +87,10 @@ There are, broadly speaking, three kinds of tests:
To prevent bloat, it is important that the test images are kept as small as
possible. To that effect, the test runner enforces a maximum size of 20 KiB.
If you're updating a test and hit `reference image size exceeds`, see
Updating reference images.
If truly necessary, this limit can however be lifted by adding `// LARGE` as
the first line of a test.
If you're updating a test and hit `reference image size exceeds`, see the
section on "Updating reference images" below. If truly necessary, the size
limit can be lifted by adding `// LARGE` as the first line of a test, but this
should be the case very rarely.
If you have the choice between writing a test using assertions or using
reference images, prefer assertions. This makes the test easier to understand