4.4 Quarto

Quarto Guide: https://quarto.org/docs/guide/

Quarto Tutorial: https://jmjung.quarto.pub/m02-advanced-literate-programming/#learning-outcomes

Run Cell

Quarto Command Keyboard Shortcut
Run Current Cell ⇧ + Enter
Run Selected Line(s) ⌘ + Enter

Host Quarto on GitHub Pages.

To get started, change your project configuration _quarto.yml to use docs as the output-dir.

project:
  type: book
  output-dir: docs

Then, add a .nojekyll file to the root of your repository that tells GitHub Pages not to do additional processing of your published site using Jekyll (the GitHub default site generation tool):

touch .nojekyll
  • Note that .nojekyll’s location is different than that of bookdown, which is at /docs folder.

Only re-render changed files

You can add the following to your _quarto.yml file to only re-render changed files:

execute: 
  freeze: auto

When freeze: auto is enabled, Quarto checks for modifications in the source files of your computational documents. If no changes are detected, Quarto will utilize the cached results from previous computations, skipping the re-execution of code chunks.

This significantly speeds up rendering times, especially for large projects with many computational documents.


Strengths of Quarto:

  • hoverable citations and cross-references, easy to read
  • easy subplots

Weakness of Quarto:

  • slow compared to Bookdown

    Workaround:

    • Use quarto preview in terminal to enable live preview
    • Set freeze: auto in _quarto.yml to only re-render changed files.
  • Issues when you want to compile one single page within a package. Changes are not reflected in time unless you render the whole website.

    Workaround: Need to exclude from project index, and need file header yaml to import mathjax settings and themes.

    Bookdown is reliable. Don’t need yaml in single Rmd, website theme will apply automatically.


4.4.1 Book Structure

book:
  chapters:
    - index.qmd
    - preface.qmd
    - part: dice.qmd
      chapters: 
        - basics.qmd
        - packages.qmd
    - part: cards.qmd
      chapters:
        - objects.qmd
        - notation.qmd
        - modifying.qmd
        - environments.qmd
    - references.qmd
  appendices:
    - tools.qmd
    - resources.qmd
  • The index.qmd file is required (because Quarto books also produce a website in HTML format). This page should include the preface, acknowledgements, etc.

  • The remainder of chapters includes one or more book chapters.

    You can divide your book into parts using part within the book chapters.

    Note that the markdown files dice.qmd and cards.qmd contain the part title (as a level one heading) as well as some introductory content for the part.

    If you just need a part title then you can alternatively use this syntax:

    book:
      chapters:
        - index.qmd
        - preface.qmd
        - part: "Dice"
          chapters: 
            - basics.qmd
            - packages.qmd
  • The references.qmd file will include the generated bibliography (see References below for details).


Syntax differences with R Markdown:

  • Code chunks

    Both R markdown and Quarto can use the following ways to specify chunk options:

    Use tag=value in the chunk header ```{r}.

    ```{r my-label, fig.cap = caption}
    
    # R code
    ```

    Alternatively, you can write chunk options in the body of a code chunk after #|, e.g.,

    ```{r}
    #| label: fig-my-label
    #| fig-cap: caption 
    
    # R code
    ```

    tag: value is the YAML syntax. Logical values in YAML can be any of: true/false, yes/no, and on/off. They all equivalent to TRUE/FALSE (uppercase) in R.

    Options format:

    • space after #| and colon :
    • TRUE/FALSE need to be in uppercase

    Note that Quarto accepts Rmd’s way of specifying chunk options. The difference is that Quarto’s label for figures must start with fig-, while Rmd accepts any labels.

    ```{r label = "fig-my-label", fig.cap = caption}
    
    # R code
    ```

4.4.2 PDF Options

Use the pdf format to create PDF output. For example:

---
title: "Lab 1: Solutions"
format: 
  pdf:
    include-in-header: ../latex/preamble.tex
    fontsize: 12pt
---
PDF Options Functions
title Document title
date Document date
author Author or authors of the document
abstract Summary of document
Includes
include-in-header Include contents at the end of the header.
Specify your pdf template here.

See HERE for all available options.

After rendering, the following info will appear in the console:

pandoc 
  to: latex
  output-file: lab1_solutions.tex
  standalone: true
  pdf-engine: xelatex
  variables:
    graphics: true
    tables: true
  default-image-extension: pdf
  
metadata
  documentclass: scrartcl
  classoption:
    - DIV=11
    - numbers=noendperiod
  papersize: letter
  header-includes:
    - \KOMAoption{captions}{tableheading}
  block-headings: true
  title: 'Lab 1: Solutions'
  fontsize: 12pt

Note that documentclass: scrartcl is the KOMA-Script article class.

It has good looking default settings, and is highly customizable.


4.4.2.1 Title Margin

One issue is it might have too wide margins around the title.

To reduce the margin above the title, add the following line to your preamble.tex file:

% reduce title top margin
\usepackage{xpatch}
\makeatletter
\xpatchcmd{\@maketitle}{\vskip2em}{
    % Insert here the space you want between the top margin and the title.
    \vspace{-2em} % Example of smaller margin. 
}{}{}
\makeatother

To reduce the margin below the title, in individual qmd file, add the following line after the YAML header:

::: {=latex}
\vspace{-6em}
:::

4.4.2.2 Templates

See HERE for an overview of how to set template for tex files.

  • pakage setup
  • article typsetting

Starter template for qmd file.

  • yaml header
  • structure of your qmd

4.4.3 HTML Theming

One simple theme

title: "My Document"
format:
  html: 
    theme: cosmo
    fontsize: 1.1em
    linestretch: 1.7

Enable dark and light modes

format:
  html:
    include-in-header: themes/mathjax.html
    respect-user-color-scheme: true
    theme:
      dark: [cosmo, themes/cosmo-dark.scss]
      light: [cosmo, themes/cosmo-light.scss]

respect-user-color-scheme: true honors the user’s operating system or browser preference for light or dark mode.

Otherwise, the order of light and dark elements in the theme or brand will determine the default appearance for your html output. For example, since the dark option appears first in the first example, a reader will see the light appearance by default, if respect-user-color-scheme is not enabled.

As of Quarto 1.7, respect-user-color-scheme requires JavaScript support: users with JavaScript disabled will see the author-preferred (first) brand or theme.


Custom Themes

Your custom.scss file might look something like this:

/*-- scss:defaults --*/
$h2-font-size:          1.6rem !default;
$headings-font-weight:  500 !default;

/*-- scss:rules --*/
h1, h2, h3, h4, h5, h6 {
  text-shadow: -1px -1px 0 rgba(0, 0, 0, .3);
}

Note that the variables section is denoted by

  • /*-- scss:defaults --*/: the defaults section (where Sass variables go)

    Used to define global variables that can be used throughout the theme.

  • /*-- scss:rules --*/: the rules section (where normal CSS rules go)

    Used to define more fine grained behavior of the theme, such as specific styles for headings, paragraphs, and other elements.


Theme Options

You can do extensive customization of themes using Sass variables. Bootstrap defines over 1,400 Sass variables that control fonts, colors, padding, borders, and much more.

The Sass Variables can be specified within SCSS files. These variables should always be prefixed with a $ and are specified within theme files rather than within YAML options

Commonly used Sass variables:

Category Variable Description
Colors $body-bg The page background color.
$body-color The page text color.
$link-color The link color.
$input-bg The background color for HTML inputs.
$popover-bg The background color for popovers (for example, when a citation preview is shown).

You can see all of the variables here:

https://github.com/twbs/bootstrap/blob/main/scss/_variables.scss

Note that when you make changes to your local .scss, the changes will be implemented in-time. That is, you don’t need to re-build your website to see the effects.

Ref:


4.4.4 Render Quarto

Rendering the whole website is slow. When you are editing a new section/page, you may want to edit as a standalone webpage and when you are finished, you add the qmd file to the _quarto.yml file index.

Difference btw a standalone webpage from a component of a qmd project

  • Standalone webpage: include yaml at the header of the file.

    Fast compile and rendering. ✅

  • A component of qmd project: added to the file index, no yaml needed, format will automatically apply.

    Slow, need to render the whole qmd project in order to see your change.

In terminal

This will provide live preview of the document in your web browser. Newest changes will be reflected while you edit the document. ✅

  • Render a Quarto document to HTML using the command line:

    $quarto render 0304-Quarto.Rmd --to html
  • Quarto Preview: display output in the external web browser.

    $ quarto preview 0304-Quarto.Rmd # all formats
    $ quarto preview 0304-Quarto.Rmd --to html # specific format

    Note that quarto render can be used to Rmd files too.

  • You can also render a Quarto project using:

    $quarto render --to html

In VS Code

You have to refresh to see your updates when using VS Code command palette quarto preview.

You can render a Quarto document in VS Code using the command palette:

  • Quarto: Render Document to render the document.
  • Quarto: Render Project to render the entire project.
  • Quarto: Preview to preview the default document in a web browser. If you want to preview a different format, use the Quarto: Preview Format command:

This will show a preview of the project in the internal browser.

In R

quarto::quarto_render(input = NULL, output_format = "html") can be used to render a Quarto document or project in R.

  • If input is not specified, it will render the current Quarto project. If input is specified, it will render the specified Quarto document.

  • If output_format is not specified, it will render the document to HTML. You can specify other formats such as PDF or Word.

    • output_format = "all" will render all formats specified in the _quarto.yml file.
# Render a Quarto document to HTML
quarto::quarto_render("0304-Quarto.Rmd", output_format = "html")
# Render a Quarto project to HTML
quarto::quarto_render(output_format = "html")
# Render a Quarto document to PDF
quarto::quarto_render("0304-Quarto.Rmd", output_format = "pdf")
# Render a Quarto project to PDF
quarto::quarto_render(output_format = "pdf")

Alternatively, you can use the Render button in RStudio. The Render button will render the first format listed in the document YAML. If no format is specified, then it will render to HTML.


4.4.5 Cross References

  1. Add labels:

    • Code cell: add option label: prefix-LABEL
    • Markdown: add attribute #prefix-LABEL
    • Note that the prefix should be connected to the label with a hyphen -.
  2. Add references: @prefix-LABEL, e.g.

    You can see in @fig-scatterplot, that...
Element ID How to cite
Figure #fig-xxx @fig-xxx
Table #tbl-xxx @tbl-xxx
Equation #eq-xxx @eq-xxx
Section #sec-xxx @sec-xxx

Equations

$$
y_i = \beta_{i}'x + u_i.
$$ {#eq-cross_sectional_hetero}
  • @eq-cross_sectional_hetero gives Equation (1)
  • [-@eq-cross_sectional_hetero] gives only the tag (1)

You can customize the appearance of inline references by either changing the syntax of the inline reference or by setting options.

Here are the various ways to compose a cross-reference and their resulting output:

Type Syntax Output
Default @fig-elephant Figure 1
Capitalized @Fig-elephant Figure 1
Custom Prefix [Fig @fig-elephant] Fig 1
No Prefix [-@fig-elephant] 1

Note that the capitalized syntax makes no difference for the default output, but would indeed capitalize the first letter if the default prefix had been changed via an option to use lower case (e.g. “fig.”).

Change the prefix in inline reference using *-prefix options. You can also specify whether references should be hyper-linked using the ref-hyperlink option.

---
title: "My Document"
crossref:
  fig-prefix: figure   # (default is "Figure")
  tbl-prefix: table    # (default is "Table")
  ref-hyperlink: false # (default is true)
---

4.4.6 Equations

Load MathJax Config

Load mathjax.html in YAML

---
title: "Model specifications"
author: "GDP and climate"
date: "2025-05-13"
from: markdown+tex_math_single_backslash
format: 
  html:
    toc: true
    self-contained: true
    html-math-method: mathjax
    include-in-header: mathjax.html
---

In mathjax.html

<script>
MathJax = { 
    tex: { 
        tags: 'ams',  // should be 'ams', 'none', or 'all' 
        macros: {  // define TeX macro
            RR: "{\\bf R}",
            bold: ["{\\bf #1}", 1]
        },
    },
};
</script>

tags: 'ams' allows equation numbering


Math delimiters

Issue: Cannot use \( and \[ for math delimiters.
Fix: Add from: markdown+tex_math_single_backslash to YAML frontmatter. Source

---
title: "Quarto Playground"
from: markdown+tex_math_single_backslash
format:
  html:
    html-math-method: mathjax
---

Inline math example: \( E = mc^2 \)

Block math example:

\[
a^2 + b^2 = c^2
\]

form: Format to read from. Extensions can be individually enabled or disabled by appending +EXTENSION or -EXTENSION to the format name (e.g. markdown+emoji).

Extension: tex_math_single_backslash

Causes anything between \( and \) to be interpreted as inline TeX math, and anything between \[ and \] to be interpreted as display TeX math. Note: a drawback of this extension is that it precludes escaping ( and [.

Refer to Docs of Quarto and Pandoc:


Q: How to get rid of the qmd dependence file?
A: Use

format: 
  html:
    self-contained: true

4.4.7 Divs and Spans

You can add classes, attributes, and other identifiers to regions of content using Divs and Spans.

Div example

::: {.border} 
This content can be styled with a border 
:::

Once rendered to HTML, Quarto will translate the markdown into:

<div class="border">   
  <p>This content can be styled with a border</p> 
</div>

A bracketed sequence of inlines, as one would use to begin a link, will be treated as a Span with attributes if it is followed immediately by attributes:

[This is *some text*]{.class key="val"}

Once rendered to HTML, Quarto will translate the markdown into

<span class="class" data-key="val">
  This is <em>some text</em>
</span>

4.4.8 Theorems

::: {#thm-line}
The equation of any straight line, called a linear equation, can be written as:

$$
y = mx + b
$$
:::

See @thm-line.

In Quarto, #thm-line is a combined command us .theorem #thm-line in bookdown. In bookdown, the label can be anything, does not have to begin with #thm-. But in Quarto, #thm-line is restrictive, it indicates the thm environment and followed by the label of the theorem line.

Theorem 4.1 The equation of any straight line, called a linear equation, can be written as:

\[ y = mx + b \]

See Theorem 4.1.


To add a name to Theorem, use name="...".

::: {#thm-topo name="Topology Space"}
A topological space $(X, \Tcal)$ is a set $X$ and a collection $\Tcal \subset \Pcal(X)$ of subsets of $X,$ called open sets, such that ...
:::

See Theorem @thm-topo.

Theorem 4.2 (Topology Space) A topological space \((X, \Tcal)\) is a set \(X\) and a collection \(\Tcal \subset \Pcal(X)\) of subsets of \(X,\) called open sets, such that …

See Theorem 4.2.


Change the label prefix:

---
crossref:
  cnj-title: "Assumption"
  cnj-prefix: "Assumption"
---
  • cnj-title: The title prefix used for conjecture captions.
  • cnj-prefix: The prefix used for an inline reference to a conjecture.

4.4.9 Callouts

There are five different types of callouts available.

  • note (blue)
  • tip (green)
  • important (red)
  • warning (amber 比 caution 更亮眼 vivid )
  • caution (orange)

The color and icon will be different depending upon the type that you select.

::: {.callout-note}
Note that there are five types of callouts, including:
`note`, `warning`, `important`, `tip`, and `caution`.
:::

::: {.callout-tip}
## Tip with Title

This is an example of a callout with a title.
:::

::: {.callout-caution collapse="true"}
## Expand To Learn About Collapse

This is an example of a 'folded' caution callout that can be expanded by the user. You can use `collapse="true"` to collapse it by default or `collapse="false"` to make a collapsible callout that is expanded by default.
:::

Here are what the various types look like in HTML output:

  • Callout heading can be defined using
    • title = "Heading" in the callout header, or

    • ## Heading in the callout body

      It can be any level of heading.

  • icon = false to disable the icon in the callout.
  • To cross-reference a callout, add an ID attribute that starts with the appropriate callout prefix, e.g., #nte-xxx. You can then reference the callout using the usual @nte-xxx syntax.
  • appearance = "default" | "simple" | "minimal"
    • default: to use the default appearance with a background color and border.

    • simple: to remove the background color, but keep the border and icon.

    • minimal: A minimal treatment that applies borders to the callout, but doesn’t include a header background color or icon.

      appearance="minimal" is equivalent to appearance = "simple" icon = false in the callout header.

You can style callouts using CSS. For example, the change font size and alignment of text, you can use the following CSS:

::: {.callout-important appearance="minimal"}
## Research Question

<center style="font-size: 1.5em; font-weight: bold;">
Does expenditure per student affect student performance \
in elementary school education?
</center>
:::

4.4.9.1 Nested Callouts

You can nest callouts within other callouts. For example:

::: {.callout-warning}
## Warning with Nested Callout
This is an example of a warning callout that contains a nested note callout.

::: {.callout-note}
This is a nested note callout.
:::

:::

Note that you need to put a blank line before and after the nested callout to ensure proper rendering.


References: