4.4 Quarto
Quarto Guide: https://quarto.org/docs/guide/
Quarto Tutorial: https://jmjung.quarto.pub/m02-advanced-literate-programming/#learning-outcomes
Run Quarto in VS Code: https://quarto.org/docs/tools/vscode/index.html
Quarto is based on Pandoc and uses its variation of markdown as its underlying document syntax. See the full documentation of Pandoc’s Markdown for more in-depth documentation.
| Quarto Command | Keyboard Shortcut |
|---|---|
| Run Current Cell | ⇧ + ⌘ + Enter |
| Run Current Cell and Jump to Next Cell | ⇧ + Enter |
| Run Selected Line(s) | ⌘ + Enter |
| Run All Cells | ⌥ + ⌘ + R |
Host Quarto on GitHub Pages.
To get started, change your project configuration _quarto.yml to use docs as the output-dir.
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):
- Note that
.nojekyll’s location is different than that ofbookdown, which is at/docsfolder.
4.4.0.1 Only re-render changed files
You can add the following to your _quarto.yml file to only re-render changed files:
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. ✅
There are drawbacks: some files may not be updated in time.
- Use
freeze: falseto force re-rendering of all files when you are able to submit your changes. - Use
freeze: autowhen you are editing actively and want to see your changes in time.
Strengths of Quarto:
- hoverable citations and cross-references, easy to read
- easy subplots
Weaknesses of Quarto:
slow compared to
BookdownWorkaround:
- Use
quarto previewin terminal to enable live preview - Set
freeze: autoin_quarto.ymlto only re-render changed files.
- Use
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
yamlto import mathjax settings and themes.Bookdownis reliable. Don’t needyamlin singleRmd, website theme will apply automatically.Not support
rstudioapifunctions. E.g., the following is often used to set working directory to the folder where the current script is located.But it does NOT work in Quarto.
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.qmdThe
index.qmdfile is required (because Quarto books also produce a website in HTML format). This page should include the preface, acknowledgements, etc.The remainder of
chaptersincludes one or more book chapters.You can divide your book into parts using
partwithin the bookchapters.Note that the markdown files
dice.qmdandcards.qmdcontain 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:
The
references.qmdfile will include the generated bibliography (see References below for details).
4.4.2 Code chunks
Both R markdown and Quarto can use the following ways to specify chunk options:
Use tag=value in the chunk header ```{r}.
Alternatively, you can write chunk options in the body of a code chunk after #|, e.g.,
tag: value is the YAML syntax.
Options format:
- space after
#|and colon: - Logical values in YAML can be any of:
true/false,yes/no, andon/off.- They all equivalent to
TRUE/FALSE(uppercase) in Rmd. - Note that TRUE/FALSE need to be in uppercase in Rmd.
- They all equivalent to
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.
❗️ Note that NOT all Rmd chunk options are supported in Quarto. See Quarto Chunk Options for all available options.
Quarto chunk options available for customizing output include:
| Option | Description |
|---|---|
eval |
Evaluate the code chunk (if false, just echos the code into the output). |
echo |
Include the source code in output |
output\(^{[1]}\) |
Include the results of executing the code in the output (true, false, or asis to indicate that the output is raw markdown and should not have any of Quarto’s standard enclosing markdown). |
warning |
Include warnings in the output. |
error |
Include errors in the output (note that this implies that errors executing code will not halt processing of the document). |
include |
Catch all for preventing any output (code or results) from being included (e.g. include: falsesuppresses all output from the code block). |
renderings |
Specify rendering names for the plot or table outputs of the cell, e.g. [light, dark] |
\(^{[1]}\) output is similar to results in Rmd. You cannot use results='hide' in Quarto, use output: false instead.
4.4.3 Knitr Options
If you are using the Knitr cell execution engine, you can specify default document-level Knitr chunk options in YAML. For example:
---
title:"My Document"
format: html
knitr:
opts_chunk:
collapse: true
comment: "#>"
R.options:
knitr.graphics.auto_pdf:true
---You can additionally specify global Knitr options using opts_knit.
The R.options chunk option is a convenient way to define R options that are set temporarily via options() before the code chunk execution, and immediately restored afterwards.
In the example above, we establish default Knitr chunk options for a single document. You can also add shared knitr options to a project-wide _quarto.yml file or a project-directory scoped _metadata.yml file.
ref: https://quarto.org/docs/computations/execution-options.html#knitr-options
4.4.4 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-engine: xelatex
---See HERE for all available options.
See Metadata variables for yaml options that Pandoc recognizes.
Title & Author
| PDF Options | Functions |
|---|---|
title |
Document title |
date |
Document date |
author |
Author or authors of the document |
abstract |
Summary of document |
Format Options
| PDF Options | Functions |
|---|---|
pdf-engine |
Specify the PDF engine to use. Options include pdflatex, xelatex, and lualatex. The default is xelatex. |
| PDF Options | Functions |
|---|---|
include-in-header |
Include contents at the end of the header. Specify your pdf template here. |
Subkeys for include-in-header
file: path to a file to include at the end of the header.text: |: include raw latex content in the YAML header.|indicates that the content is in multiple lines.If you omit
file:ortext:, Quarto assumesfile:by default.
Use example
format:
pdf:
include-in-header:
- text: |
\usepackage{eplain}
\usepackage{easy-todo}
- file: packages.tex
- macros.tex # assume file by default- Note that you need the dash
-beforetext:andfile:to indicate a list of items.
Any packages specified using includes that you don’t already have installed locally will be installed by Quarto during the rendering of the document.
header-includes: | is a pandoc variable for including raw LaTeX code in the document header.
- use example in quarto doc
- pandoc doc for
header-includes
header-includes: |
\RedeclareSectionCommand[
beforeskip=-10pt plus -2pt minus -1pt,
afterskip=1sp plus -1sp minus 1sp,
font=\normalfont\itshape]{paragraph}
\RedeclareSectionCommand[
beforeskip=-10pt plus -2pt minus -1pt,
afterskip=1sp plus -1sp minus 1sp,
font=\normalfont\scshape,
indent=0pt]{subparagraph}Format & Typesettings
| PDF Options | Functions |
|---|---|
toc-depth: 3 |
Specify the number of section levels to include in the table of contents. The default is 3 |
number-sections: false |
Number section headings rendered output. By default, sections are not numbered. |
number-depth |
By default, all headings in your document create a numbered section. |
| PDF Options | Functions |
|---|---|
df-print |
Method used to print tables in Knitr engine documents. - default: Use the default S3 method for the data frame. - kable: Default method. Markdown table using the knitr::kable() function. - tibble: Plain text table using the tibble package. - paged: HTML table with paging for row and column overflow. |
| PDF Options | Functions |
|---|---|
keep-tex: false |
Whether to keep the intermediate tex file used during render. Defaults to false.Helpful when you want to debug or share tex files with others. |
Q: How to print dollar sign in pdf output?
A: qmd supports $ directly. No need to escape. If it fails, try \$ or \\$.
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.4.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.
}{}{}
\makeatotherTo reduce the margin below the title, in individual qmd file, add the following line after the YAML header:
fenced divs
code chunks
For pdf output, it is possible to write LaTeX code directly in Markdown document using fenced divs or code chunks with {=latex}.
- Don’t forget the equal sign before
latex.
ref: R Markdown Cookbook: Section 6.11 Write raw LaTeX code
4.4.4.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.4.3 Add Appendices
\newpage
# Appendices {.unnumbered}
\appendix
\renewcommand{\thesubsection}{\Alph{subsection}}
\setcounter{table}{0}
\renewcommand{\thetable}{\thesection\arabic{table}}
\setcounter{figure}{0}
\renewcommand{\thefigure}{\thesection\arabic{figure}}
## Optimal Portfolio R Code# Appendices {.unnumbered}creates a title for the appendices section without a section number.- Use
\appendixto reset the section counter to 0 and\renewcommand{\thesubsection}{\Alph{subsection}}to change the section numbering to letters (A, B, C, …). - Similarly, reset the table and figure counters and change their numbering to include the section letter “A”, “B”, … as a prefix.
- Finally, use
## Optimal Portfolio R Codeto create an appendix section for your first appendix. The# Appendiceswill be level one heading, and## Optimal Portfolio R Codewill be level two heading under the appendices section.
4.4.5 HTML Theming
One simple theme
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]- See HTML basic yaml for basic option settings.
- See HTML format reference for a complete list of all available options.
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
| 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:
Quarto document: https://quarto.org/docs/output-formats/html-themes.html
Check sass variables: https://bootswatch.com
4.4.6 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
yamlat the header of the file.Fast compile and rendering. ✅
A component of
qmdproject: added to the file index, noyamlneeded, format will automatically apply.Slow, need to render the whole
qmdproject 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 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 rendercan be used to Rmd files too. - Run
quarto preview helpto see its complete syntax.
- Note that
You can also render a Quarto project using:
quarto preview [file] [args] first provide file name, then additional arguments.
Supported arguments:
--portSuggested port to listen on (defaults to random value between 3000 and 8000).--hostHostname to bind to (defaults to 127.0.0.1)--no-browserUse internal viewer, do not open external browser.--no-watch-inputsflag specifically prevents Quarto from automatically re-rendering the output when changes are detected in your input source files (e.g.,.qmdfiles). This means that if you edit and save your.qmdfile, the preview in your browser will not automatically update.To see changes in the preview when using this flag, you would need to manually stop the
quarto previewprocess and restart it, or explicitly trigger a re-render usingquarto render.Even when using this flag, Quarto will still print the message “Watching file for changes.” This means that Quarto is still watching CSS files and
_quarto.ymlfor changes, but not the main input files.
quarto preview [file] --port 7200 Previewing website using a specific port. This is useful when your want to preview multiple documents simultaneously.
The default “internal” viewer in VS Code opens only one document at a time. Can use Simple Browser Multi Extension to open multiple internal browsers in VS Code.
Steps:
Install Simple Browser Multi Extension.
Use command
quarto preview 0304-Quarto.Rmd --port 7200in terminal to start live preivew. This will open the preview in your external web browser.If you don’t want automatic re-rendering when you save the file, add
--no-watch-inputsflag.In VS Code, use command palette
Simple Browser Multi: Showand enter the url in Step 2 to open the preview in the internal browser.
In VS Code
By default Quarto does not automatically render .qmd or .ipynb files when you save them. This is because rendering might be very time consuming (e.g. it could include long running computations) and it’s good to have the option to save periodically without doing a full render.
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 Documentto render the document.Quarto: Render Projectto render the entire project.Quarto: Previewto preview the default document in a web browser. If you want to preview a different format, use theQuarto: Preview Formatcommand:
This will show a preview of the project in the internal browser.
However, you can configure the Quarto extension to automatically render whenever you save. In settings, set quarto.renderOnSave to true.
You might also want to control this behavior on a per-document or per-project basis. If you include the editor: render-on-save option in your document or project YAML it will supersede whatever your VS Code setting is. For example:
Q: Quarto Preview pane not refreshing and updating changes.
A: The issue seems to come from the --no-watch-inputs option to the preview command, preventing the live update. ↩︎
Use the following command in terminal to enable live preview:
Copy and paste the url to the internal browser in VS Code. The command supports live preview. When you make changes to your qmd file and save, the preview will be updated in time.
In R
quarto::quarto_render(input = NULL, output_format = "html") can be used to render a Quarto document or project in R.
If
inputis not specified, it will render the current Quarto project. Ifinputis specified, it will render the specified Quarto document.If
output_formatis 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.ymlfile.
# 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.7 Cross References
Add labels
Two options:
- 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
-. - Note that the hash sign
#is required.
- Note that the prefix should be connected to the label with a hyphen
- Code cell: add option
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 |
Cross-reference to a figure:
Figure 4.1: Scatter plots example
See Figure 4.1 (@fig-scatter) for the scatter plots.
You can customize the prefix of the reference (Figure x) using crossref/*-prefix options in YAML.
Cross-references to Equations
@eq-cross_sectional_heterogivesEquation 1. There are no parentheses around the number.With the
Equationprefx, but no parentheses around labels.([-@eq-cross_sectional_hetero])gives only the tag(1), note that you need to add the parentheses yourself.An alternative way is to use
\eqref{eq-cross_sectional_hetero}fromamsmathpackage, which gives(1)with parentheses automatically. You need to add the prefix Eq. yourself. ↩︎
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.8 Equations
4.4.8.1 Individual qmd file
Load MathJax Config
For individual qmd files, load mathjax.html in YAML
---
title: "Model specifications"
author: "GDP and climate"
date: "2025-05-13"
format:
html:
toc: true
self-contained: true
html-math-method: mathjax
include-in-header: mathjax.html
from: markdown+tex_math_single_backslash
---fromcan be a top-level option (same level astitle) or a third-level option underformat/htmlin YAML.- It specifies formats to read from.
- Extensions can be individually enabled or disabled by appending
+EXTENSIONor-EXTENSIONto the format name (e.g. markdown+emoji). - See Quarto Extensions for available extensions.
from: markdown+tex_math_single_backslashtells Quarto/Pandoc to read the input as Pandoc Markdown with thetex_math_single_backslashextension enabled.fromtex_math_single_backslashsupports\(and\[as math delimiters.- See Pandoc: Math Input for available math extensions.
In mathjax.html, define the MathJax configuration, e.g., user-defined macros.
<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.
4.4.8.2 Quarto project
In _quarto.yml,
format:
html:
include-in-header:
- file: themes/mathjax.html # MathJax for LaTeX custom macro support
- file: themes/common-header.html # load js scripts and external css (e.g., font-awesome) for all pages
from: markdown+tex_math_single_backslashNote that from is under html, rather than at the top level of YAML.
4.4.8.3 Cross-referencing Equations
Equations need to be labeled to be numbered and cross-referenced.
- Note that labels must begin with
#eq-xxx. Don’t forget the hyphen-betweeneqandxxx. - Put the label after the
$$and inside curly braces{}. - References to equations are made using
@eq-xxx.
Difference with
bookdown.bookdown, on the other hand, use(\#eq:label)(must use colon) after the equation but inside the$$.
4.4.8.4 Math delimiters
Use $ delimiters for inline math and $$ delimiters for display math.
Note that for inline math, NO spaces are allowed between the dollar signs and the math content. Otherwise, it will NOT be recognized as math.
Examples:
Inline math:
$E = mc^2$Block math:
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:
https://quarto.org/docs/reference/formats/html.html#rendering
https://pandoc.org/MANUAL.html#extension-tex_math_single_backslash
https://pandoc.org/MANUAL.html#extension-tex_math_double_backslash
Q: How to get rid of the qmd dependence file?
A: Use
4.4.9 Extensions
4.4.9.1 Color Text
Create a filter to apply blue text color to fenced div.
- Created a minimal local color-text filter:
- Added
_quiz/_extensions/color-text/color-text.lua - It supports the
.blueclass for both blocks and inline spans:- HTML: adds
style="color: blue;" - PDF: wraps with LaTeX xcolor; automatically injects
\usepackage{xcolor}
- HTML: adds
- Added
- Updated the
qmdfile YAML to reference this local filter:- filters:
_extensions/color-text/color-text.lua
- filters:
- You can use fenced divs and inline spans with
.blue.
Use example
In the yaml header of your
qmdfile, add the following line to reference the local filter:Use the
.blueclass in your markdown content:
4.4.9.2 Emoji
In the yaml, add the emoji extension to the from option in document metadata.
For markdown formats that support text representations of emojis 😁 (e.g. :grinning:), the text version will be written. For other formats the literal emoji character will be written. Currently, the gfm and hugo (with enableEmoji = true in the site config) formats both support text representation of emojis.
Note: This does NOT work for quarto pdf. Use twemoji approach instead. See below.
How to add more emoji later:
Open
twemoji_manifest.jsonand append new code points to the emoji object- Example:
"1f44d": ["👍", ":thumbsup:"]
How to find the code points of an emoji:
- Example:
Run the fetcher again:
Within the project directory:
From anywhere:
$'/Users/menghan/Documents/language/norsk/norskprøver/B2/exam notes/emoji/fetch_twemoji.sh' Exists: 1f4a1.png Exists: 1f4c8.png Exists: 1f4dd.png Exists: 1f539.png Exists: 1f600.png Exists: 1f604.png Exists: 1f680.png Exists: 26a0.png Downloading: 2705.png Done. Files saved in ~/Documents/language/norsk/norskprøver/B2/exam notes/emoji. Map to filter names as needed (already matching).The script downloads only missing PNGs. If you add more codes to
twemoji_manifest.json, just run it again.To refresh files, delete specific PNGs (or all) in emoji and rerun.
Add to
unicode_mapinemoji.luato point to the same filename.- Example:
["⚠️"] = "26a0.png",
This ensures when you use the emoji directly, it maps to the correct image file.
- Example:
Optionally add a shortcode mapping in
emoji.lua’semoji_mapto point to the same filename.- Example:
[":warning:"] = "26a0.png",
This allows you to use the shortcode
:warning:in addition to the direct emoji.- Example:
🎯 Usage Examples
You can now use emojis in your QMD files in two ways:
- Direct Unicode: Great job! 👍 This is amazing! 🎉
- Shortcodes: Great job!
:thumbsup:This is amazing!:tada:
ref:
4.4.10 Divs and Spans
You can add classes, attributes, and other identifiers to regions of content using Divs and Spans.
- classes:
.class - identifiers:
#id - key-value attributes:
key="value"
Note that:
They are separated by spaces, do NOT use commas.
This is different from
bookdown, which uses commas.Order: identifiers, classes, and then key-value attributes.
Logical attributes:
true/false,yes/no, andon/offare all equivalent toTRUE/FALSEin R.It is optional to enclose in quotes.
4.4.10.1 Block Attributes
Apply attributes to a block of content, such as a paragraph, list, or code block.
Div example:
Once rendered to HTML, Quarto will translate the markdown into:
Note that:
The Div should be separated by blank lines from preceding and following blocks.
Fenced divs can be nested.
For example
will be rendered to
More examples
Headings with attributes
renders to:
List with attributes
renders to:
Paragrphs with attributes
renders to:
4.4.10.2 Inline Attributes
Apply attributes to inline text, such as selected words within a paragraph.
A bracketed sequence of inlines [text here] (as one would use to begin a link) will be treated as a <span> with attributes if it is followed immediately by attributes {attributes here}.
Syntax for inline attributes:
Once rendered to HTML, Quarto will translate the markdown into
Note that:
No space between
]and{.Ordering of attributes matter.
#idcomes first then.classthenkey="val".Any of these can be omitted, but must follow that order if they are provided.
Valid example:
Invalid example:
Use example:
renders to:
4.4.11 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:
cnj-title: The title prefix used for conjecture captions.cnj-prefix: The prefix used for an inline reference to a conjecture.
4.4.12 Tables
Tables in Latex
Tables in raw LaTeX can be included in Quarto documents using fenced divs or code chunks with {=latex}.
- Use fenced div to add labels
#tbl-xxxfor cross-referencing. Note the#is mandatory. Without it, the table cross reference will show as??in the output.- You can ignore the fenced divs if you don’t need cross-reference.
- Refer to the table using
@tbl-xxx.
::: {#tbl-1}
```{=latex}
% Or whatever actual you want, includegraphics, whatever.
% (_not_ \begin{table}, just the content of it)
\begin{tabular}{l c r}
\hline
Header 1 & Header 2 & Header 3 \\
\hline
Row 1 Col 1 & Row 1 Col 2 & Row 1 Col 3 \\
Row 2 Col 1 & Row 2 Col 2 & Row 2 Col 3 \\
\hline
\end{tabular}
```
This is a table caption.
:::
For cross-reference: See @tbl-1.Alternatively, use LaTeX syntax entirely as follows.
The regression results are summarized in Table \ref{tbl-regression-results}.
```{=latex}
\begin{table}
\centering
\caption{Regression Results: CAPM vs. Fama-French 3-Factor Model}
\label{tbl-regression-results}
\begin{tabular}{l c r}
\hline
Header 1 & Header 2 & Header 3 \\
\hline
Row 1 Col 1 & Row 1 Col 2 & Row 1 Col 3 \\
Row 2 Col 1 & Row 2 Col 2 & Row 2 Col 3 \\
\hline
\end{tabular}
\end{table}
```Q: How to use [H] to force table placement in qmd?
A: Add the following to the preamble file:
\usepackage{float} % for [H] placement specifier
% Make all tables use [H] placement by default
\makeatletter
\renewenvironment{table}[1][H]{%
\@float{table}[#1]%
}{%
\end@float
}
\makeatotherref: https://github.com/quarto-dev/quarto-cli/discussions/6734#discussioncomment-6919437
Tables in Markdown
You can create tables using standard Markdown syntax.
| Col1 | Col2 | Col3 |
| ---- | ---- | ---- |
| A | B | C |
| E | F | G |
| A | G | G |
: My Caption {#tbl-letters .striped .hover}
See @tbl-letters for the table.Captions are added using Pandoc table syntax:
:␣Caption text.Table labels and attributes can be added within curly braces
{}after the caption.If your table does not have a caption, you can still add attributes by placing them directly after
:␣You can also explicitly specify columns widths using the
tbl-colwidthsattribute or document-level option. If you have a table with two columns, and want to set 1st col to 25% and 2nd col to 75% of the table width, you can do:
ref: https://quarto.org/docs/authoring/tables.html#markdown-tables
4.4.13 Raw Content
Raw content can be included directly without Quarto parsing it using Pandoc’s raw attribute. A raw block starts with ```{= followed by a format and closing }, e.g. here’s a raw HTML block:
```{=html}
<iframe src="https://quarto.org/" width="500" height="400"></iframe>
```
For PDF output use a raw LaTeX block:
```{=latex}
\renewcommand*{\labelitemi}{\textgreater}
```
4.4.14 Lists
Will be rendered as:
- ordered list
- item 2
- sub-item 1 A. sub-sub-item 1
Quarto uses Pandoc’s Markdown, which supports a variety of ordered list types, including:
- numbers: 1. 2. 3.
- letters: a. b. c. or A. B. C.
- roman numerals: i. ii. iii. or I. II. III.
These list markers / labels need to be followed by a period and a space. Optionally, list markers may be enclosed in parentheses or followed by a single right-parentheses or period.
Special list marker @ can be used for sequentially numbered examples. The benefit of using @ is that when the list is broken up by other content, the numbering will continue correctly.
(@) My first example will be numbered (1).
(@) My second example will be numbered (2).
Explanation of examples. ← This breaks list structure.
(@) My third example will be numbered (3).Q: How to start numbering at a number other than 1?
A: Simply explicitly restart the list at the number you want.
Code block
3. item 3
1. item 4
will be rendered as:
- item 1
- item 2
Code block
- item 3
- item 4
ref: https://stackoverflow.com/a/78497776
4.4.15 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## Headingin the callout bodyIt can be any level of heading.
icon = falseto 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-xxxsyntax. 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 toappearance = "simple" icon = falsein 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.15.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.
4.4.15.2 Cross-reference Callouts
To cross-reference a callout, add an ID attribute that starts with the appropriate callout prefix (see Table blow). You can then reference the callout using the usual @ syntax. For example, here we add the ID #tip-example to the callout, and then refer back to it:
::: {#tip-example .callout-tip}
## Cross-Referencing a Tip
Add an ID starting with `#tip-` to reference a tip.
:::
See @tip-example...Note that the ID attribute must come first, before the class attribute.
This follows the general rule for Divs and Spans that IDs must come before classes.
The prefixes for each type of callout are:
Prefixes for callout cross-references
| Callout Type | Prefix |
|---|---|
note |
#nte- |
| — | — |
tip |
#tip- |
warning |
#wrn- |
important |
#imp- |
caution |
#cau- |
Cross-referencing callouts is currently only supported for HTML, PDF and MS Word.
4.4.16 Conditional Content
In some cases you may want to create content that only displays for a given output format (or only displays when not rendering to a format). You can accomplish this by creating divs, spans and code blocks with the .content-visible and .content-hidden classes.
E.g., you have a home assignment file and you want to have two versions of it: one for questions only, and the other for questions and solutions.
You can set a metadata variable in yaml, e.g., solutions: true or solutions: false.
---
title: "Quiz: Linear Regression and Hypothesis Testing (p1)"
from: markdown+tex_math_single_backslash
solution: false
# solution: true
format:
pdf:
include-in-header: ../latex/preamble.tex
fontsize: 12pt
---Then, in the body of your document, you can use the following syntax to conditionally include or exclude content based on the value of the solutions variable.
::: {.content-visible when-meta="solutions"}
This content will only be visible if `solutions` is set to `true`.
Put your solutions here.
:::Expected behavior:
- If
solutions: true, the content will be displayed. - If
solutions: false, the content will be hidden.
You can use multiple levels of metadata keys separated by periods. For example,
::: {.content-hidden unless-meta="path.to.metadata"}
This content will be hidden unless there exists a metadata entry like such:
```yml
path:
to:
metadata: true
```
:::You need to use unless-meta="path.to.metadata" to refer to your
user defined metadata key.
4.4.16.1 Set up multiple profiles
You can also set up multiple profiles in _quarto.yml, so you can just run quarto render --profile with-solutions / --profile no-solutions in terminal to render the document with or without solutions.
project:
type: book
output-dir: docs
profiles:
with-solutions:
metadata:
solutions: true
no-solutions:
metadata:
solutions: falseYou can then render the document with solutions using --profile argument:
Default profile
To define a default profile, add a default option to the profile key. For example, to make the with-solutions profile the default, you can use the following configuration:
Then, you can simply run quarto render without specifying a profile, and it will use the with-solutions profile by default.
4.4.16.2 Conditional Code Blocks
Q: Conditional contents NOT working for code blocks.
A: It’s because .content-visible runs after code execution. knitr executes the chunk and emits output even if the wrapper later hides the surrounding Markdown. Control the chunk itself with the meta flag.
Solution: Use params in rmarkdown.
In the YAML header, define a parameter
solutionwith a default value offalse.--- title: "Home Assignment" from: markdown+tex_math_single_backslash params: solution: false # solution: true ---solution: falsemeans do not show solutions by default.solution: truemeans show solutions.
Using a code chunk to get the value of the parameter. Put it at the beginning of the document as part of a global setup.
For following code chunks, you can use
eval=.solution, include=.solutionto control whether to evaluate and include the chunk based on the value of.solution.- When
.solutionisTRUE, the chunk will be evaluated and included in the output.- If you still want to evaluate but not include in the output, use
include=.solutiononly
- If you still want to evaluate but not include in the output, use
- when
.solutionisFALSE, the chunk will not be evaluated or included in the output.
- When
For regular text, use fenced divs with
.content-visibleandwhen-meta="solution"to conditionally include or exclude content based on the value of thesolutionparameter.::: {.content-visible when-meta="params.solution"} This content will only be visible if `solution` is set to `true`. Put your solutions here. :::- Use the attributes
unless-metaandwhen-meta, and use periods.to separate metadata keys. solutionis a second-level key underparams, so you need to useparams.solutionto refer to it.
- Use the attributes
Use scenarios:
- When preparing the assignment, you can set
solution: trueto see the solutions while editing. - After you finish editing, set
solution: falseto hide the solutions before submission.
When you want to render the document with solutions, you can set the parameter solution to true in the YAML header or use command line arguments.
ref:
- https://jadeyryan.quarto.pub/cascadia-quarto/4-conditionals/
- meta variables: https://quarto.org/docs/authoring/variables.html
References: