banner
Previous Page
PCLinuxOS Magazine
PCLinuxOS
Article List
Disclaimer
Next Page

Typst Cookbook, Part Two


by David Pardue (kalwisti)

In my previous article, I offered some practical tips for using Typst more efficiently. This month, we will take a look at additional Typst features which should help you create more typographically complex documents.


Simple Text Formatting

Typst's text function can customize the appearance and layout of text in various ways. The source code below produces the output shown in the screenshot:


#underline[The Pirates of Penzance]

#overline[Text with overline (aka overscore or overbar)]

#strike[Incorrect statement with strikethrough]

#text(fill:red)[Nota bene (red fill)]

#text(fill:blue)[*Nothing in excess (with blue boldface)*]

#text(stroke: 0.5pt + red)[Easy come, easy go (stroked in red)]

#highlight[Highlight for emphasis]

#highlight(fill:lime)[In daylight, green is the most visible color]

// This is a comment; it won't be typeset


Typst part 2

Miscellaneous Symbols

Typst offers a comprehensive set of symbols and emojis. The general symbols below are generated with the " #sym. " prefix and might prove useful in your writing.

The code below produces output shown in the screenshots. (Note: The forward slash symbol at the beginning of each line indicates that what follows is a term. Each term ends with a colon, then the term's description comes afterward.)

/ Ellipsis: #sym.dots.h To intentionally omit text, or to keep your reader in suspense
/ Greater than symbol: #sym.gt Useful for software menus, e.g., `Insert` #sym.gt `Special Character`
/ Degree symbol: Bake at 300#sym.degree F unless it is 100#sym.degree F outside.
/ Angstrom: If you measure in microscopic wavelengths such as 5 #sym.angstrom units.


Typst part 2


/ Right arrow: #sym.arrow.r
/ Long right arrow: #sym.arrow.r.long
/ Ballot checkmark: #sym.ballot.check Chicken of the Sea tuna for Fluffy
/ Ballot crossmark: #sym.ballot.cross Starkist tuna for Fluffy
/ Checkmark (heavy): #sym.checkmark.heavy Still more canned tuna for Fluffy
/ Crossmark (heavy): #sym.crossmark.heavy Pallet of fish burritos for Fluffy
/ Euro symbol: #sym.euro 50 for Fluffy's sushi
/ Infinity symbol: Fluffy's approved credit card limit: #sym.infinity
/ Hedera or Fleuron: #sym.floral This glyph resembles a floral heart. (Now rarely) used as a punctuation mark or for decorations. Hedera means 'ivy' in Latin, and fleuron is derived from the French _floron_ ('flower').
/ Trademark symbol: Kleenex#sym.trademark is a brand name of facial tissues.
/ Registered trademark symbol: Xerox#sym.trademark.registered is used by some people as a generic word for "photocopy."
/ Section sign: #sym.section for referring to a numbered section of a document, or to a specific section of a legal code. Also called a double-s, silcrow or the "paragraph symbol" (as in the German _Paragrafzeichen_).
/ Dagger: #sym.dagger Can indicate a footnote, or indicate death (of a person) or extinction (of species or languages).
/ Double dagger: Indicates a footnote or reference. Also used as a subfield delimiter in MARC cataloging records: e.g., 260 #sym.dagger.double a Chicago : #sym.dagger.double b University of Chicago Press, #sym.dagger.double c 1955.


Typst part 2


Enumerated List with Roman Numerals

If you need to make an outline, it is easy to switch from the default Arabic numbers to a Roman numerals style with a #set rule.


#set enum(numbering: "I.")

+ Rome
+ Alexandria
+ Constantinople
+ Memphis
+ Thebes
+ Nineveh
+ Persepolis
+ Carthage
+ Tyre
+ Samarkand


The code above produces this output:


Typst part 2


To create a nested list, use indentation and specify a numbering pattern with multiple counting symbols (as shown in the example below):

#set enum(numbering: "I.a.")

+ Rome
+ Alexandria
+ Constantinople
+ Istanbul ; the name's origin is likely from the Demotic Greek phrase στήν πόλιν
+ Memphis
+ Located near the modern-day Mit Rahina (Egypt)


Typst part 2


Raw Text / Code Blocks

If you need to embed computer code within your document, Typst provides methods to display verbatim text (with optional syntax highlighting) for several different programming languages. The Raw Text / Code function explains how to accomplish this.

For short bursts of inline code, you can use the #box function. The (optional) highlighting is added via a #show rule in conjunction with the fill parameter.

If you wish to highlight your code blocks, the Typst code below creates a pinkish fill:


// Display inline code in a small box
// that retains the correct baseline.
#show raw.where(block: false): box.with(
fill: luma(240),
inset: (x: 3pt, y: 0pt),
outset: (y: 3pt),
radius: 2pt,
)


Here is an example of brief inline code:


To copy a file in Linux, type: #box(``` `cp ~/Downloads/file.txt ~/Documents/file.txt.bak` ```)


It produces this output:


Typst part 2


The code below:


To copy a file, type in the Terminal: `cp ~/Downloads/foo.txt ~/Documents/foo.txt.bak`


Generates this output:


Typst part 2


With the option of #box(```` ```language code``` ````) you can indicate the programming/scripting language (typ [Typst], bash, py, rust, etc.) Note: The language name is preceded by three backticks with no intervening space. This snippet of inline code


#box(```` ```bash cp ~/Downloads/bar.txt ~/Documents/bar.txt.bak``` ````)

Produces the output:

Typst part 2


If you want to display the raw text as a separate block with highlighting, insert the code below:


// Display block code in a larger block
// with more padding.
#show raw.where(block: true): block.with(
fill:luma(240),
inset: 10pt,
radius: 4pt,
)

```bash
rg “Hello World”
```

This produces the output shown below:

Typst part 2


Another option for displaying code blocks is to use the codly package from Typst Universe; it allows a high degree of customization and produces attractive output. I will discuss it in a later section of my article.


Page Headers

The header parameter of Typst's page function can be configured to adjust the placement of the page header and its content. It provides control similar to the fancyhdr package in LaTeX.

Place the code below at the beginning of your Typst file. It will center the header and create a solid line that spans the width of your document. (The rect function [" #rect( ) "] in this example instructs Typst to draw/stroke the bottom edge of the rectangle, which will serve as the separating line. The text of the header will be placed inside the rectangle and centered.)


#set page(header:[
#rect(
stroke: (bottom:0.2pt),width: 100%,
align(center)[Customizing Typst Templates]
)
])

Typst part 2


The code below will create a flush right header with a solid line beneath it:

#set page(header:[
#rect(
stroke: (bottom:0.2pt),width: 100%,
align(right)[Customizing Typst Templates]
)
])

Typst part 2


The code below generates a flush right header without a solid line:

#set page(header: [#align(right)[Customizing Typst Templates]])

Typst part 2


Finally, the code snippet below creates a header with the authors' names flush left, and the article's title flush right:

#set page(header: [Stein _et al._ #h(1fr) Customizing Typst Templates])

Typst part 2


Endnotes

Endnotes are not currently implemented in Typst, but they are on the development roadmap (under the “Layout” section). Typst user aarnent, however, created a skeleton that allows the use of footnotes. It works—both locally and in Typst's web app—and is customizable (if you understand Typst coding). You can access his shared Typst project for more details. His workaround enables simultaneous endnote and footnote capability, if you wish.

The History StackExchange has a lengthy discussion about publishers' use of endnotes versus footnotes. Many publishers prefer endnotes because they are cheaper (requiring less fiddling by typesetters) and easier to manage, even though they inconvenience readers by making them jump back and forth between the main text and the endnotes.

#let allendotes = state("endnotes", ())
#let endnote(cnt) = {
allendotes.update(x => {
x.push(cnt + parbreak())
return x
})
context super[#allendotes.get().len()]
}

#let showendnote() = context {
v(2em)
align(center, heading(level: 2)[Notes])
for (idx, cnt) in allendotes.get().enumerate() {
super[#(idx + 1)] + cnt
}
}

#show heading: it => {
if it.level == 1 {
allendotes.update(x => ())
}
it
}

Note: Place the Typst code (above) at the beginning of your document. In addition, you must place these two commands at the end of your Typst file, so that the endnotes display properly:

#pagebreak()

#showendnote()

The #endnote command is called with the syntax below. (I truncated this code for two endnote commands to save space.)

<snip> ... understand Typst coding).#endnote[See his shared Typst project at https://typst.app/project/rnU99-7IT8dbMjGTVceOqs for more details.]

<snip> ... inconvenience to readers.#endnote[See https://tinyurl.com/3wemtjn4 for the opinionated discussion.]

The screenshots below show the generated Typst output:

Typst part 2


Typst part 2



Importing Packages from Typst Universe

Typst Universe is a collection of packages and templates to enhance Typst. I have been exploring various packages and would like to cover a few which I found useful in my writing. I hope they will benefit you as well.

(As user sitandr points out, we should remember that — unlike in LaTeX — Typst packages are needed only for some specialized tasks because basic formatting can be handled without them. In addition, Typst packages are much lighter/smaller and more easily installed than LaTeX packages.)

The procedure below will import a package into Typst's web app or the Typst compiler installed locally. I will use the colorful-boxes package as an example; however, this method works identically for the other packages that I describe.

  • Go to Typst Universe: https://typst.app/universe
  • In the Search box, type the name of the package that you wish to import
  • A list of Search results will be displayed. Click on your desired package to read more information about it
  • Typst part 2

  • Next, look for the "How to add" instructions:
  • Typst part 2

  • Click on the "Copy to clipboard" icon to copy the #import command for that package
  • Open your Typst file in the web app—or in your preferred editor, e.g., VSCodium, if you are using Typst locally—and paste the #import command at the beginning of your file
  • (Now comes the slightly tricky bit.) At the end of the #import command, type " : * " (as shown below):

  • #import "@preview/colorful-boxes:1.4.3": *

  • Importing with " : * " at the end of the #import statement puts all the content of the colorful-boxes package/module into the current scope
  • Typst part 2

  • This method is effective for small packages but for large packages with lots of functions, such as cetz (for drawing figures and charts), it is better to avoid that and use module import. Otherwise, functions from packages may overlap with yours and each other's

  • (Thanks to Redditor Greedy-Vegetable-345 for this technical explanation)

  • Your package is now available for use. You can read its documentation and/or begin experimenting with examples provided by the package's author


colorful-boxes

Once you have installed this package (as described above), you can add colorful, customizable boxes to your documents.

These examples illustrate some of the package's capabilities:

#colorbox(
title: "Great White North Facts",
color: "blue",
radius: 2pt,
width: auto
)[
Good day. How's it goin', eh?

Hosted by brothers Bob (Rick Moranis) and Doug McKenzie (Dave Thomas). It was originally known as "Kanadian Korner." They frequently used the interjection "Eh?" and taunted each other with "Take off, hoser." The sketches were mostly improvised on the set. The characters' popularity prompted a spinoff movie: _Strange Brew_ (1983).
]

Typst part 2


#slanted-colorbox(
title: "Snazzy Slanted Headline",
color: "red",
radius: 0pt,
width: auto
)[
Remember to type the command `#import "@preview/colorful-boxes:1.4.3":*` to download the package locally. The `" :* "` at the end is the tricky bit.
]

Typst part 2


#outline-colorbox(
title: "Centered Title",
color: "green",
width: auto,
radius: 2pt,
centering: true
)[
Good typography is invisible; bad typography is everywhere.

Two good introductions to typography are Robert Bringhurst (_The Elements of Typographic Style_ [1992, rev. 2012]) and _Butterick's Practical Typography_ (2nd ed., 2024).
]

Typst part 2

The "Stickybox" function is fun; it mimics the ubiquitous yellow Post-It Note.

#stickybox(
rotation: 5deg,
width: 5cm
)[
The Post-it Note's adhesive was discovered accidentally by a scientist at 3M named Spencer Silver. His colleague, Art Fry, used Silver's adhesive to create a bookmark, leading to the launch of Post-it Notes in 1977.
]

Typst part 2


codly

The codly package is your best choice if you need to embed a lot of code blocks in your document. It allows you to add annotations, skip lines, customize numberings and add programming language icons. Since I am a beginner with codly, I did not change any of the default parameters; I will only cover its most basic usage. For more details, you should consult the author's extensive manual (47 p.) on GitHub. After importing the package, you must initialize it with a #show rule. (You only need to do this once per document.)

#import "@preview/codly:1.3.0": *
#import "@preview/codly-languages:0.1.1": *
#show: codly-init.with()

By default, codly ships with smart-indent enabled. This means that codly will automatically detect the indentation of your code block and adjust the horizontal offset on line wrapping accordingly.

Adding the Typst code block below will generate the output shown in the screenshot. (The “typ” following the three backticks (```) identifies the programming language as Typst.) ```typ
// Hyperlink styling
#show link: set text(blue)
// Another option is:
// #show link: underline
```

Typst part 2

The package ships with language definitions for the Typst language. If you wish, you can use the typst-icon function to produce the Typst icon (featuring a miniature Typst logo) for your code blocks:

#codly(languages: typst-icon)
```typ
// Hyperlink styling
#show link: set text(blue)
// Another option is:
// #show link: underline
```

Typst part 2


run-liners

The run-liners package allows you to create various sorts of run-in (inline) lists. Its functionality is similar to the paralist package in LaTeX.

After importing the package, the Typst code below will produce the output shown in the screenshot:

This includes: #run-in-enum([first task], [second task], [third task]) to be completed by the end of the month.
The list can have custom markers, if you wish:
This includes:
#run-in-list(
marker: [#sym.circle.filled.small],
[first task],
[second task],
[third task]
)
to be completed by the end of the month.

#run-in-terms(
([Festina], ['make haste']),
([lente], ['slowly'])
)
is a famous Latin idiom that reminds us to keep a steady pace rather than rushing through tasks mindlessly. Activities should be performed with a proper balance of urgency and diligence.

Typst part 2


There is also an option for run-in lines of poetry, such as this classic haiku by Japanese writer Natsume Sōseki (1867–1916):

#run-in-verse(
[The lamp once out],
[Cool stars enter],
[The window frame.]
)

Typst part 2


untypsignia and metalogo

If you find yourself needing to typeset the logos for TeX and friends, there are two useful packages that work well: untypsignia and metalogo. Their usage is straightforward; you will be able to understand them from the examples provided by their authors.


basic-report Template

For a report format with a clean, professional look, I recommend the basic-report template by Roland Schätzle. It was designed to include an attractive title page, a table of contents page and content pages (supporting three levels of headings). The template uses the Vollkorn (serif) font for the body text; the Ubuntu font (sans serif) is used as a contrasting companion font for the title page, table of contents, headings, and labels.

I created a brief document (7 p.) with the basic-report template and have shared it as a project (read-only access) from Typst's web app, to provide a glimpse of the results that you can expect. The user guide for Acme™ rocket-powered roller skates is tongue in cheek—unless you are a hungry coyote in pursuit of a roadrunner.

In case you have not used a template from Typst Universe before, here are quick instructions:

  • In the Typst web app, click on the "Start from template" option in the Dashboard, then search for basic-report
  • Typst part 2


  • When the search results are displayed, click on the basic-report page icon to select it. Give your project a title, then click on the Create button

Typst part 2


One quirk with using this template is that although Vollkorn comes pre-installed in the Typst web app, the Ubuntu font does not. Therefore, you must import the font into your project. That can be accomplished easily following the steps below:

  • Download the Ubuntu font via Google Fonts or from the 1001 Fonts website. The Ubuntu font family is distributed at no cost, under an open/libre license

    • If you download via Google Fonts, you will have a .zip file which you will need to extract. The unzipped folder will include several fonts; the most versatile choice is the Ubuntu-Regular.ttf file

    • If you download from 1001 Fonts, you can select just the "Ubuntu Regular" variant (which will download a file named ubuntu.regular.ttf)

  • In Typst's web app, click on the Explore files icon, then click on the Upload a new file button to upload your desired .ttf file

    Typst part 2


  • The new font will be discovered automatically. You should see the font on the title page, table of contents and the headings change from Vollkorn to Ubuntu Regular

If you are using the Typst compiler locally on your PCLinuxOS system, the procedure for setting up the basic-report template is slightly different. I have written separate instructions for that in my shared project, in case you are interested.

I hope these tips will boost your productivity with Typst and encourage you to continue exploring its capabilities. I am working on the third (and final) part of this cookbook series, which will focus on creating title pages with Typst. If you are interested in seeing a Typst-generated replica of this article, I have publicly shared my project. The document's body typeface is Source Serif Pro, and the headings use Source Sans Pro.



Previous Page              Top              Next Page