page_content
stringlengths
0
33.5k
metadata
dict
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview Quarto has a wide variety of options available for controlling how code and computational output appear within rendered documents. In this tutorial we’ll take a .qmd file that has some numeric output and plots, and cover how to apply these options. This tutorial will make use of the matplotlib and plotly Python packages. The commands you can use to install them are given in the table below. Platform Commands Mac/Linux Terminal python3 -m pip install jupyter matplotlib plotly pandas Windows Terminal py -m pip install jupyter matplotlib plotly pandas If you want to follow along step-by-step in your own environment, create a computations.qmd file and copy the following content into it. --- title: Quarto Computations jupyter: python3 --- ## NumPy ```{python} import numpy as np a = np.arange(15).reshape(3, 5) a ``` ## Matplotlib ```{python} import matplotlib.pyplot as plt fig = plt.figure() x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)') plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True') plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True, label='uplims=True, lolims=True') upperlimits = [True, False] * 5 lowerlimits = [False, True] * 5 plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits, label='subsets of uplims and lolims') plt.legend(loc='lower right') plt.show(fig) ``` ## Plotly ```{python} import plotly.express as px import plotly.io as pio gapminder = px.data.gapminder() gapminder2007 = gapminder.query("year == 2007") fig = px.scatter(gapminder2007, x="gdpPercap", y="lifeExp", color="continent", size="pop", size_max=60, hover_name="country") fig.show() ``` Now, open a Terminal and run quarto preview, then position your editor side-by-side with the browser showing the preview. Terminal quarto preview computations.qmd Cell Output All of the code in the source file is displayed within the rendered document. However, in some cases, you may want to hide all of the code and just show the output. Let’s go ahead and specify echo: false within the document execute options to prevent code from being printed. --- title: Quarto Computations execute: echo: false jupyter: python3 --- Save the file after making this change. The preview will update to show the output with no code. You might want to selectively enable code echo for some cells. To do this add the echo: true cell option. Try this with the NumPy cell. ```{python} #| echo: true import numpy as np a = np.arange(15).reshape(3, 5) a ``` Save the file and note that the code is now included for the NumPy cell. There a large number of other options available for cell output, for example warning to show/hide warnings (which can be especially helpful for package loading messages), include as a catch all for preventing any output (code or results) from being included in output, and error to prevent errors in code execution from halting the rendering of the document (and print the error in the rendered document). See the Jupyter Cell Options documentation for additional details. Code Folding Rather than hiding code entirely, you might want to fold it and allow readers to view it at their discretion. You can do this via the code-fold option. Remove the echo option we previously added and add the code-fold HTML format option. --- title: Quarto Computations format: html: code-fold: true jupyter: python3 --- Save the file. Now a “Code” widget is available above the output of each cell. You can also provide global control over code folding. Try adding code-tools: true to the HTML format options. --- title: Quarto Computations format: html: code-fold: true code-tools: true jupyter: python3 --- Save the file and you’ll see that a code menu appears at the top right of the document that provides global control over showing and hiding code. Figures Let’s improve the appearance of our Matplotlib output. It could certainly stand to be wider, and it would be nice to provide a caption and a label for cross-referencing. Go ahead and modify the Matplotlib cell to include label and fig-cap options as well as a call to fig.set_size_inches() to set a larger figure size with a wider aspect ratio: ```{python} #| label: fig-limits #| fig-cap: "Errorbar limit selector" import matplotlib.pyplot as plt fig = plt.figure() fig.set_size_inches(12, 7) ``` Save the file to re-render and see the updated plot: Multiple Figures The Plotly cell visualizes GDP and life expectancy data from a single year (2007). Let’s plot another year next to it for comparison and add a caption and subcaptions. Since this will produce a wider visualization we’ll also use the column option to lay it out across the entire page rather than being constrained to the body text column. There are quite a few changes to this cell. Copy and paste this code into computations.qmd if you want to try them locally: #| label: fig-gapminder #| fig-cap: "Life Expectancy and GDP" #| fig-subcap: #| - "Gapminder: 1957" #| - "Gapminder: 2007" #| layout-ncol: 2 #| column: page import plotly.express as px import plotly.io as pio gapminder = px.data.gapminder() def gapminder_plot(year): gapminderYear = gapminder.query("year == " + str(year)) fig = px.scatter(gapminderYear, x="gdpPercap", y="lifeExp", size="pop", size_max=60, hover_name="country") fig.show() gapminder_plot(1957) gapminder_plot(2007) Save the file, the preview will update as follows: Let’s discuss some of the new options used here. You’ve seen fig-cap before but we’ve now added a fig-subcap option: #| fig-cap: "Life Expectancy and GDP" #| fig-subcap: #| - "Gapminder: 1957" #| - "Gapminder: 2007" For code cells with multiple outputs adding the fig-subcap option enables us to treat them as subfigures. We also added an option to control how multiple figures are laid out—in this case we specified side-by-side in two columns: #| layout-ncol: 2 If you have 3, 4, or more figures in a panel there are many options available for customizing their layout. See the article Figures for details. Finally, we added an option to control the span of the page that our figures occupy: #| column: page This allows our figure display to span out beyond the normal body text column. See the documentation on Article Layout to learn about all of the available layout options. Next Up You’ve now covered the basics of customizing the behavior and output of executable code in Quarto documents. Next, check out the the Authoring Tutorial to learn more about output formats and technical writing features like citations, crossrefs, and advanced layout.
{ "lastmod": "2023-07-05T19:35:15.431Z", "loc": "https://quarto.org/docs/get-started/computations/text-editor.html", "source": "https://quarto.org/docs/get-started/computations/text-editor.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview Quarto supports executable code blocks within markdown. This allows you to create fully reproducible documents and reports—the code required to produce your output is part of the document itself, and is automatically re-run whenever the document is rendered. In this tutorial we’ll show you how to author fully reproducible computational documents with Quarto in RStudio. If you would like to follow along step-by-step in your own environment, download the Quarto document (.qmd) below, open it in RStudio, and click on Render (or use the keyboard shortcut ⇧⌘K). We recommend also checking the box for Render on Save for a live preview of your changes. Download computations.qmd Note that you will need to open this document in RStudio v2022.07 or later, which you can download here. Cell Output By default, the code and its output are displayed within the rendered document. However, for some documents, you may want to hide all of the code and just show the output. To do so, specify echo: false within the execute option in the YAML. --- title: "Quarto Computations" execute: echo: false --- If you checked Render on Save earlier, just save the document after making this change for a live preview. Otherwise render the document to see your updates reflected. The result will look like the following. You might want to selectively enable code echo for some cells. To do this add the echo: true cell option. Try this with the chunk labelled scatterplot. #| label: scatterplot #| echo: true ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) + geom_point(alpha = 0.5, size = 2) + scale_color_viridis_c() + theme_minimal() Save the document again and note that the code is now included for the scatterplot chunk. The echo option can be set to true, false, or fenced. The last one might be of special interest for writing documentation and teaching materials as it allows you to include the fenced code delimiter in your code output to emphasize that executable code requires that delimiter. You can read more about this option in the Fenced Echo documentation. There are a large number of other options available for cell output, for example warning for showing/hiding warnings (which can be especially helpful for package loading messages), include as a catch all for preventing any output (code or results) from being included in output, and error to prevent errors in code execution from halting the rendering of the document (and print the error in the rendered document). See the Knitr Cell Options documentation for additional details. Code Folding Rather than hiding code entirely, you might want to fold it and allow readers to view it at their discretion. You can do this via the code-fold option. Remove the echo option we previously added and add the code-fold HTML format option. --- title: "Quarto Computations" format: html: code-fold: true --- Save the document again and note that new Code widgets are now included for each code chunk. You can also provide global control over code folding. Try adding code-tools: true to the HTML format options. --- title: "Quarto Computations" format: html: code-fold: true code-tools: true --- Save the document and you’ll see that a code menu appears at the top right of the rendered document that provides global control over showing and hiding all code. Code Linking The code-link option enables hyper-linking of functions within code blocks to their online documentation. Try adding code-link: true to the HTML format options. --- title: "Quarto Computations" format: html: code-link: true --- Save the document and observe that the functions are now clickable hyperlinks. Note that code linking is currently implemented only for the knitr engine via the downlit package. Figures We can improve the appearance and accessibility of our plot. We can change its aspect ratio by setting fig-width and fig-height, provide a fig-cap, modify its label for cross referencing, and add alternative text with fig-alt. We’ll add the following chunk options. #| label: fig-scatterplot #| fig-cap: "City and highway mileage for 38 popular models of cars." #| fig-alt: "Scatterplot of city vs. highway mileage for cars, where points are colored by the number of cylinders. The plot displays a positive, linear, and strong relationship between city and highway mileage, and mileage increases as the number of cylinders decreases." #| fig-width: 6 #| fig-height: 3.5 Save the document to see the updated plot. Note that we have also updated the narrative with a cross reference to this figure using the following. @fig-scatterplot shows a positive, strong, and linear relationship between the city and highway mileage of these cars. Multiple Figures Let’s add another plot to our chunk—a scatterplot where the points are colored by engine displacement, using a different color scale. Our goal is to display these plots side-by-side (i.e., in two columns), with a descriptive subcaption for each plot. Since this will produce a wider visualization we’ll also use the column option to lay it out across the entire page rather than being constrained to the body text column. There are quite a few changes to this chunk. To follow along, copy and paste the options outlined below into your Quarto document. #| label: fig-mpg #| fig-cap: "City and highway mileage for 38 popular models of cars." #| fig-subcap: #| - "Color by number of cylinders" #| - "Color by engine displacement, in liters" #| layout-ncol: 2 #| column: page ggplot(mpg, aes(x = hwy, y = cty, color = cyl)) + geom_point(alpha = 0.5, size = 2) + scale_color_viridis_c() + theme_minimal() ggplot(mpg, aes(x = hwy, y = cty, color = displ)) + geom_point(alpha = 0.5, size = 2) + scale_color_viridis_c(option = "E") + theme_minimal() Additionally, replace the existing text that describes the visualization with the following. The plots in @fig-mpg show the relationship between city and highway mileage for 38 popular models of cars. In @fig-mpg-1 the points are colored by the number of cylinders while in @fig-mpg-2 the points are colored by engine displacement. Then, save the document and inspect the rendered output, which should look like the following. Let’s discuss some of the new options used here. You’ve seen fig-cap before but we’ve now added a fig-subcap option. #| fig-cap: "City and highway mileage for 38 popular models of cars." #| fig-subcap: #| - "Color by number of cylinders" #| - "Color by engine displacement, in liters" For code cells with multiple outputs adding the fig-subcap option enables us to treat them as subfigures. We also added an option to control how multiple figures are laid out—in this case we specified side-by-side in two columns. #| layout-ncol: 2 If you have 3, 4, or more figures in a panel there are many options available for customizing their layout. See the article Figure Layout for details. Finally, we added an option to control the span of the page that our figures occupy. #| column: page This allows our figure display to span out beyond the normal body text column. See the documentation on Article Layout to learn about all of the available layout options. Data Frames You can control how data frames are printed by default using the df-print document option. Available options include: Option Description default Use the default S3 method for the data frame. kable 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 (implemented using rmarkdown::paged_table()) For example, here we specify that we want paged printing for data frames: --- title: "Document" format: html: df-print: paged --- Inline Code To include executable expressions within markdown, enclose the expression in `r `. For example, we can use inline code to state the number of observations in our data. Try adding the following markdown text to your Quarto document. There are `r nrow(mpg)` observations in our data. Save your document and inspect the rendered output. The expression inside the backticks has been executed and the sentence includes the actual number of observations. There are 234 observations in our data. If the expression you want to inline is more complex, involving many functions or a pipeline, we recommend including it in a code chunk (with echo: false) and assigning the result to an object. Then, you can call that object in your inline code. For example, say you want to state the average city and highway mileage in your data. First, compute these values in a code chunk. #| echo: false mean_cty <- round(mean(mpg$cty), 2) mean_hwy <- round(mean(mpg$hwy), 2) Then, add the following markdown text to your Quarto document. The average city mileage of the cars in our data is `r mean_cty` and the average highway mileage is `r mean_hwy`. Save your document and inspect the rendered output. The average city mileage of the cars in our data is 16.86 and the average highway mileage is 23.44. Caching If your document includes code chunks that take too long to compute, you might want to cache the results of those chunks. You can use the cache option either at the document level using the YAML execute option. execute: cache: true However caching all code chunks in a document may not be preferable. You can also indicate which chunks should be cached directly with using a chunk option. #| cache: true Try adding this chunk option to one of the code chunks in your document that produces a plot and save. When the document is rendered, you’ll see that a new folder has been created in your working directory with the same name as your document and the suffix _cache. This folder contains the cached results. You can find out more about caching in Quarto documents in the Cache documentation. If you followed along step-by-step with this tutorial, you should now have a Quarto document that implements everything we covered. Otherwise, you can download a completed version of computations.qmd below. Download computations-complete.qmd Next Up You’ve now covered the basics of customizing the behavior and output of executable code in Quarto documents. Next, check out the the Authoring Tutorial to learn more about output formats and technical writing features like citations, crossrefs, and advanced layout.
{ "lastmod": "2023-07-05T19:35:15.431Z", "loc": "https://quarto.org/docs/get-started/computations/rstudio.html", "source": "https://quarto.org/docs/get-started/computations/rstudio.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview Quarto has a wide variety of options available for controlling how code and computational output appear within rendered documents. In this tutorial we’ll take a simple notebook that has some numeric output and plots, and cover how to apply these options. If you want to follow along step-by-step in your own environment, download the notebook below: Download computations.ipynb Then, create a new directory to work within and copy the notebook into this directory. Once you’ve done that, switch to this directory in a Terminal, install notebook dependencies (if necessary), and open Jupyter Lab to get started working with the notebook. The commands you can use for installation and opening Jupyter Lab are given in the table below. Platform Commands Mac/Linux Terminal python3 -m pip install jupyter matplotlib plotly python3 -m jupyter lab computations.ipynb Windows Terminal py -m pip install jupyter matplotlib plotly py -m jupyter lab computations.ipynb The notebook as we start out is shown below. Note that none of the cells are executed yet. --- title: Quarto Computations jupyter: python3 --- ## NumPy ```{python} import numpy as np a = np.arange(15).reshape(3, 5) a ``` ## Matplotlib ```{python} import matplotlib.pyplot as plt fig = plt.figure() x = np.arange(10) y = 2.5 * np.sin(x / 20 * np.pi) yerr = np.linspace(0.05, 0.2, 10) plt.errorbar(x, y + 3, yerr=yerr, label='both limits (default)') plt.errorbar(x, y + 2, yerr=yerr, uplims=True, label='uplims=True') plt.errorbar(x, y + 1, yerr=yerr, uplims=True, lolims=True, label='uplims=True, lolims=True') upperlimits = [True, False] * 5 lowerlimits = [False, True] * 5 plt.errorbar(x, y, yerr=yerr, uplims=upperlimits, lolims=lowerlimits, label='subsets of uplims and lolims') plt.legend(loc='lower right') plt.show(fig) ``` ## Plotly ```{python} import plotly.express as px import plotly.io as pio gapminder = px.data.gapminder() gapminder2007 = gapminder.query("year == 2007") fig = px.scatter(gapminder2007, x="gdpPercap", y="lifeExp", color="continent", size="pop", size_max=60, hover_name="country") fig.show() ``` Next, create a new Terminal within Jupyter Lab to use for Quarto commands. Finally, run quarto preview in the Terminal, and position Jupyter Lab side-by-side with the browser showing the preview. Terminal quarto preview computations.ipynb Go ahead and run all of the cells and then save the notebook. You’ll see that the preview updates immediately. Cell Output All of the code in the notebook is displayed within the rendered document. However, for some documents, you may want to hide all of the code and just show the output. Let’s go ahead and specify echo: false within the document execute options to prevent code from being printed. --- title: Quarto Computations execute: echo: false jupyter: python3 --- Save the notebook after making this change. The preview will update to show the output with no code. You might want to selectively enable code echo for some cells. To do this add the echo: true cell option. Try this with the NumPy cell. ```{python} #| echo: true import numpy as np a = np.arange(15).reshape(3, 5) a ``` Save the notebook and note that the code is now included for the NumPy cell. There a large number of other options available for cell output, for example warning to show/hide warnings (which can be especially helpful for package loading messages), include as a catch all for preventing any output (code or results) from being included in output, and error to prevent errors in code execution from halting the rendering of the document (and print the error in the rendered document). See the Jupyter Cell Options documentation for additional details. Code Folding Rather than hiding code entirely, you might want to fold it and allow readers to view it at their discretion. You can do this via the code-fold option. Remove the echo option we previously added and add the code-fold HTML format option. --- title: Quarto Computations execute: code-fold: true jupyter: python3 --- Save the notebook. Now a “Code” widget is available above the output of each cell. You can also provide global control over code folding. Try adding code-tools: true to the HTML format options. --- title: Quarto Computations execute: code-fold: true code-tools: true jupyter: python3 --- Save the notebook and you’ll see that a code menu appears at the top right of the document that provides global control over showing and hiding code. ```{python} #| label: fig-limits #| fig-cap: "Errorbar limit selector" import matplotlib.pyplot as plt fig = plt.figure() fig.set_size_inches(12, 7) ``` Let’s improve the appearance of our Matplotlib output. It could certainly stand to be wider, and it would be nice to provide a caption and a label for cross-referencing. Go ahead and modify the Matplotlib cell to include label and fig-cap options as well as a call to fig.set_size_inches() to set a larger figure size with a wider aspect ratio. ```{python} #| label: fig-limits #| fig-cap: "Errorbar limit selector" import matplotlib.pyplot as plt fig = plt.figure() fig.set_size_inches(12, 7) ``` Execute the cell to see the updated plot. Then, save the notebook so that the Quarto preview is updated. Multiple Figures The Plotly cell visualizes GDP and life expectancy data from a single year (2007). Let’s plot another year next to it for comparison and add a caption and subcaptions. Since this will produce a wider visualization we’ll also use the column option to lay it out across the entire page rather than being constrained to the body text column. There are quite a few changes to this cell. Copy and paste the code below into the notebook if you want to try them locally. #| label: fig-gapminder #| fig-cap: "Life Expectancy and GDP" #| fig-subcap: #| - "Gapminder: 1957" #| - "Gapminder: 2007" #| layout-ncol: 2 #| column: page import plotly.express as px import plotly.io as pio gapminder = px.data.gapminder() def gapminder_plot(year): gapminderYear = gapminder.query("year == " + str(year)) fig = px.scatter(gapminderYear, x="gdpPercap", y="lifeExp", size="pop", size_max=60, hover_name="country") fig.show() gapminder_plot(1957) gapminder_plot(2007) Run the modified cell then save the notebook. The preview will update as follows: Let’s discuss some of the new options used here. You’ve seen fig-cap before but we’ve now added a fig-subcap option. #| fig-cap: "Life Expectancy and GDP" #| fig-subcap: #| - "Gapminder: 1957" #| - "Gapminder: 2007" For code cells with multiple outputs adding the fig-subcap option enables us to treat them as subfigures. We also added an option to control how multiple figures are laid out—in this case we specified side-by-side in two columns. #| layout-ncol: 2 If you have 3, 4, or more figures in a panel there are many options available for customizing their layout. See the article on Figures for details. Finally, we added an option to control the span of the page that our figures occupy. #| column: page This allows our figure display to span out beyond the normal body text column. See the documentation on Article Layout to learn about all of the available layout options. Next Up You’ve now covered the basics of customizing the behavior and output of executable code in Quarto documents. Next, check out the the Authoring Tutorial to learn more about output formats and technical writing features like citations, crossrefs, and advanced layout.
{ "lastmod": "2023-07-05T19:35:15.431Z", "loc": "https://quarto.org/docs/get-started/computations/jupyter.html", "source": "https://quarto.org/docs/get-started/computations/jupyter.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview In this tutorial we’ll explore more of Quarto’s authoring features. We’ll cover rendering documents in multiple formats and show you how to add components like table of contents, equations, citations, cross-references, and more. Output Formats Quarto supports rendering notebooks to dozens of different output formats. By default, the html format is used, but you can specify an alternate format (or formats) within document options. Format Options Let’s create a new file (authoring.qmd) and define various formats for it to be rendered to, adding some options to each of the formats. As a reminder, document options are specified in YAML at the beginning of the source file. --- title: "Quarto Document" author: "Norah Jones" format: pdf --- We specified pdf as the default output format (if we exclude the format option then it will default to html). Let’s add some options to control our PDF output. --- title: "Quarto Document" author: "Norah Jones" format: pdf: toc: true number-sections: true --- Multiple Formats Some documents you create will have only a single output format, however in many cases it will be desirable to support multiple formats. Let’s add the html and docx formats to our document. --- title: "Quarto Document" author: "Norah Jones" toc: true number-sections: true highlight-style: pygments format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=20mm docx: default --- There’s a lot to take in here! Let’s break it down a bit. The first two lines are generic document metadata that aren’t related to output formats at all. title: "Quarto Document" author: "Norah Jones" The next three lines are document format options that apply to all formats. which is why they are specified at the root level. toc: true number-sections: true highlight-style: pygments Next, we have the format option, where we provide format-specific options. format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=30mm docx: default The html and pdf formats each provide an option or two. For example, for the HTML output we want the user to have control over whether to show or hide the code (code-fold: true) and use katex for math text. For PDF we define some margins. The docx format is a bit different—it specifies docx: default. This means just use all of the default options for the format. Rendering The formats specified within document options define what is rendered by default. If we render the document with all the options given above using the following. Terminal quarto render authoring.qmd Then the following files would be created. authoring.html authoring.pdf authoring.docx We can select one or more formats using the --to option. Terminal quarto render authoring.qmd --to docx quarto render authoring.qmd --to docx,pdf Note that the target file (in this case authoring.qmd) should always be the very first command line argument. If needed we can also render formats that aren’t specified within document options. Terminal quarto render authoring.qmd --to odt Since the odt format isn’t included within document options, the default options for the format will be used. Sections You can use a table of contents and/or section numbering to make it easier for readers to navigate your document. Do this by adding the toc and/or number-sections options to document options. Note that these options are typically specified at the root level because they are shared across all formats. --- title: Quarto Basics author: Norah Jones date: 'May 22, 2021' toc: true number-sections: true --- ## Colors - Red - Green - Blue ## Shapes - Square - Circle - Triangle ## Textures - Smooth - Bumpy - Fuzzy Here’s what this document looks like when rendered to HTML. There are lots of options available for controlling how the table of contents and section numbering behave. See the output format documentation (e.g. HTML, PDF, MS Word) for additional details. Equations You can use LaTeX equations within markdown. Einstein's theory of special relatively that expresses the equivalence of mass and energy: $E = mc^{2}$ This appears as follows when rendered. Einstein’s theory of special relatively that expresses the equivalence of mass and energy: \(E = mc^{2}\) Inline equations are delimited with $…$. To create equations in a new line (display equation) use $$…$$. See the documentation on markdown equations for additional details. Citations To cite other works within a Quarto document. First create a bibliography file in a supported format (BibTeX or CSL). Then, link the bibliography to your document using the bibliography YAML metadata option. Here’s a document that includes a bibliography and single citation. --- title: Quarto Basics format: html bibliography: references.bib jupyter: python3 --- ## Overview Knuth says always be literate [@knuth1984]. ```{python} 1 + 1 ``` ## References Note that items within the bibliography are cited using the @citeid syntax. Knuth says always be literate [@knuth1984]. References will be included at the end of the document, so we include a ## References heading at the bottom of the source file. Here is what this document looks like when rendered. The @ citation syntax is very flexible and includes support for prefixes, suffixes, locators, and in-text citations. See the documentation on Citations and Footnotes to learn more. Cross References Cross-references make it easier for readers to navigate your document by providing numbered references and hyperlinks to figures, tables, equations, and sections. Cross-reference-able entities generally require a label (unique identifier) and a caption. This example illustrates cross-referencing various types of entities. --- title: Quarto Crossrefs format: html jupyter: python3 --- ## Overview See @fig-simple in @sec-plot for a demonstration of a simple plot. See @eq-stddev to better understand standard deviation. ## Plot {#sec-plot} ```{python} #| label: fig-simple #| fig-cap: "Simple Plot" import matplotlib.pyplot as plt plt.plot([1,23,2,4]) plt.show() ``` ## Equation {#sec-equation} $$ s = \sqrt{\frac{1}{N-1} \sum_{i=1}^N (x_i - \overline{x})^2} $$ {#eq-stddev} We cross-referenced sections, figures, and equations. The table below shows how we expressed each of these. Entity Reference Label / Caption Section @sec-plot ID added to heading: # Plot {#sec-plot} Figure @fig-simple YAML options in code cell: #| label: fig-simple #| fig-cap: "Simple Plot" Equation @eq-stddev At end of display equation: $$ {#eq-stddev} And finally, here is what this document looks like when rendered. See the article on Cross References to learn more, including how to customize caption and reference text (e.g. use “Fig.” rather than “Figure”). Callouts Callouts are an excellent way to draw extra attention to certain concepts, or to more clearly indicate that certain content is supplemental or applicable to only some scenarios. Callouts are markdown divs that have special callout attributes. To create a callout within a markdown cell, type the following in your document. ::: {.callout-note} Note that there are five types of callouts, including: `note`, `tip`, `warning`, `caution`, and `important`. ::: This appears as follows when rendered. Note Note that there are five types of callouts, including note, tip, warning, caution, and important. You can learn more about the different types of callouts and options for their appearance in the Callouts documentation. Article Layout The body of Quarto articles have a default width of approximately 700 pixels. This width is chosen to optimize readability. This normally leaves some available space in the document margins and there are a few ways you can take advantage of this space. In this example, we use the reference-location option to indicate that we would like footnotes to be placed in the right margin. We also use the column: screen-inset cell option to indicate we would like our figure to occupy the full width of the screen, with a small inset. --- title: Quarto Layout format: html reference-location: margin jupyter: python3 --- ## Placing Colorbars Colorbars indicate the quantitative extent of image data. Placing in a figure is non-trivial because room needs to be made for them. The simplest case is just attaching a colorbar to each axes:^[See the [Matplotlib Gallery](https://matplotlib.org/stable/gallery/subplots_axes_and_figures/colorbar_placement.html) to explore colorbars further]. ```{python} #| code-fold: true #| column: screen-inset import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 2) fig.set_size_inches(20, 8) cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh( np.random.random((20, 20)) * (col + 1), cmap=cmaps[col] ) fig.colorbar(pcm, ax=ax) plt.show() ``` Here is what this document looks like when rendered. You can locate citations, footnotes, and asides in the margin. You can also define custom column spans for figures, tables, or other content. See the documentation on Article Layout for additional details. Learning More You’ve now learned the basics of using Quarto! Once you feel comfortable creating and customizing documents here are a few more things to explore: Presentations — Author PowerPoint, Beamer, and Revealjs presentations using the same syntax you’ve learned for creating documents. Websites — Publish collections of documents as a website. Websites support multiple forms of navigation and full-text search. Blogs — Create a blog with an about page, flexible post listings, categories, RSS feeds, and over twenty themes. Books — Create books and manuscripts in print (PDF, MS Word) and online (HTML, ePub) formats. Interactivity — Include interactive components to help readers explore the concepts and data you are presenting more deeply.
{ "lastmod": "2023-07-05T19:35:15.387Z", "loc": "https://quarto.org/docs/get-started/authoring/text-editor.html", "source": "https://quarto.org/docs/get-started/authoring/text-editor.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview In this tutorial we’ll show you how to author Quarto documents in RStudio. In particular, we’ll discuss the various document formats you can produce with the same source code and show you how to add components like table of contents, equations, citations, etc. The visual markdown editor in RStudio makes many of these tasks easier so we’ll highlight its use in this tutorial, but note that it’s possible to accomplish these tasks in the source editor as well. If you would like to follow along step-by-step in your own environment, make sure that you have the latest release of RStudio (v2023.03), which you can download here, installed. Output Formats Quarto supports rendering notebooks to dozens of different output formats. By default, the html format is used, but you can specify an alternate format (or formats) within document options. Format Options You can choose the format you want to render your Quarto document to at the time of creating your new document. To create a new document, go to File > New File > Quarto Document… Alternatively, use the command palette (accessible via Ctrl+Shift+P), search for Create a new Quarto document and hit return. In the Title field, give a title for your document (e.g. the screenshot below suggests “Housing Prices”) and add your name to the Author field. Next, you will select the output format for your document. By default, RStudio suggests using HTML as the output, let’s leave that default for now. A new document will be created with the following YAML. --- title: "Housing Prices" author: "Mine Çetinkaya-Rundel" --- Note that our format choice (HTML) is not even reflected in the YAML as it is the default output format for Quarto documents. However you can directly edit the YAML to change the output format, e.g. to PDF (pdf) or MS Word (docx). Add format: pdf to your document’s YAML as shown below. --- title: "Housing Prices" author: "Mine Çetinkaya-Rundel" format: pdf --- Unfortunately, this document has no content, so rendering it would not result in very interesting output. To make it a bit easier to demonstrate all the features we want to highlight in this tutorial, let’s close this empty document and start with one that has a little bit of content in it. If you would like to follow along step-by-step in your own environment, download the Quarto document (.qmd) below and open it in RStudio. Download authoring.qmd In order to create PDFs you will need to install a recent distribution of LaTeX. We recommend the use of TinyTeX (which is based on TexLive), which you can install with the following command: Terminal quarto install tinytex See the article on PDF Engines for details on using other LaTeX distributions and PDF compilation engines. Once you have LaTeX setup, click on Render (or use the keyboard shortcut ⇧⌘K). We recommend also checking the box for Render on Save for a live preview of your changes. As shown below, you should see the rendered PDF in the Viewer in RStudio. Next, let’s add an option to the YAML, e.g. to add line numbers to the code chunks (code-line-numbers: true). Add this option to your document’s YAML as shown below, paying attention to the indentation scheme. Under format: our format choice pdf is indented (with two spaces) and it’s followed by : to indicate that further options for that format will be specified. In the next line, further indented by two spaces, we add code-line-numbers: true. --- title: "Housing Prices" author: "Mine Çetinkaya-Rundel" format: pdf: code-line-numbers: true --- If you checked Render on Save earlier, just save the document after making this change for a live preview. Otherwise render the document to see your updates reflected, including a table of contents that looks like the following. An incredibly exciting format option that we won’t go into too much detail in this tutorial is revealjs. Yes, you can make presentations with Quarto as well! In fact, Quarto supports a variety of formats for creating presentations, including revealjs for HTML slides, pptx for PowerPoint, and beamer for LaTeX/PDF. The Presentations article gives a thorough walk through of creating slide decks with Quarto. Multiple Formats Some documents you create will have only a single output format, however in many cases it will be desirable to support multiple formats. Let’s add the html and docx formats to our document and modify some options specific to each format. --- title: "Housing Prices" author: "Mine Çetinkaya-Rundel" highlight-style: pygments format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=30mm docx: default --- There’s a lot to take in here! Let’s break it down a bit. The first two lines are generic document metadata that aren’t related to output formats at all. --- title: "Housing Prices" author: "Mine Çetinkaya-Rundel" --- The next line is a document format option that applies to all formats, which is why it is specified at the root level. --- highlight-style: pygments --- Next, we have the format option, where we provide format-specific options. --- format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=30mm docx: default --- The html and pdf formats each provide an option or two. For example, for the HTML output we want the user to have control over whether to show or hide the code (code-fold: true) and use katex for math text. For PDF we define some margins. The docx format is a bit different—it specifies docx: default. This indicates that we just want to use all of the default options for the format. Rendering Clicking the Render button (or using the keyboard shortcut ⇧⌘K) in RStudio will render the document to the first format listed in the YAML. Note that the Render button also has a drop down menu that enables you to render to any of the formats listed in YAML front matter: If you would like to render to all formats, you can do so with the quarto package, which provides an R interface to the Quarto CLI. For example, to render the current document, use quarto::quarto_render(). You can also specify the name of the document you want to render as well as the output format(s). quarto::quarto_render( "authoring.qmd", output_format = c("pdf", "html", "docx") ) As a result, you will see three new files appear in your Files pane: authoring.docx authoring.html authoring.pdf Sections You can use a table of contents and/or section numbering to make it easier for readers to navigate your document. Do this by adding the toc and/or number-sections options to document options. Note that these options are typically specified at the root level because they are shared across all formats. --- title: "Housing Prices" author: "Mine Çetinkaya-Rundel" toc: true number-sections: true highlight-style: pygments format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=30mm docx: default --- Here’s what this document looks like when rendered to HTML. There are lots of options available for controlling how the table of contents and section numbering behave. See the output format documentation (e.g. HTML, PDF, MS Word) for additional details. Equations If you are using the visual editor mode, you can add LaTeX equations to Quarto documents in RStudio using the Insert Anything tool. You can access it with / at the beginning of an empty block or Cmd+/ anywhere else. Display equations (in a new line) are delimited with $$…$$ while inline equations are delimited with $…$. Add the following as display math in the document. price = \hat{\beta}_0 + \hat{\beta}_1 \times area + \epsilon RStudio displays a rendered version of the tutorial as you type it in the editor. See the documentation on markdown equations for additional details. Citations The Insert Anything tool can also be used to insert citations to your document. In the next window you can insert a citation via from a variety of sources including your document bibliography, Zotero personal or group libraries, DOI (Document Object Identifier) references, and searches of Crossref, DataCite, or PubMed. You can find out more about citations with the visual editor here. Select From DOI on the left and copy-and-paste the DOI 10.1093/comjnl/27.2.97 in the search bar and hit Search. Then, select the found reference, and Insert it into your document. If this is the first citation you are adding to your document, RStudio will automatically create a bibliography file for you. This file is called references.bib by default and RStudio will also add bibliography: references.bib to your document’s YAML metadata. Note that items within the bibliography are cited using the @citeid syntax. Add the following text to your document. We're going to do this analysis using literate programming [@knuth1984]. References will be included at the end of the document, so we include a ## References heading at the bottom of the notebook. You might also add .unnumbered class to this section by clicking on the three dots (…) to edit its attributes. Here is what this document looks like when rendered (with middle sections removed to highlight the relevant parts. The @ citation syntax is very flexible and includes support for prefixes, suffixes, locators, and in-text citations. See the documentation on Citations and Footnotes to learn more. Cross References Cross-references make it easier for readers to navigate your document by providing numbered references and hyperlinks to figures, tables, equations, and sections. Cross-reference-able entities generally require a label (unique identifier) and a caption. For example, to add a label to the equation inserted earlier, click on the three dots to edit its attributes and use the suggested format (starting with #eq-) to label the equation. Then, add a cross reference using the Insert Anything tool in the visual editor. You might add a sentence like "We can fit a simple linear regression model of the form shown in" to contextualize the cross reference and then add the reference to the end of that sentence. In the Insert Cross Reference menu, navigate to the desired cross reference entity on the left, and select the equation labeled earlier. Alternatively, start typing the label of the equation to be referenced in the visual editor, and the autofill tool will bring up the cross references to choose from. Below we illustrate cross-referencing various types of entities using fragments from the document you’ve been working with. We present the results of exploratory data analysis in @sec-eda and the regression model in @sec-model. @fig-scatterplot displays the relationship between these two variables in a scatterplot. @tbl-stats displays basic summary statistics for these two variables. We can fit a simple linear regression model of the form shown in @eq-slr. This examples include cross-referenced sections, figures, and equations. The table below summarizes how we express each of these. Entity Reference Label / Caption Section @sec-eda ID added to heading: # Exploratory data analysis {#sec-eda} Figure @fig-scatterplot YAML options in code cell: #| label: fig-scatterplot #| fig-cap: "Scatterplot of price vs. area of houses in Duke Forest" Table @tbl-stats YAML options in code cell: #| label: tbl-stats #| tbl-cap: "Summary statistics for price and area of houses in Duke Forest" Equation @eq-slr At end of display equation: $$ {#eq-slr} See the article on Cross References to learn more, including how to customize caption and reference text (e.g. use “Fig.” rather than “Figure”). Callouts Callouts are an excellent way to draw extra attention to certain concepts, or to more clearly indicate that certain content is supplemental or applicable to only some scenarios. Callouts are markdown divs that have special callout attributes. We can insert a callout using the Insert Anything tool. In the subsequent dialogue you can select one of five types of callout (note, tip, important, caution, or warning), customize its appearance (default, simple, or minimal), and decide whether you want to show the icon. Then, try inserting the following text in the callout box. This is a pretty incomplete analysis, but hopefully the document provides a good overview of some of the authoring features of Quarto! Here is what a callout looks like in the visual editor. And here is the rendered callout in the output document. You can learn more about the different types of callouts and options for their appearance in the Callouts documentation. Article Layout The body of Quarto articles have a default width of approximately 700 pixels. This width is chosen to optimize readability. This normally leaves some available space in the document margins and there are a few ways you can take advantage of this space. We can use the column: page-right cell option to indicate we would like our figure to occupy the full width of the screen, with some inset. Go ahead and add this chunk option to the chunk labeled fig-histogram. #| label: fig-histogram #| fig-cap: "Histograms of individual variables" #| fig-subcap: #| - "Histogram of `price`s" #| - "Histogram of `area`s" #| layout-ncol: 2 #| column: page-right Here is what the relevant section of the document looks like when rendered. You can locate citations, footnotes, and asides in the margin. You can also define custom column spans for figures, tables, or other content. See the documentation on Article Layout for additional details. Publishing Once your document is rendered to HTML, you can publish to RPubs (a free service from RStudio for sharing documents on the web) simply by clicking the Publish button on the editor toolbar or preview window. Alternatively, you can use the quarto::quarto_publish_doc() function. quarto::quarto_publish_doc( "authoring.qmd", server = "rpubs.com" ) Other possible publishing options include RStudio Connect and ShinyApps as well as GitHub Pages, Netlify, etc. The Publishing HTML article gives a much more detailed overview of your publishing options. If you followed along step-by-step with this tutorial, you should now have a Quarto document that implements everything we covered. Otherwise, you can download a completed version of computations.qmd below. Download authoring-complete.qmd Learning More You’ve now learned the basics of using Quarto! Once you feel comfortable creating and customizing documents here are a few more things to explore: Presentations — Author PowerPoint, Beamer, and Revealjs presentations using the same syntax you’ve learned for creating documents. Websites — Publish collections of documents as a website. Websites support multiple forms of navigation and full-text search. Blogs — Create a blog with an about page, flexible post listings, categories, RSS feeds, and over twenty themes. Books — Create books and manuscripts in print (PDF, MS Word) and online (HTML, ePub) formats. Interactivity — Include interactive components to help readers explore the concepts and data you are presenting more deeply.
{ "lastmod": "2023-07-05T19:35:15.387Z", "loc": "https://quarto.org/docs/get-started/authoring/rstudio.html", "source": "https://quarto.org/docs/get-started/authoring/rstudio.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview In this tutorial we’ll show you how to author Quarto documents in Jupyter Lab. In particular, we’ll discuss the various document formats you can produce and show you how to add components like table of contents, equations, citations, cross-references, and more. Output Formats Quarto supports rendering notebooks to dozens of different output formats. By default, the html format is used, but you can specify an alternate format (or formats) within document options. Format Options Let’s create a notebook and define various formats for it to be rendered to and add some options to each of the formats. As a reminder, document options are specified in YAML within a “Raw” cell at the beginning of the notebook. To create a Raw cell, add a cell at the top of the notebook and set its type to Raw using the notebook toolbar: Now, let’s add some basic document metadata and a default output format. --- title: "Quarto Document" author: "Norah Jones" format: pdf jupyter: python3 --- We specified pdf as the default output format (if we exclude the format option then it will default to html). Let’s add some options to control our PDF output. --- title: "Quarto Document" author: "Norah Jones" format: pdf: toc: true number-sections: true jupyter: python3 --- Multiple Formats Some documents you create will have only a single output format, however in many cases it will be desirable to support multiple formats. Let’s add the html and docx formats to our document. --- title: "Quarto Document" author: "Norah Jones" toc: true number-sections: true highlight-style: pygments format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=20mm docx: default jupyter: python3 --- There’s a lot to take in here! Let’s break it down a bit. The first two lines are generic document metadata that aren’t related to output formats at all. title: "Quarto Document" author: "Norah Jones" The next three lines are document format options that apply to all formats. which is why they are specified at the root level. toc: true number-sections: true highlight-style: pygments Next, we have the format option, where we provide format-specific options. format: html: code-fold: true html-math-method: katex pdf: geometry: - top=30mm - left=30mm docx: default The html and pdf formats each provide an option or two. For example, for the HTML output we want the user to have control over whether to show or hide the code (code-fold: true) and use katex for math text. For PDF we define some margins. The docx format is a bit different—it specifies docx: default. This means just use all of the default options for the format. Rendering The formats specified within document options define what is rendered by default. If we render the notebook with all the options given above using the following. Terminal quarto render notebook.ipynb Then, the following files would be created. notebook.html notebook.pdf notebook.docx We can select one or more formats using the --to option. Terminal quarto render notebook.ipynb --to docx quarto render notebook.ipynb --to docx,pdf Note that the target file (in this case notebook.ipynb) should always be the very first command line argument. If needed we can also render formats that aren’t specified within document options. Terminal quarto render notebook.ipynb --to odt Since the odt format isn’t included within document options, the default options for the format will be used. Note that when rendering an .ipynb Quarto will not execute the cells within the notebook by default (the presumption being that you already executed them while editing the notebook). If you want to execute the cells you can pass the --execute flag to render. Terminal quarto render notebook.ipynb --execute Sections You can use a table of contents and/or section numbering to make it easier for readers to navigate your document. Do this by adding the toc and/or number-sections options to document options. Note that these options are typically specified at the root level because they are shared across all formats. --- title: Quarto Basics author: Norah Jones date: 'May 22, 2021' toc: true number-sections: true jupyter: python3 --- ## Colors - Red - Green - Blue ## Shapes - Square - Circle - Triangle ## Textures - Smooth - Bumpy - Fuzzy Here’s what this document looks like when rendered to HTML. There are lots of options available for controlling how the table of contents and section numbering behave. See the output format documentation (e.g. HTML, PDF, MS Word) for additional details. Equations You can add LaTeX equations to markdown cells within Jupyter Lab. Einstein's theory of special relatively that expresses the equivalence of mass and energy: $E = mc^{2}$ \(E = mc^{2}\) Equations are rendered when you run the cell. Inline equations are delimited with $…$. To create equations in a new line (display equation) use $$…$$. See the documentation on markdown equations for additional details. Citations To cite other works within a Quarto document. First create a bibliography file in a supported format (BibTeX or CSL). Then, link the bibliography to your document using the bibliography YAML metadata option. Here’s a notebook that includes a bibliography and single citation. Note that markdown cells are un-executed so you can see all of the syntax. --- title: Quarto Basics format: html bibliography: references.bib jupyter: python3 --- ## Overview Knuth says always be literate [@knuth1984]. ```{python} 1 + 1 ``` ## References Note that items within the bibliography are cited using the @citeid syntax. Knuth says always be literate [@knuth1984]. References will be included at the end of the document, so we include a ## References heading at the bottom of the notebook. Here is what this document looks like when rendered. The @ citation syntax is very flexible and includes support for prefixes, suffixes, locators, and in-text citations. See the documentation on Citations and Footnotes to learn more. Cross References Cross-references make it easier for readers to navigate your document by providing numbered references and hyperlinks to figures, tables, equations, and sections. Cross-reference-able entities generally require a label (unique identifier) and a caption. The notebook below illustrates cross-referencing various types of entities. Once again, the markdown cells are again un-executed so that the syntax is visible. --- title: Quarto Crossrefs format: html jupyter: python3 --- ## Overview See @fig-simple in @sec-plot for a demonstration of a simple plot. See @eq-stddev to better understand standard deviation. ## Plot {#sec-plot} ```{python} #| label: fig-simple #| fig-cap: "Simple Plot" import matplotlib.pyplot as plt plt.plot([1,23,2,4]) plt.show() ``` ## Equation {#sec-equation} $$ s = \sqrt{\frac{1}{N-1} \sum_{i=1}^N (x_i - \overline{x})^2} $$ {#eq-stddev} \[ x + 1 \] This example includes cross-referenced sections, figures, and equations. The table below shows how we expressed each of these. Entity Reference Label / Caption Section @sec-plot ID added to heading: # Plot {#sec-plot} Figure @fig-simple YAML options in code cell: #| label: fig-simple #| fig-cap: "Simple Plot" Equation @eq-stddev At end of display equation: $$ {#eq-stddev} And finally, here is what this notebook looks like when rendered. See the article on Cross References to learn more, including how to customize caption and reference text (e.g. use “Fig.” rather than “Figure”). Callouts Callouts are an excellent way to draw extra attention to certain concepts, or to more clearly indicate that certain content is supplemental or applicable to only some scenarios. Callouts are markdown divs that have special callout attributes. Here’s an example of creating a callout within a markdown cell. ::: {.callout-note} Note that there are five types of callouts, including: `note`, `tip`, `warning`, `caution`, and `important`. ::: When we ultimately render the document with Quarto the callout appears as intended. Note Note that there are five types of callouts, including note, tip, warning, caution, and important. You can learn more about the different types of callouts and options for their appearance in the Callouts documentation. Article Layout The body of Quarto articles have a default width of approximately 700 pixels. This width is chosen to optimize readability. This normally leaves some available space in the document margins and there are a few ways you can take advantage of this space. In this notebook, we use the reference-location option to indicate that we would like footnotes to be placed in the right margin. We also use the column: screen-inset cell option to indicate we would like our figure to occupy the full width of the screen, with a small inset. --- title: Quarto Layout format: html reference-location: margin jupyter: python3 --- ## Placing Colorbars Colorbars indicate the quantitative extent of image data. Placing in a figure is non-trivial because room needs to be made for them. The simplest case is just attaching a colorbar to each axes:^[See the [Matplotlib Gallery](https://matplotlib.org/stable/gallery/subplots_axes_and_figures/colorbar_placement.html) to explore colorbars further]. ```{python} #| code-fold: true #| column: screen-inset import matplotlib.pyplot as plt import numpy as np fig, axs = plt.subplots(2, 2) fig.set_size_inches(20, 8) cmaps = ['RdBu_r', 'viridis'] for col in range(2): for row in range(2): ax = axs[row, col] pcm = ax.pcolormesh( np.random.random((20, 20)) * (col + 1), cmap=cmaps[col] ) fig.colorbar(pcm, ax=ax) plt.show() ``` Here is what this document looks like when rendered. You can locate citations, footnotes, and asides in the margin. You can also define custom column spans for figures, tables, or other content. See the documentation on Article Layout for additional details. Learning More You’ve now learned the basics of using Quarto! Once you feel comfortable creating and customizing documents here are a few more things to explore: Presentations — Author PowerPoint, Beamer, and Revealjs presentations using the same syntax you’ve learned for creating documents. Websites — Publish collections of documents as a website. Websites support multiple forms of navigation and full-text search. Blogs — Create a blog with an about page, flexible post listings, categories, RSS feeds, and over twenty themes. Books — Create books and manuscripts in print (PDF, MS Word) and online (HTML, ePub) formats. Interactivity — Include interactive components to help readers explore the concepts and data you are presenting more deeply.
{ "lastmod": "2023-07-05T19:35:15.387Z", "loc": "https://quarto.org/docs/get-started/authoring/jupyter.html", "source": "https://quarto.org/docs/get-started/authoring/jupyter.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview In this tutorial we’ll show you how to use your favorite text editor with Quarto. You’ll edit plain text .qmd files and preview the rendered document in a web browser as you work. Below is an overview of how this will look. The notebook on the left is rendered into the HTML version you see on the right. This is the basic model for Quarto publishing—take a source document (in this case a notebook) and render it to a variety of output formats, including HTML, PDF, MS Word, etc. The tutorials will make use of the matplotlib and plotly Python packages—the commands you can use to install them are given in the table below. Platform Commands Mac/Linux Terminal python3 -m pip install jupyter matplotlib plotly Windows Terminal py -m pip install jupyter matplotlib plotly Note Note that while this tutorial uses Python, using Julia (via the IJulia kernel) is also well supported. See the article on Using Julia for additional details. Editor Modes If you are using VS Code, you should install the Quarto Extension for VS Code before proceeding. The extension provides syntax highlighting for markdown and embedded languages, completion for embedded languages (e.g. Python, R, Julia, LaTeX, etc.), commands and key-bindings for running cells and selected line(s), and much more. There are also Quarto syntax highlighting modes available for several other editors: Editor Extension Emacs https://github.com/quarto-dev/quarto-emacs Vim / Neovim https://github.com/quarto-dev/quarto-vim Neovim https://github.com/quarto-dev/quarto-nvim Sublime Text https://github.com/quarto-dev/quarto-sublime Rendering We’ll start out by rendering a simple example (hello.qmd) to a couple of formats. If you want to follow along step-by-step in your own environment, create a new file named hello.qmd and copy the following content into it. --- title: "Quarto Basics" format: html: code-fold: true jupyter: python3 --- For a demonstration of a line plot on a polar axis, see @fig-polar. ```{python} #| label: fig-polar #| fig-cap: "A line plot on a polar axis" import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots( subplot_kw = {'projection': 'polar'} ) ax.plot(theta, r) ax.set_rticks([0.5, 1, 1.5, 2]) ax.grid(True) plt.show() ``` Next, open a Terminal and switch to the directory containing hello.qmd. Let’s start by rendering the document to a couple of formats. Terminal quarto render hello.qmd --to html quarto render hello.qmd --to docx Note that the target file (in this case hello.qmd) should always be the very first command line argument. When you render a .qmd file with Quarto, the executable code blocks are processed by Jupyter, and the resulting combination of code, markdown, and output is converted to plain markdown. Then, this markdown is processed by Pandoc, which creates the finished format. Authoring The quarto render command is used to create the final version of your document for distribution. However, during authoring you’ll use the quarto preview command. Try it now from the Terminal with hello.qmd. Terminal quarto preview hello.qmd This will render your document and then display it in a web browser. You might want to position your editor and the browser preview side-by-side so you can see changes as you work. To see live preview in action: Change the the line of code that defines theta as follows: theta = 4 * np.pi * r Save the file. The document is re-rendered, and the browser preview is updated. This is the basic workflow for authoring with Quarto. There are few different types of content in hello.qmd, let’s work a bit with each type. YAML Options At the top of the file there is a YAML block with document level options. --- title: "Quarto Basics" format: html: code-fold: true jupyter: python3 --- Try changing the code-fold option to false: format: html: code-fold: false Then save the file. You’ll notice that the code is now shown above the plot, where previously it was hidden with a Code button that could be used to show it. Markdown Narrative content is written using markdown. Here we specify a header and a cross-reference to the figure created in the code cell below. ## Polar Axis For a demonstration of a line plot on a polar axis, see @fig-polar. Try changing the header and saving the notebook—the preview will update with the new header text. Code Cells Code cells contain executable code to be run during render, with the output (and optionally the code) included in the rendered document. ```{python} #| label: fig-polar #| fig-cap: "A line plot on a polar axis" import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots( subplot_kw = {'projection': 'polar'} ) ax.plot(theta, r) ax.set_rticks([0.5, 1, 1.5, 2]) ax.grid(True) plt.show() ``` You are likely familiar with the Matplotlib code given here. However, there are some less familiar components at the top of the code cell: label and fig-cap options. Cell options are written in YAML using a specially prefixed comment (#|). In this example, the cell options are used to make the figure cross-reference-able. Try changing the fig-cap and/or the code, running the cell, and then saving the file to see the updated preview. There are a wide variety of cell options that you can apply to tailor your output. We’ll delve into these options in the next tutorial. Note One particularly useful cell option for figures is fig-alt, which enables you to add alternative text to images for users with visual impairments. See Amy Cesal’s article on Writing Alt Text for Data Visualization to learn more. Next Up You now know the basics of creating and authoring Quarto documents. The following tutorials explore Quarto in more depth: Tutorial: Computations — Learn how to tailor the behavior and output of executable code blocks. Tutorial: Authoring — Learn more about output formats and technical writing features like citations, crossrefs, and advanced layout.
{ "lastmod": "2023-07-05T19:35:15.467Z", "loc": "https://quarto.org/docs/get-started/hello/text-editor.html", "source": "https://quarto.org/docs/get-started/hello/text-editor.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview Quarto is a multi-language, next-generation version of R Markdown from Posit and includes dozens of new features and capabilities while at the same being able to render most existing Rmd files without modification. In this tutorial, we’ll show you how to use RStudio with Quarto. You’ll edit code and markdown in RStudio just as you would with any computational document (e.g., R Markdown) and preview the rendered document in the Viewer tab as you work. The following is a Quarto document with the extension .qmd (on the left), along with its rendered version as HTML (on the right). You could also choose to render it into other formats like PDF, MS Word, etc. This is the basic model for Quarto publishing—take a source document and render it to a variety of output formats. If you would like a video introduction to Quarto before you dive into the tutorial, watch the Get Started with Quarto where you can see a preview of authoring a Quarto document with executable code chunks, rendering to multiple formats, including revealjs presentations, creating a website, and publishing on QuartoPub. If you would like to follow along with this tutorial in your own environment, follow the steps outlined below. Download and install the latest release of RStudio (v2023.03): Download RStudio v2023.03 Be sure that you have installed the tidyverse and palmerpenguins packages: install.packages("tidyverse") install.packages("palmerpenguins") Download the Quarto document (.qmd) below, open it in RStudio, and click on Render. Download hello.qmd Rendering Use the Render button in the RStudio IDE to render the file and preview the output with a single click or keyboard shortcut (⇧⌘K). If you prefer to automatically render whenever you save, you can check the Render on Save option on the editor toolbar. The preview will update whenever you re-render the document. Side-by-side preview works for both HTML and PDF outputs. Note that documents can also be rendered from the R console via the quarto package: install.packages("quarto") quarto::quarto_render("hello.qmd") When rendering, Quarto generates a new file that contains selected text, code, and results from the .qmd file. The new file can be an HTML, PDF, MS Word document, presentation, website, book, interactive document, or other format. Authoring In the image below, we can see the same document in the two modes of the RStudio editor: visual (on the left) and source (on the right). RStudio’s visual editor offers an WYSIWYM authoring experience for markdown. For formatting (e.g., bolding text), you can use the toolbar, a keyboard shortcut (⌘B), or the markdown construct (**bold**). The plain text source code underlying the document is written for you, and you can view/edit it at any point by switching to source mode for editing. You can toggle back and forth between these two modes by clicking on Source and Visual in the editor toolbar (or using the keyboard shortcut ⌘⇧ F4). Next, let’s turn our attention to the contents of our Quarto document. The file contains three types of content: a YAML header, code chunks, and markdown text. YAML header An (optional) YAML header demarcated by three dashes (---) on either end. --- title: "Hello, Quarto" format: html editor: visual --- When rendered, the title, "Hello, Quarto", will appear at the top of the rendered document with a larger font size than the rest of the document. The other two YAML fields denote that the output should be in html format and the document should open in the visual editor by default. The basic syntax of YAML uses key-value pairs in the format key: value. Other YAML fields commonly found in headers of documents include metadata like author, subtitle, date as well as customization options like theme, fontcolor, fig-width, etc. You can find out about all available YAML fields for HTML documents here. The available YAML fields vary based on document format, e.g., see here for YAML fields for PDF documents and here for MS Word. Code chunks R code chunks identified with {r} with (optional) chunk options, in YAML style, identified by #| at the beginning of the line. ```{r} #| label: load-packages #| include: false library(tidyverse) library(palmerpenguins) ``` In this case, the label of the code chunk is load-packages, and we set include to false to indicate that we don’t want the chunk itself or any of its outputs in the rendered documents. In addition to rendering the complete document to view the results of code chunks, you can also run each code chunk interactively in the RStudio editor by clicking the icon or keyboard shortcut (⇧⌘⏎). RStudio executes the code and displays the results either inline within your file or in the Console, depending on your preference. Markdown text Text with formatting, including section headers, hyperlinks, an embedded image, and an inline code chunk. Quarto uses markdown syntax for text. If using the visual editor, you won’t need to learn much markdown syntax for authoring your document, as you can use the menus and shortcuts to add a header, bold text, insert a table, etc. If using the source editor, you can achieve these with markdown expressions like ##, **bold**, etc. How it works When you render a Quarto document, first knitr executes all of the code chunks and creates a new markdown (.md) document, which includes the code and its output. The markdown file generated is then processed by pandoc, which creates the finished format. The Render button encapsulates these actions and executes them in the right order for you. Next Up You now know the basics of creating and authoring Quarto documents. The following tutorials explore Quarto in more depth: Tutorial: Computations — Learn how to tailor the behavior and output of executable code blocks. Tutorial: Authoring — Learn more about output formats and technical writing features like citations, crossrefs, and advanced layout.
{ "lastmod": "2023-07-05T19:35:15.467Z", "loc": "https://quarto.org/docs/get-started/hello/rstudio.html", "source": "https://quarto.org/docs/get-started/hello/rstudio.html" }
Choose your tool VS Code Jupyter RStudio Neovim Editor Overview In this tutorial we’ll show you how to use Jupyter Lab with Quarto. You’ll edit code and markdown in Jupyter Lab, just as you would with any notebook, and preview the rendered document in a web browser as you work. Below is an overview of how this will look. The notebook on the left is rendered into the HTML version you see on the right. This is the basic model for Quarto publishing—take a source document (in this case a notebook) and render it to a variety of output formats, including HTML, PDF, MS Word, etc. Note Note that while this tutorial uses Python, using Julia (via the IJulia kernel) is also well supported. See the article on Using Julia for additional details. Rendering We’ll start out by opening a notebook (hello.ipynb) in Jupyter Lab and rendering it to a couple of formats. If you want to follow along step-by-step in your own environment, download the notebook below. Download hello.ipynb Then, create a new directory to work within, copy the notebook into this directory, and switch to this directory in a Terminal. Next, execute these commands to install JupyterLab along with the packages used in the tutorial (matplotlib and plotly), and to open the tutorial notebook: Platform Commands Mac/Linux Terminal python3 -m pip install jupyter jupyterlab python3 -m pip install matplotlib plotly python3 -m jupyter lab hello.ipynb Windows Terminal py -m pip install jupyter jupyterlab py -m pip install matplotlib plotly py -m jupyter lab hello.ipynb Here is our notebook in Jupyter Lab. --- title: "Quarto Basics" format: html: code-fold: true jupyter: python3 --- For a demonstration of a line plot on a polar axis, see @fig-polar. ```{python} #| label: fig-polar #| fig-cap: "A line plot on a polar axis" import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots( subplot_kw = {'projection': 'polar'} ) ax.plot(theta, r) ax.set_rticks([0.5, 1, 1.5, 2]) ax.grid(True) plt.show() ``` Next, create a new Terminal within Jupyter Lab to use for Quarto commands. And finally, render the notebook to a couple of formats. Terminal quarto render hello.ipynb --to html quarto render hello.ipynb --to docx Note that the target file (in this case hello.ipynb) should always be the very first command line argument. When you render a Jupyter notebook with Quarto, the contents of the notebook (code, markdown, and outputs) are converted to plain markdown and then processed by Pandoc, which creates the finished format. Authoring The quarto render command is used to create the final version of your document for distribution. However, during authoring you’ll use the quarto preview command. Try it now from the Terminal with hello.ipynb. Terminal quarto preview hello.ipynb This will render your document and then display it in a web browser. You might want to position Jupyter Lab and the browser preview side-by-side so you can see changes as you work. To see live preview in action: Change the the line of code that defines theta as follows: theta = 4 * np.pi * r Re-run the code cell to generate a new version of the plot. Save the notebook (the preview will update automatically). This is the basic workflow for authoring with Quarto. Once you are comfortable with this, we also recommend installing the Quarto JupyterLab Extension which provides additional tools for working with Quarto in JupyterLab. There are few different types of cells in our notebook, let’s work a bit with each type. YAML Options You are likely already familiar with markdown and code cells, but there is a new type of cell (“Raw”) that is used for document-level YAML options. --- title: "Quarto Basics" format: html: code-fold: true jupyter: python3 --- Try changing the code-fold option to false. format: html: code-fold: false Then save the notebook. You’ll notice that the code is now shown above the plot, where previously it was hidden with a Code button that could be used to show it. Markdown Cells Markdown cells contain raw markdown that will be passed through to Quarto during rendering. You can use any valid Quarto markdown syntax in these cells. Here we specify a header and a cross-reference to the figure created in the code cell below. ## Polar Axis For a demonstration of a line plot on a polar axis, see @fig-polar. Try changing the header and saving the notebook—the preview will update with the new header text. Code Cells You are likely already familiar with code cells, like the one shown below. ```{python} #| label: fig-polar #| fig-cap: "A line plot on a polar axis" import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots( subplot_kw = {'projection': 'polar'} ) ax.plot(theta, r) ax.set_rticks([0.5, 1, 1.5, 2]) ax.grid(True) plt.show() ``` But there are some new components at the top of the code cell: label and fig-capoptions. Cell options are written in YAML using a specially prefixed comment (#|). In this example, the cell options are used to make the figure cross-reference-able. Try changing the fig-cap and/or the code, running the cell, and then saving the notebook to see the updated preview. There are a wide variety of cell options that you can apply to tailor your output. We’ll delve into these options in the next tutorial. Note One particularly useful cell option for figures is fig-alt, which enables you to add alternative text to images for users with visual impairments. See Amy Cesal’s article on Writing Alt Text for Data Visualization to learn more. Next Up You now know the basics of creating and authoring Quarto documents. The following tutorials explore Quarto in more depth: Tutorial: Computations — Learn how to tailor the behavior and output of executable code blocks. Tutorial: Authoring — Learn more about output formats and technical writing features like citations, crossrefs, and advanced layout. Additionally, you may want to install the Quarto JupyterLab Extension which provides additional tools for working with Quarto in JupyterLab.
{ "lastmod": "2023-07-05T19:35:15.467Z", "loc": "https://quarto.org/docs/get-started/hello/jupyter.html", "source": "https://quarto.org/docs/get-started/hello/jupyter.html" }
Overview When you introduce interactive components into a document you’ll want to be sure to lay them out in a fashion that optimizes for readability and navigation. There are of course a wide variety of ways you can incorporate interactivity spanning from visualizations embedded within a longer-form article all the way up to a more application/dashboard style layout. We’ll cover both of these layout scenarios below. We’ll use examples from both Observable JS and Shiny interactive documents—if you aren’t familiar with the code/syntax used for a given example just focus on the enclosing layout markup rather than the application code. Input Panel If you have several inputs, you may want to group them inside an input panel (code block with option panel: input or div with class .panel-input). For example: The inputs are grouped in a panel and laid out in three columns by adding the panel: input and layout-ncol: 3 options to the OJS code cell: ```{ojs} //| panel: input //| layout-ncol: 3 viewof ch = checkbox({ title: "Passport color:", options: [ { value: "red", label: "Red" }, { value: "green", label: "Green" }, { value: "blue", label: "Blue" }, { value: "black", label: "Black" } ], value: ["red", "green", "blue", "black"], submit: false }) viewof type = radio({ title: "Representation:", options: [ { label: 'Passports', value: 'p' }, { label: 'Circles', value: 'c' } ], value: 'p' }) viewof k = slider({ title: "Symbol size:", min: 1, max: 10, value: 3, step: 1 }) ``` Tabset Panel If you want to allow users to toggle between multiple visualizations, use a tabset (div with class .panel-tabset). Include a heading (e.g. ##) for each tab in the tabset. For example, here are a plot and data each presented in their own tab: data = FileAttachment("ojs/palmer-penguins.csv").csv({typed: true}) PlotData Plot.rectY(data, Plot.stackY( Plot.binX( {y: "count"}, {x: "body_mass_g", fill: "species", thresholds: 20}) ) ).plot({ facet: { data, x: "sex" }, marks: [Plot.frame()] }) Inputs.table(data) Here is the markup and code used to create the tabset: ::: {.panel-tabset} ## Plot ```{ojs} Plot.rectY(data, Plot.stackY( Plot.binX( {y: "count"}, {x: "body_mass_g", fill: "species", thresholds: 20}) ) ).plot({ facet: { data, x: "sex" }, marks: [Plot.frame()] }) ``` ## Data ```{ojs} Inputs.table(filtered) ``` ::: Full Page Layout By default Quarto documents center their content within the document viewport, and don’t exceed a maximum width of around 900 pixels. This behavior exists to optimize readability, but for an application layout you generally want to occupy the entire page. To do this, add the page-layout: custom option. For example: format: html: page-layout: custom Here’s an example of a Shiny application that occupies the full width of the browser: You’ll also note that the inputs are contained within a sidebar—the next section describes how to create sidebars. Sidebar Panel Sidebars are created using divs with class .panel-sidebar. You can do this using a markdown div container (as illustrated above for .panel-input), or, if the entire contents of your sidebar is created from a single code cell, by adding the panel: sidebar option to the cell. Sidebar panels should always have an adjacent panel with class .panel-fill or .panel-center which they will be laid out next to. The former (.panel-fill) will fill all available space, the latter (.panel-center) will leave some horizontal margin around its content. For example, here is the source code of the user-interface portion of the Shiny application displayed above: --- title: "Iris K-Means Clustering" format: html: page-layout: custom server: shiny --- ```{r} #| panel: sidebar vars <- setdiff(names(iris), "Species") selectInput('xcol', 'X Variable', vars) selectInput('ycol', 'Y Variable', vars, selected = vars[[2]]) numericInput('clusters', 'Cluster count', 3, min = 1, max = 9) ``` ```{r} #| panel: fill plotOutput('plot1') ``` The panel: fill option is added to the plot output chunk. You can alternately use panel: center if you want to leave some horizontal margin around the contents of the panel. Adding the panel option to a code chunk is shorthand for adding the CSS class to its containing div (i.e. it’s equivalent to surrounding the code chunk with a div with class e.g. panel-fill). Here’s an example of using a sidebar with OJS inputs: To do this you would use the following code: ```{ojs} //| panel: sidebar viewof myage = { const myage = select({ title: "Quelle classe d'âge voulez-vous cartographier ?", options: ages, value: "80etplus" }); return myage; } viewof pctvax = slider({ title: '<br/>Objectif de vaccination', description: '200% signifie 2 doses par personnes pour tout le monde', min: 50, max: 200, value: 200, step: 10, format: v => v + "%" }) viewof overlay = radio({ title: "Écarter les cercles", options: [{ label: 'Oui', value: 'Y' }, { label: 'Non', value: 'N' }], value: 'N' }) viewof label = radio({ title: "Numéros des départements", options: [{ label: 'Afficher', value: 'Y' }, { label: 'Masquer', value: 'N' }], value: 'N' }) ``` ```{ojs} //| panel: fill (vaccine visualization code) ``` Panel Layout You can arrange multiple interactive components into a panel using the layout attribute of a containing div. For example, here we have a main visualization in the first row and two ancillary visualizations in the second row: As described in the article on Figures, you can arrange panels of figures in very flexible fashion using the layout attribute. For the example above we enclosed the three visualizations in the following div: ::: {layout="[ [1], [1,1] ]"} (outputs) ::: Note that you can apply the layout attribute to a div that is already a panel (e.g. .panel-fill) to specify layout for content adjacent to a sidebar. So the following markup is also valid: ::: {.panel-sidebar} (inputs) ::: ::: {.panel-fill layout="[ [1], [1,1] ]"} (outputs) ::: The layout attribute is an array of arrays, each of which defines a row of the layout. Above we indicate that we want the first row to encompass the first visualization, and then to split the next two equally over the second row. The values in rows don’t need to add up to anything in particular (they are relative within each row), so we could have just as well have specified different relative widths for the second row if that was better suited to presenting our data: ::: {layout="[ [1], [3,2] ]"} (outputs) :::
{ "lastmod": "2023-07-05T19:35:15.479Z", "loc": "https://quarto.org/docs/interactive/layout.html", "source": "https://quarto.org/docs/interactive/layout.html" }
Demonstration of using the GitHub API. Code viewof repo = Inputs.radio( [ "pandas-dev/pandas", "tidyverse/ggplot2", ], { label: "Repo:", value: "pandas-dev/pandas"} ) Code import { chart } with { commits as data } from "@d3/d3-bubble-chart" chart Data d3 = require('d3') contributors = await d3.json( "https://api.github.com/repos/" + repo + "/stats/contributors" ) commits = contributors.map(contributor => { const author = contributor.author; return { name: author.login, title: author.login, group: author.type, value: contributor.total } }) Inputs.table(commits, { sort: "value", reverse: true }) Source Code --- title: "GitHub API" format: html: toc: false code-tools: true --- Demonstration of using the [GitHub API](https://developer.github.com/v3). ```{ojs} //| code-fold: true viewof repo = Inputs.radio( [ "pandas-dev/pandas", "tidyverse/ggplot2", ], { label: "Repo:", value: "pandas-dev/pandas"} ) ``` ```{ojs} //| code-fold: true import { chart } with { commits as data } from "@d3/d3-bubble-chart" chart ``` ## Data ```{ojs} d3 = require('d3') contributors = await d3.json( "https://api.github.com/repos/" + repo + "/stats/contributors" ) commits = contributors.map(contributor => { const author = contributor.author; return { name: author.login, title: author.login, group: author.type, value: contributor.total } }) ``` ```{ojs} Inputs.table(commits, { sort: "value", reverse: true }) ```
{ "lastmod": "2023-07-05T19:35:15.663Z", "loc": "https://quarto.org/docs/interactive/ojs/examples/github.html", "source": "https://quarto.org/docs/interactive/ojs/examples/github.html" }
This example demonstrates importing a notebook from ObervableHQ and replacing its data with data of our own (the code and data for this example were originally published here). First we read from a local JSON file into population: population = FileAttachment("population.json").json() Then we import from https://observablehq.com/@d3/zoomable-sunburst and specify that we’d like to use population instead of the data built in to the notebook: import { chart } with { population as data } from "@d3/zoomable-sunburst" Finally, we display the chart: chart Source Code --- title: "Population" format: html: code-tools: true toc: false --- This example demonstrates importing a notebook from ObervableHQ and replacing its data with data of our own (the code and data for this example were originally published [here](https://github.com/observablehq/examples/tree/main/custom-data)). First we read from a local JSON file into `population`: ```{ojs} population = FileAttachment("population.json").json() ``` Then we import from <https://observablehq.com/@d3/zoomable-sunburst> and specify that we'd like to use `population` instead of the data built in to the notebook: ```{ojs} import { chart } with { population as data } from "@d3/zoomable-sunburst" ``` Finally, we display the chart: ```{ojs} chart ```
{ "lastmod": "2023-07-05T19:35:15.663Z", "loc": "https://quarto.org/docs/interactive/ojs/examples/population.html", "source": "https://quarto.org/docs/interactive/ojs/examples/population.html" }
Simple demonstration of Arquero using Allison Horst’s Palmer Penguins dataset. import { aq, op } from '@uwdata/arquero' penguins = aq.loadCSV("palmer-penguins.csv") penguins.view() penguins .groupby('species') .filter(d => d.body_mass_g > 0) .rollup({ count: op.count(), avg_mass: op.average('body_mass_g') }) .view() If you want to use inputs in an arquero query, you can use the params method of table. Below is a simple example of filtering a dataset by the values provided. viewof bill_length_min = Inputs.range( [32, 50], {value: 35, step: 1, label: "Bill length (min):"} ) viewof islands = Inputs.checkbox( ["Torgersen", "Biscoe", "Dream"], { value: ["Torgersen", "Biscoe"], label: "Islands:" } ) penguins .params({ blm: bill_length_min, i: islands }) .filter((d, $) => op.includes($.i, d.island) && d.bill_length_mm > $.blm) .view() Source Code --- title: "Arquero" format: html: code-tools: true --- Simple demonstration of [Arquero](https://uwdata.github.io/arquero/) using Allison Horst's [Palmer Penguins](https://allisonhorst.github.io/palmerpenguins/) dataset. ```{ojs} import { aq, op } from '@uwdata/arquero' penguins = aq.loadCSV("palmer-penguins.csv") penguins.view() penguins .groupby('species') .filter(d => d.body_mass_g > 0) .rollup({ count: op.count(), avg_mass: op.average('body_mass_g') }) .view() ``` If you want to use inputs in an arquero query, you can use the `params` method of table. Below is a simple example of filtering a dataset by the values provided. ```{ojs} //| panel: input viewof bill_length_min = Inputs.range( [32, 50], {value: 35, step: 1, label: "Bill length (min):"} ) viewof islands = Inputs.checkbox( ["Torgersen", "Biscoe", "Dream"], { value: ["Torgersen", "Biscoe"], label: "Islands:" } ) ``` ```{ojs} penguins .params({ blm: bill_length_min, i: islands }) .filter((d, $) => op.includes($.i, d.island) && d.bill_length_mm > $.blm) .view() ```
{ "lastmod": "2023-07-05T19:35:15.663Z", "loc": "https://quarto.org/docs/interactive/ojs/examples/arquero.html", "source": "https://quarto.org/docs/interactive/ojs/examples/arquero.html" }
This variant of a sunburst diagram shows only two layers of the hierarchy at a time. Click a node to zoom in, or the center to zoom out. Compare to an icicle. Code sunburst = { const root = partition(flareData); root.each(d => d.current = d); const svg = d3.create("svg") .attr("viewBox", [0, 0, width, width]) .style("font", "15px sans-serif"); const g = svg.append("g") .attr("transform", `translate(${width / 2},${width / 2})`); const path = g.append("g") .selectAll("path") .data(root.descendants().slice(1)) .join("path") .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); }) .attr("fill-opacity", d => arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0) .attr("d", d => arc(d.current)); path.filter(d => d.children) .style("cursor", "pointer") .on("click", clicked); path.append("title") .text(d => `${d.ancestors().map(d => d.data.name).reverse().join("/")}\n${format(d.value)}`); const label = g.append("g") .attr("pointer-events", "none") .attr("text-anchor", "middle") .style("user-select", "none") .selectAll("text") .data(root.descendants().slice(1)) .join("text") .attr("dy", "0.35em") .attr("fill-opacity", d => +labelVisible(d.current)) .attr("transform", d => labelTransform(d.current)) .text(d => d.data.name); const parent = g.append("circle") .datum(root) .attr("r", radius) .attr("fill", "none") .attr("pointer-events", "all") .on("click", clicked); function clicked(event, p) { parent.datum(p.parent || root); root.each(d => d.target = { x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI, x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI, y0: Math.max(0, d.y0 - p.depth), y1: Math.max(0, d.y1 - p.depth) }); const t = g.transition().duration(750); // Transition the data on all arcs, even the ones that aren’t visible, // so that if this transition is interrupted, entering arcs will start // the next transition from the desired position. path.transition(t) .tween("data", d => { const i = d3.interpolate(d.current, d.target); return t => d.current = i(t); }) .filter(function(d) { return +this.getAttribute("fill-opacity") || arcVisible(d.target); }) .attr("fill-opacity", d => arcVisible(d.target) ? (d.children ? 0.6 : 0.4) : 0) .attrTween("d", d => () => arc(d.current)); label.filter(function(d) { return +this.getAttribute("fill-opacity") || labelVisible(d.target); }).transition(t) .attr("fill-opacity", d => +labelVisible(d.target)) .attrTween("transform", d => () => labelTransform(d.current)); } function arcVisible(d) { return d.y1 <= 3 && d.y0 >= 1 && d.x1 > d.x0; } function labelVisible(d) { return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03; } function labelTransform(d) { const x = (d.x0 + d.x1) / 2 * 180 / Math.PI; const y = (d.y0 + d.y1) / 2 * radius; return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`; } return svg.node(); } flareData = FileAttachment("flare-2.json").json() partition = flareData => { const root = d3.hierarchy(flareData) .sum(d => d.value) .sort((a, b) => b.value - a.value); return d3.partition() .size([2 * Math.PI, root.height + 1]) (root); } color = d3.scaleOrdinal( d3.quantize(d3.interpolateRainbow, flareData.children.length + 1) ) format = d3.format(",d") width = 932 radius = width / 6 arc = d3.arc() .startAngle(d => d.x0) .endAngle(d => d.x1) .padAngle(d => Math.min((d.x1 - d.x0) / 2, 0.005)) .padRadius(radius * 1.5) .innerRadius(d => d.y0 * radius) .outerRadius(d => Math.max(d.y0 * radius, d.y1 * radius - 1)) ReuseISC License Source Code --- title: "Sunburst" subtitle: "Originally published at <https://observablehq.com/@d3/zoomable-sunburst>" author: "Mike Bostock" date: "2018-04-30" license: ISC License format: html: toc: false code-tools: true --- This variant of a [sunburst diagram](https://observablehq.com/@d3/sunburst) shows only two layers of the hierarchy at a time. Click a node to zoom in, or the center to zoom out. Compare to an [icicle](https://observablehq.com/@d3/zoomable-icicle). ```{ojs} //| code-fold: true sunburst = { const root = partition(flareData); root.each(d => d.current = d); const svg = d3.create("svg") .attr("viewBox", [0, 0, width, width]) .style("font", "15px sans-serif"); const g = svg.append("g") .attr("transform", `translate(${width / 2},${width / 2})`); const path = g.append("g") .selectAll("path") .data(root.descendants().slice(1)) .join("path") .attr("fill", d => { while (d.depth > 1) d = d.parent; return color(d.data.name); }) .attr("fill-opacity", d => arcVisible(d.current) ? (d.children ? 0.6 : 0.4) : 0) .attr("d", d => arc(d.current)); path.filter(d => d.children) .style("cursor", "pointer") .on("click", clicked); path.append("title") .text(d => `${d.ancestors().map(d => d.data.name).reverse().join("/")}\n${format(d.value)}`); const label = g.append("g") .attr("pointer-events", "none") .attr("text-anchor", "middle") .style("user-select", "none") .selectAll("text") .data(root.descendants().slice(1)) .join("text") .attr("dy", "0.35em") .attr("fill-opacity", d => +labelVisible(d.current)) .attr("transform", d => labelTransform(d.current)) .text(d => d.data.name); const parent = g.append("circle") .datum(root) .attr("r", radius) .attr("fill", "none") .attr("pointer-events", "all") .on("click", clicked); function clicked(event, p) { parent.datum(p.parent || root); root.each(d => d.target = { x0: Math.max(0, Math.min(1, (d.x0 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI, x1: Math.max(0, Math.min(1, (d.x1 - p.x0) / (p.x1 - p.x0))) * 2 * Math.PI, y0: Math.max(0, d.y0 - p.depth), y1: Math.max(0, d.y1 - p.depth) }); const t = g.transition().duration(750); // Transition the data on all arcs, even the ones that aren’t visible, // so that if this transition is interrupted, entering arcs will start // the next transition from the desired position. path.transition(t) .tween("data", d => { const i = d3.interpolate(d.current, d.target); return t => d.current = i(t); }) .filter(function(d) { return +this.getAttribute("fill-opacity") || arcVisible(d.target); }) .attr("fill-opacity", d => arcVisible(d.target) ? (d.children ? 0.6 : 0.4) : 0) .attrTween("d", d => () => arc(d.current)); label.filter(function(d) { return +this.getAttribute("fill-opacity") || labelVisible(d.target); }).transition(t) .attr("fill-opacity", d => +labelVisible(d.target)) .attrTween("transform", d => () => labelTransform(d.current)); } function arcVisible(d) { return d.y1 <= 3 && d.y0 >= 1 && d.x1 > d.x0; } function labelVisible(d) { return d.y1 <= 3 && d.y0 >= 1 && (d.y1 - d.y0) * (d.x1 - d.x0) > 0.03; } function labelTransform(d) { const x = (d.x0 + d.x1) / 2 * 180 / Math.PI; const y = (d.y0 + d.y1) / 2 * radius; return `rotate(${x - 90}) translate(${y},0) rotate(${x < 180 ? 0 : 180})`; } return svg.node(); } ``` ```{ojs} flareData = FileAttachment("flare-2.json").json() partition = flareData => { const root = d3.hierarchy(flareData) .sum(d => d.value) .sort((a, b) => b.value - a.value); return d3.partition() .size([2 * Math.PI, root.height + 1]) (root); } color = d3.scaleOrdinal( d3.quantize(d3.interpolateRainbow, flareData.children.length + 1) ) format = d3.format(",d") width = 932 radius = width / 6 arc = d3.arc() .startAngle(d => d.x0) .endAngle(d => d.x1) .padAngle(d => Math.min((d.x1 - d.x0) / 2, 0.005)) .padRadius(radius * 1.5) .innerRadius(d => d.y0 * radius) .outerRadius(d => Math.max(d.y0 * radius, d.y1 * radius - 1)) ```
{ "lastmod": "2023-07-05T19:35:15.663Z", "loc": "https://quarto.org/docs/interactive/ojs/examples/sunburst.html", "source": "https://quarto.org/docs/interactive/ojs/examples/sunburst.html" }
As you build larger Quarto projects (like websites and books) that incorporate OJS, you’ll likely want to re-use code, data, and output across different pages. Modules JavaScript modules are directly supported in Quarto’s OJS blocks. For example, if we have the following source file square.js: export function square(x) { return x * x; } Then you can import and use the square() function as follows: import { square } from "./square.js" square(5) Data You may be using Python or R to pre-process data that is then provided to OJS via the ojs_define() function (this is described in more depth in the Data Sources article). If you want to share data prepared in this fashion you can import it directly from another .qmd. For example, here we import the co2data that we read and pre-processed with dplyr in data-sources.qmd: import { co2data } from "./data-sources.qmd"; Inputs.table(transpose(co2data)) Output You can import any reactive value from another .qmd file. Here, we’re reusing a chart directly from data-sources.qmd: import { yearlyChart } from "./data-sources.qmd"; yearlyChart
{ "lastmod": "2023-07-05T19:35:15.483Z", "loc": "https://quarto.org/docs/interactive/ojs/code-reuse.html", "source": "https://quarto.org/docs/interactive/ojs/code-reuse.html" }
OJS code cells {ojs} behave a bit differently than cells in traditional notebooks, and have many options available to control their display and layout. Cell Execution A critical difference between OJS cell execution and traditional notebooks is that in OJS cells do not need to be defined in any particular order. Because execution is fully reactive, the runtime will automatically execute cells in the correct order based on how they reference each other. This is more akin to a spreadsheet than a traditional notebook with linear cell execution. For example, in this cell we reference a variable that is not yet defined (it’s defined immediately below): ```{ojs} x + 5 ``` ```{ojs} x = 10 ``` This code works because the Observable runtime automatically determines the correct order of execution for the cells. Cell Output By default, OJS cells show their full source code and output within rendered documents. Depending on the type of document you are creating you might want to change this behavior either globally or for individual cells. Code Visibility The echo option controls whether cells display their source code. To prevent display of code for an entire document, set the echo: false option in YAML metadata: --- title: "My Document" execute: echo: false --- You can also specify this option on a per-cell basis. For example: ```{ojs} //| echo: false data = FileAttachment("palmer-penguins.csv").csv({ typed: true }) ``` Output Visibility OJS cell output is also displayed by default. You can change this at a global or (more likely) per-cell level using the output option. For example, here we disable output for a cell: ```{ojs} //| output: false data ``` Note that cells which only carry assignments do not print their output by default. For example, this assignment won’t print anything: ```{ojs} //| echo: fenced dummy1 = "aHiddenAssignment" ``` If you want to print even the results of assignments, you can specify the output: all option. For example: ```{ojs} //| echo: fenced //| output: all dummy2 = [{key: 1, value: [1, 2, [3, 4], dummy1]}] ``` If you click the inspector you’ll see it expand to reveal the data as JSON. Code Display We talked about showing and hiding source code above, but what about controlling exactly how it’s displayed? There are options available for customizing the appearance of code blocks (highlighting, background, border, etc.) as well as how horizontal overflow is handled. See the article on HTML Code Blocks for all of the details. One option we wanted to specifically highlight here is code folding, which enables you to collapse code but still provide an option for users to view it. This is especially handy for custom JavaScript visualizations as they often span dozens of lines of code. Add the code-fold: true option to a code cell to enable code folding (you can also enable this globally). For example, click the “Code” button to show the code block (note the code-fold: true option is specified) Code ```{ojs} //| code-fold: true pdata = FileAttachment("palmer-penguins.csv").csv({typed: true}) Plot.plot({ facet: { data: pdata, x: "sex", y: "species", marginRight: 80 }, marks: [ Plot.frame(), Plot.rectY(pdata, Plot.binX( {y: "count"}, {x: "body_mass_g", thresholds: 20, fill: "species"} ) ), Plot.tickX(pdata, Plot.groupZ( {x: "median"}, {x: "body_mass_g", z: d => d.sex + d.species, stroke: "#333", strokeWidth: 2 } ) ) ] }) ``` Cell Layout There are additional panel and layout options which you can add to OJS cells to customize how their output is presented. Here’s a version of some of the previous examples we’ve used presented with a sidebar and tabset: filtered = pdata.filter(function(penguin) { return bill_length_min < penguin.bill_length_mm && islands.includes(penguin.island); }) viewof bill_length_min = Inputs.range( [32, 50], {value: 35, step: 1, label: "Bill length (min):"} ) viewof islands = Inputs.checkbox( ["Torgersen", "Biscoe", "Dream"], { value: ["Torgersen", "Biscoe"], label: "Islands:" } ) PlotData Plot.rectY(filtered, Plot.binX( {y: "count"}, {x: "body_mass_g", fill: "species", thresholds: 20} )) .plot({ facet: { data: filtered, x: "sex", y: "species", marginRight: 80 }, marks: [ Plot.frame(), ] } ) Inputs.table(filtered) We created this layout by first adding the panel: sidebar option to the cell with our inputs: ```{ojs} //| panel: sidebar viewof bill_length_min = Inputs.range( [32, 50], {value: 35, step: 1, label: "Bill length (min):"} ) viewof islands = Inputs.checkbox( ["Torgersen", "Biscoe", "Dream"], { value: ["Torgersen", "Biscoe"], label: "Islands:" } ) ``` We then added a tabset (div of class .panel-tabset) with Plot and Data tabs (headings within the div define the tabs): ::: {.panel-tabset} ## Plot ```{ojs} Plot.rectY(filtered, Plot.binX( {y: "count"}, {x: "body_mass_g", fill: "species", thresholds: 20} )) .plot({ facet: { data: filtered, x: "sex", y: "species", marginRight: 80 }, marks: [ Plot.frame(), ] } ) ``` ## Data ```{ojs} Inputs.table(filtered) ``` ::: See the Layout example for the full source code. Learn more in the article on Layout for interactive documents. Cell Figures OJS cells can also be rendered as numbered, cross-referenceable figures. To do this, add the label and fig-cap options to the cell. For example: ```{ojs} //| echo: fenced //| label: fig-penguin-body-mass //| fig-cap: "Penguin body mass by sex and species" Plot.rectY(filtered, Plot.binX( {y: "count"}, {x: "body_mass_g", fill: "species", thresholds: 20} )) .plot({ facet: { data: filtered, x: "sex", y: "species", marginRight: 80 }, marks: [ Plot.frame(), ] } ) ``` Figure 1: Penguin body mass by sex and species See Figure 1 for further illustration. To reference the figure use its label in a markdown cross reference: See @fig-penguin-body-mass for further illustration.
{ "lastmod": "2023-07-05T19:35:15.667Z", "loc": "https://quarto.org/docs/interactive/ojs/ojs-cells.html", "source": "https://quarto.org/docs/interactive/ojs/ojs-cells.html" }
Overview Earlier we described how to use the ojs_define() function to make data from Python and R available in OJS cells. In this scenario, data pre-processing is done once during render time then all subsequent interactions are handled on the client. But what if you want to do data transformation dynamically in response to user inputs? This is also possible with ojs_define(), as it can be passed not just static values but also Shiny reactives (assuming it’s running inside a Shiny interactive document). Hello, Shiny Here is the K-Means Clustering example from the Shiny Gallery implemented with an OJS client and Shiny Server: You can see the document deployed at https://jjallaire.shinyapps.io/kmeans-shiny-ojs/. Source Code Let’s take a look at the source code. On the client we have familiar looking OJS inputs and a plot laid out using panel: sidebar and panel: fill: ```{ojs} //| panel: sidebar vars = ["Sepal.Length", "Sepal.Width", "Petal.Length", "Petal.Width"] viewof xcol = Inputs.select(vars, {label: "X Variable"}) viewof ycol = Inputs.select(vars, {label: "Y Variable", value: vars[1]}) viewof count = Inputs.range([1, 9], {label: "Cluster Count", step: 1, value: 3}) ``` ```{ojs} //| panel: fill Plot.plot({ color: { type: "ordinal", scheme: "category10" }, marks: [ Plot.dot(transpose(selectedData), { x: xcol, y: ycol, fill: (d, i) => clusters.cluster[i], }), Plot.dot(clusters.centers, { x: d => d[0], y: d => d[1], r: 10, stroke: "black", fill: (d, i) => i + 1 }), ] }) ``` Note that the plotting code references the variables selectedData and clusters. These will be provided by reactive expressions within the Shiny server code. Note also that we use the transpose() function to reshape the data into the row-oriented format that the Plot library expects. Here is the server code: ```{r} #| context: server selectedData <- reactive({ iris[, c(input$xcol, input$ycol)] }) clusters <- reactive({ kmeans(selectedData(), input$count) }) ojs_define(selectedData, clusters) ``` We designate this code as running on the server via the context: server option. Note that we reference several inputs that were defined by viewof expressions on the client (e.g. input$xcol). When these inputs change they will cause the appropriate server side reactives to re-execute. We create two reactive values (selectedData and clusters) and provide them to the client using ojs_define(). The plot will be automatically re-drawn on the client side when these values change. Examples Here are some examples that demonstrate various ways to use OJS with Shiny: Example Source Description K-Means Code Simple example of binding OJS inputs to Shiny inputs and shiny reactives to OJS plots. Binning Code Demonstrates fast binning of a medium sized dataset (32mb) on the server. Data Binding Code Demonstrates importing a notebook from https://observablehq.com and binding it’s data field to a Shiny reactive. Bindings OJS to Shiny In the example above we took advantage of the fact that by default OJS viewof expressions are automatically propagated to Shiny inputs (e.g input$xcol). This provides a reasonable separation of concerns, and prevents excess network traffic in the case that you have large OJS variables. However, if you want to use other OJS variables as Shiny inputs this is also possible using the ojs-export option. The default behavior maps to the following configuration: --- server: type: shiny ojs-export: viewof --- You can also specify ojs-export: all to cause all OJS reactives to be bound to Shiny inputs: --- server: type: shiny ojs-export: all --- Alternatively, you can specify a list of OJS reactives by name (including using ~ to filter out reactives), and optionally combine this with the viewof and/or all options. For example: --- server: type: shiny ojs-export: [all, ~large_dataset] --- Shiny to OJS Less common but occasionally useful is the ability to bind Shiny inputs into OJS. By default no such bindings occur, however you can use the ojs-import option to opt-in for specific Shiny inputs. For example: --- server: type: shiny ojs-import: [minimum, maximum] ---
{ "lastmod": "2023-07-05T19:35:15.667Z", "loc": "https://quarto.org/docs/interactive/ojs/shiny.html", "source": "https://quarto.org/docs/interactive/ojs/shiny.html" }
Overview Shiny interactive documents can contain both code that executes at render time as well as code that executes on the server in response to user actions and changes in input values. A solid understanding of these execution contexts is important both to have the right mental model during development as well as to optimize the performance of your document. Render & Server Contexts To break this down more clearly, let’s revisit the “Hello, Shiny” document we started with in the introduction to interactive documents: --- title: "Old Faithful" format: html server: shiny --- ```{r} sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) plotOutput("distPlot") ``` ```{r} #| context: server output$distPlot <- renderPlot({ x <- faithful[, 2] # Old Faithful Geyser data bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = 'darkgray', border = 'white') }) ``` Here is how execution breaks down for this document: The first code chunk that contains the calls to sliderInput() and plotOutput() will execute when you render the document (e.g. quarto render old-faithful.qmd). The second code chunk with the context: server option will not execute at render time, but rather will execute only when the document is served. It’s critical to understand that the two chunks are run in completely separate R sessions. That means that you cannot access variables created in the first chunk within the second, and vice-versa. The is analogous to the ui.R and server.R scripts that compose most normal Shiny applications. Of course, it’s quite useful to be able to re-use code between contexts, and we’ll cover some ways to do this in the Sharing Code section below. In order to make the code of interactive documents straightforward to understand and work with, we strongly recommend that your server contexts (there can be more than one) be located at the bottom of the document. This makes the separate execution environments more clear in the flow of the document source code. server.R There is one other option if you prefer to have a stronger separation. You can restrict your .qmd file to only code that will execute at render time, and then split out the server code into a separate server.R file. Re-writing our example in this fashion would look like this: old-faithful.qmd --- title: "Old Faithful" format: html server: shiny --- ```{r} sliderInput("bins", "Number of bins:", min = 1, max = 50, value = 30) plotOutput("distPlot") ``` server.R function(input, output, session) { output$distPlot <- renderPlot({ x <- faithful[, 2] # Old Faithful Geyser data bins <- seq(min(x), max(x), length.out = input$bins + 1) hist(x, breaks = bins, col = 'darkgray', border = 'white') }) } This is perhaps a bit less convenient but does align better with the traditional ui.R / server.R separation that exists in traditional Shiny applications. Sharing Code Sharing code between rendering contexts works a bit differently depending on if your code is in a single .qmd file or if it uses server.R. We’ll cover both scenarios below. Single File context: setup To have code execute in both rendering and serving contexts, create a code chunk with context: setup. For example: ```{r} #| context: setup #| include: false # load libraries library(dplyr) # load data dataset <- import_data("data.csv") dataset <- sample_n(dataset, 1000) ``` This code will execute at both render time as well as when the server is created for each new user session. Note that we also specify include: false to make sure that code, warnings, and output from the chunk are not included in the rendered document. context: data The loading and manipulation of data often dominates the startup time of Shiny applications. Since interactive documents are executed in two phases (the initial render and then the serving of the document to users) we can perform the expensive data manipulations during rendering and then simply load the data when starting up the application. You can define prerendered data by adding the context: data option to an R code chunk. The chunk will be executed during render and any R objects it creates will be saved to an .RData file, which will then be loaded during Shiny server startup. For example, we could take the the setup chunk illustrated above and factor out the data loading into its own chunk: ```{r} #| context: data #| include: false dataset <- import_data("data.csv") dataset <- sample_n(dataset, 1000) ``` Note that R objects created within a context: data chunk are available to both the UI rendering and server contexts. Knitr cache You can further improve the performance of data rendering by adding the cache: true option to the data chunk. This will cause the code chunk to be re-executed only when required. For example: ```{r} #| context: data #| include: false #| cache: true #| cache.extra: !expr file.info("data.csv")$mtime dataset <- import_data("data.csv") dataset <- sample_n(dataset, 1000) ``` In this example the cache will be invalidated if either the R code in the chunk changes or the modification time of the “data.csv” file changes (this is accomplished using the cache.extra option). You can also invalidate an existing cache by removing the _cache directory alongside with your interactive document. context: server-start There is one additional execution context that enables you to share code and data across multiple user sessions. Chunks with context: server-start executee once when the Shiny document is first run and are not re-executed for each new user of the document. Using context: server-start is appropriate for several scenarios including: Establishing shared connections to remote servers (e.g. databases, Spark contexts, etc.). Creating reactive values intended to be shared across sessions (e.g. with reactivePoll or reactiveFileReader). For example: ```{r} #| context: server-start library(DBI) db <- dbConnect(...) ``` Multiple Files If your interactive document uses a .qmd file to define the user-interface and a server.R file for the server, you can put shared code in a file named global.R. Functions and variables defined within global.R will be available both during render as well as during execution of the server. In this scenario your interactive document consists of 3 source files: File Description doc.qmd Markdown content as well as Shiny inputs and outputs (e.g. sliderInput(), plotOutput(), etc.) server.R Main server function with reactive expressions, assignments to outputs, etc. global.R Code shared between doc.qmd and server.R.
{ "lastmod": "2023-07-05T19:35:15.667Z", "loc": "https://quarto.org/docs/interactive/shiny/execution.html", "source": "https://quarto.org/docs/interactive/shiny/execution.html" }
Overview There are a number of ways to run Shiny interactive documents: Use Run Document within the RStudio IDE. Use the quarto serve command line interface. Deploy them to a server for use by a wider audience. We’ll cover all of these scenario in depth here. Note that in order to run interactive Shiny documents you will to install the very latest version of the rmarkdown package (v2.10) which you can install as follows: install.packages("rmarkdown") RStudio IDE While you are developing an interactive document it will likely be most convenient to run within RStudio. Note that you need RStudio v2022.07 or a later version in order to run Quarto interactive documents. You can download the latest release (v2023.03) here https://posit.co/download/rstudio-desktop/. Click the Run Document button while editing a Shiny interactive document to render and view the document within the IDE: When you make changes, just click Run Document again to see them reflected in the document preview. Two options you may want to consider enabling are Run on Save and Preview in Viewer Pane (by default previews occur in an external window). You can access these options on the editor toolbar: Command Line You can also run Shiny interactive documents from the command line via quarto serve. For example: Terminal quarto serve document.qmd There are a number of options to the serve command to control the port and host of the document server as well as whether a browser is automatically opened for the running document. You can learn more about these options with quarto serve help. If you are within an R session you can also use the quarto R package to run a document: library(quarto) quarto_serve("document.qmd") Deployment ShinyApps You can publish Shiny interactive documents to the ShinyApps hosted service. To do this you should ensure that you have: An account on ShinyApps (use the signup form to create an account). The very latest versions of the rsconnect and quarto R packages. You can install them as follows: install.packages("rsconnect") install.packages("quarto") You can then deploy your interactive document using the quarto_publish_app() function of the quarto package. You can do this as follows (working from the directory that contains your document): library(quarto) quarto_publish_app(server = "shinyapps.io") If you are using RStudio you can also use the Publish button available when working with an interactive document: Note that you should always Run Document locally prior to publishing your document (as this will create the .html file that is served on ShinyApps. Posit Connect Posit Connect is a server product from Posit for secure sharing of applications, reports, and plots. You can publish Shiny interactive documents to Posit Connect in much the same way as described above for ShinyApps. First, make sure you very latest development versions of the rsconnect and quarto R packages. You can install them as follows: install.packages("rsconnect") install.packages("quarto") Next, deploy your interactive document using the quarto_publish_app() function of the quarto package, providing the domain name or IP address of your Posit Connect installation via the server parameter. You can do this as follows (working from the directory that contains your document): library(quarto) quarto_publish_app(server = "rsc.example.com") If you are using RStudio you can also use the Publish button as described above in the ShinyApps documentation: As with ShinyApps, you should always Run Document locally prior to publishing your document (as this will create the .html file that is served by Posit Connect).
{ "lastmod": "2023-07-05T19:35:15.675Z", "loc": "https://quarto.org/docs/interactive/shiny/running.html", "source": "https://quarto.org/docs/interactive/shiny/running.html" }
Overview Jupyter Widgets enable you to use JavaScript visualization libraries like Leaflet, Plotly, and threejs directly from Python. If you are using the Jupyter engine with Quarto this is a great way to incorporate interactivity without learning JavaScript. Leaflet Example Including Jupyter Widgets within a Quarto document is as easy as including a plot. For example, here is how we embed a Leaflet map: from ipyleaflet import Map, Marker, basemaps, basemap_to_tiles m = Map( basemap=basemap_to_tiles( basemaps.NASAGIBS.ModisTerraTrueColorCR, "2017-04-08" ), center=(52.204793, 360.121558), zoom=4 ) m.add_layer(Marker(location=(52.204793, 360.121558))) m To learn about available Jupyter Widgets visit https://jupyter.org/widgets. Plotly Plotly is an interactive graphics library that can also be used with the Jupyter engine. Here’s an example of using Plotly: import plotly.express as px import plotly.io as pio df = px.data.iris() fig = px.scatter(df, x="sepal_width", y="sepal_length", color="species", marginal_y="violin", marginal_x="box", trendline="ols", template="simple_white") fig.show() Note If you are using Plotly within the VS Code Notebook Editor you will need to add a line of code to ensure that your plots can be seen both within VS Code and when rendered to HTML by Quarto. You can do this by configuring the Plotly default renderer as follows: ```{python} import plotly.io as pio pio.renderers.default = "plotly_mimetype+notebook_connected" ``` This workaround is required because when running within VS Code, Plotly chooses a default rendering that can’t be easily exported to HTML (for more background, see this GitHub Issue and related discussion). Note that this workaround is only required for the VS Code Notebook Editor (it is not required if you are using Jupyter Lab or if you are editing a plain-text .qmd file).
{ "lastmod": "2023-07-05T19:35:15.675Z", "loc": "https://quarto.org/docs/interactive/widgets/jupyter.html", "source": "https://quarto.org/docs/interactive/widgets/jupyter.html" }
Slide Title Slide content Custom footer text Another Slide Title A different custom footer
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/per-slide-footer.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/per-slide-footer.html" }
Slide with speaker notes Slide content Speaker notes go here.
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/slide-with-speaker-notes.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/slide-with-speaker-notes.html" }
Presentation Slide 1 Eat spaghetti Drink wine
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/theme-dark.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/theme-dark.html" }
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/executable-code-figure-size.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/executable-code-figure-size.html" }
Habits John Doe Turn off alarm Get out of bed Get in bed Count sheep
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/creating-slides-3.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/creating-slides-3.html" }
import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.plot(theta, r) ax.set_rticks([0.5, 1, 1.5, 2]) ax.grid(True) plt.show()
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/line-highlighting-4.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/line-highlighting-4.html" }
import numpy as np import matplotlib.pyplot as plt r = np.arange(0, 2, 0.01) theta = 2 * np.pi * r fig, ax = plt.subplots(subplot_kw={'projection': 'polar'}) ax.plot(theta, r) ax.set_rticks([0.5, 1, 1.5, 2]) ax.grid(True) plt.show()
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/line-highlighting-3.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/line-highlighting-3.html" }
Slide Title This slide’s background image will be sized to 100px and repeated.
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/image-background.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/image-background.html" }
Slide, aquamarine Slide, #806040
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/background-color.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/background-color.html" }
Slide 1 Footer and logo are shared across all slides. Slide 2 Footer text
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/footer-and-logo.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/footer-and-logo.html" }
Slide with a pause content before the pause content after the pause
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/incremental-pause.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/incremental-pause.html" }
Non-scrollable Slide Bullet Point 1 Bullet Point 2 Bullet Point 3 Bullet Point 4 Bullet Point 5 Bullet Point 6 Bullet Point 7 Bullet Point 8 Bullet Point 9 Bullet Point 10 Bullet Point 11 Bullet Point 12 Bullet Point 13 Bullet Point 14 Bullet Point 15 Bullet Point 16 Scrollable Slide Bullet Point 1 Bullet Point 2 Bullet Point 3 Bullet Point 4 Bullet Point 5 Bullet Point 6 Bullet Point 7 Bullet Point 8 Bullet Point 9 Bullet Point 10 Bullet Point 11 Bullet Point 12 Bullet Point 13 Bullet Point 14 Bullet Point 15 Bullet Point 16
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/examples/scrollable.html", "source": "https://quarto.org/docs/presentations/revealjs/examples/scrollable.html" }
Overview This article covers the mechanics of presenting slides with Reveal. Basic navigation is done using the following keyboard shortcuts: Action Keys Next slide → SPACE N Previous slide ← P Navigate without fragments Alt → Alt ← Jump to first/last slide Shift → Shift ← You will often want to enter fullscreen mode when presenting. You can do this by pressing the F key. In addition to basic keyboard navigation, Reveal supports several more advanced capabilities, including: Navigation menu and overview mode Speaker view (w/ speaker notes,timer, and preview of upcoming slides) Printing to PDF and publishing as self contained HTML Drawing on top of slides & chalkboard/whiteboard mode Multiplex, which allows your audience to follow the slides of the presentation you are controlling on their own phone, tablet or laptop. These capabilities are described below. Navigation Menu Quarto includes a built in version of the reveal.js-menu plugin. You can access the navigation menu using the button located in the bottom left corner of the presentation. Clicking the button opens a slide navigation menu that enables you to easily jump to any slide: You can also open the navigation menu by pressing the M key. The navigation menu also includes a Tools pane that provides access to the various other navigation tools including Fullscreen, Speaker View, Overview Mode, and Print to PDF. Use the following options to customize the appearance and behavior of the menu: Option Description side Side of the presentation where the menu will be shown. left or right (defaults to left). width Width of the menu (normal, wide, third, half, full, or any valid css length value). Defaults to normal numbers Add slide numbers to menu items. For example: format: revealjs: menu: side: right width: wide You can hide the navigation menu by specifying the menu: false option: format: revealjs: menu: false Note that you can still open the menu using the M key even if the button is hidden. Overview Mode Overview mode provides an alternate view that shows you a thumbnail for each slide: You can enable Overview Mode by pressing the O key. Slide Zoom Hold down the Alt key (or Ctrl in Linux) and click on any element to zoom towards it. Try zooming in on one of these images: Alt or Ctrl click again to zoom back out. Speaker View The speaker view shows the current slide along with the upcoming slide, a timer, and any speaker notes associated with the current slide: You can enable Speaker View by pressing the S key. You can add speaker notes to a slide using a div with class .notes. For example: ## Slide with speaker notes Slide content ::: {.notes} Speaker notes go here. ::: Slide Numbers You can add slide numbers to your presentation using the slide-number option. You can also control in which contexts slide numbers appear using the show-slide-number option. For example, here we configure slides numbers for printed output only: --- title: "Presentation" format: revealjs: slide-number: true show-slide-number: print --- In addition to a simple true or false value, the slide-number option can also specify a format. Available formats include: Value Description c/t Slide number / total slides (default) c Slide number only h/v Horizontal / Vertical slide number h.v Horizontal . Vertical slide number See Vertical Slides for additional information on vertical slides. The show-slide-number option supports the following values: Value Description all Show slide numbers in all contexts (default) print Only show slide numbers when printing to PDF speaker Only show slide numbers in the speaker view Print to PDF Reveal presentations can be exported to PDF via a special print stylesheet. Note Note: This feature has only been confirmed to work in Google Chrome and Chromium. To Print to PDF, do the following: Toggle into Print View using the E key (or using the Navigation Menu) Open the in-browser print dialog (CTRL/CMD+P). Change the Destination setting to Save as PDF. Change the Layout to Landscape. Change the Margins to None. Enable the Background graphics option. Click Save 🎉 Here’s what the Chrome print dialog would look like with these settings enabled: Print Options There are a number of options that affected printed output that you may want to configure prior to printing: Option Description show-notes Include speaker notes (true, false, or separate-page) slide-number Include slide numbers (true or false) pdf-max-pages-per-slide Slides that are too tall to fit within a single page will expand onto multiple pages. You can limit how many pages a slide may expand to using the pdf-max-pages-per-slide option. pdf-separate-fragments Slides with multiple fragments are printed on a single page by default. To create a page for each fragment set this option to true. For example, the following specifies that we want to print speaker notes on their own page and include slide numbers: --- title: "Presentation" format: revealjs: show-notes: separate-page slide-number: true --- Preview Links Reveal makes it easy to incorporate navigation to external websites into the flow of presentations using the preview-links option. When you click on a hyperlink with preview-links: true, the link will be navigated to in an iframe that overlays the slide. For example, here we’ve clicked on a Matplotlib link and the website opens on top of the slide (you’d click the close button at top right to hide it): Available values for preview-link include: Option Description auto Preview links when presenting in full-screen mode (otherwise navigate to them normally) true Always preview links false Never preview links (the default) For example, here we set preview-links to auto: --- title: "Presentation" format: revealjs: preview-links: auto --- You can also set this option on a per-link basis. These two links respectively enable and disable preview: [Preview](https://example.com){preview-link="true"} [NoPreview](https://example.com){preview-link="false"} Slide Tone Slide tone plays a subtle sound when you change slides. It was requested by a blind user and enables presenters to hear an auditory signal of their progress through the slides. Enable slide tone with: format: revealjs: slide-tone: true The tones increase in pitch for each slide from a low C to a high C note. The tone pitch stays the same for incremental slides. The implementation of slide tone was adapted from the slide tone plugin in xaringanExtra. Auto-Slide Presentations can be configured to step through slides automatically, without any user input. To enable this you will need to specify an interval for slide changes using the auto-slide option (the interval is provided in milliseconds). The loop option can additionally be specified to continue presenting in a loop once all the slides have been shown. For example, here we specify that we want to advance every 5 seconds and continue in a loop: --- title: "Presentation" format: revealjs: auto-slide: 5000 loop: true --- A play/pause control element will automatically appear for auto-sliding decks. Sliding is automatically paused if the user starts interacting with the deck. It’s also possible to pause or resume sliding by pressing A on the keyboard. You can disable the auto-slide controls and prevent sliding from being paused by specifying auto-slide-stoppable: false. Slide Timing It’s also possible to override the slide duration for individual slides and fragments by using the autoslide attribute (this attribute also works on Fragments). For example, here we set the auto-slide value to 2 seconds: ## Slide Title {autoslide=2000} Publishing There are two main ways to publish Reveal presentations: As a PDF file—see Print to PDF above for details on how to do this. As an HTML file. For HTML, it’s often most convenient to distribute the presentation as a single self contained file. To do this, specify the embed-resources option: --- title: "Presentation" format: revealjs: embed-resources: true --- All of the dependent images, CSS styles, and other assets will be contained within the HTML file created by Quarto. Note that specifying embed-resources can slow down rendering by a couple of seconds, so you may want to enable embed-resources only when you are ready to publish. Also note that Reveal plugin Chalkboard is not compatible with embed-resources — when Chalkboard plugin is enabled, specifying embed-resources: true will result an error. See the documentation on Publishing HTML for details on additional ways to publish Reveal presentations including GitHub Pages and Posit Connect. Navigation Options There are several navigational cues provided as part of Reveal presentations and corresponding options that control them: Option Description controls Show arrow controls for navigating through slides (defaults to auto, which will show controls when vertical slides are present or when the deck is embedded in an iframe). progress Show a progress bar at the bottom (defaults to true). history Push slide changes to the browser history. Defaults to true, which means that the browser Forward/Back buttons can be used for slide navigation. hash-type Type of URL hash to use for slides. Defaults to title which is derived from the slide title. You can also specify number. For example, the following configuration hides the progress bar and specifies that we want to use browser history: --- title: "Presentation" format: revealjs: progress: false history: true --- Chalkboard Quarto includes a built-in version of the reveal.js-chalkboard plugin. Specify the chalkboard: true option to enable the plugin, which enables you to draw on a notes canvas on top of your slides and/or open up an empty chalkboard within your presentation: --- title: "Presentation" format: revealjs: chalkboard: true --- Note that Reveal plugin Chalkboard is not compatible with embed-resources output — when Chalkboard plugin is enabled, specifying embed-resources: true will result an error. Here are what the notes canvas and chalkboard look like when activated: To toggle the notes canvas on and off use the button or the C key. To toggle the chalkboard on and off use the button or the B key. Here are all of the keyboard shortcuts associated with the notes canvas and chalkboard: Action Key Toggle notes canvas C Toggle chalkboard B Reset all drawings BACKSPACE Clear drawings on slide DEL Cycle colors forward X Cycle colors backward Y Download drawings D The following mouse and touch gestures can be used for interacting with drawings: Click on the buttons at the bottom left to toggle the notes canvas or chalkboard Click on the color picker at the left to change the color (the color picker is only visible if the notes canvas or chalkboard is active) Click on the up/down arrows on the right to switch among multiple chalkboard (the up/down arrows are only available for the chalkboard) Click the left mouse button and drag to write on notes canvas or chalkboard Click the right mouse button and drag to wipe away previous drawings Touch and move to write on notes canvas or chalkboard Touch and hold for half a second, then move to wipe away previous drawings Restoring Drawings The D key downloads any active drawings into a JSON file. You can then restore these drawings when showing your presentation using the src option. For example: --- title: "Presentation" format: revealjs: chalkboard: src: drawings.json --- Chalkboard Options The following options are available to customize the behavior and appearance of the chalkboard: Option Description theme Can be set to either chalkboard (default) or whiteboard. boardmarker-width The drawing width of the boardmarker; larger values draw thicker line. Defaults to 3. chalk-width The drawing width of the chalk; larger values draw thicker lines. Defaults to 7. chalk-effect A float in the range [0.0, 1.0], the intensity of the chalk effect on the chalk board. Full effect (default) 1.0, no effect 0.0. src Optional file name for pre-recorded drawings (download drawings using the D key). read-only Configuration option to prevent changes to existing drawings. If set to true no changes can be made, if set to false false changes can be made, buttons Add chalkboard buttons at the bottom of the slide (defaults to true) transition Gives the duration (in milliseconds) of the transition for a slide change, so that the notes canvas is drawn after the transition is completed. For example, the following configuration specifies that we want to use the whiteboard theme with a (thicker) boardmarker width, and that we want to hide the chalkboard buttons at the bottom of each slide: --- title: "Presentation" format: revealjs: chalkboard: theme: whiteboard boardmarker-width: 5 buttons: false --- If you disable the chalkboard buttons globally you can selectively re-enable them for indvidual slides with the chalkboard-buttons attribute. For example: ## Slide Title {chalkboard-buttons="true"} You can also use chalkboard-buttons="false" to turn off the buttons for individual slides. Multiplex Quarto includes a built-in version of the Reveal Multiplex plugin. The multiplex plugin allows your audience to follow the slides of the presentation you are controlling on their own phone, tablet or laptop. When you change slides in your master presentations everyone will follow and see the same content on their own device. Creating a Reveal presentation that supports multiplex is straightforward. Just specify the multiplex: true option as follows: --- title: "Presentation" format: revealjs: multiplex: true --- Rendering the presentation will result in two HTML files being created by Quarto: File Description presentation.html This is the file you should publish online and that your audience should view. presentation-speaker.html This is the file that you should present from . This file can remain on your computer and does not need to be published elsewhere. The two versions of the presentation will be synchronized such that when the speaker version switches slides the viewers also all switch to the same slide. Multiplex Server Behind the scenes there is a multiplex server that is synchronizing slide events between the viewer and speaker versions of the presentation. Note that the this server does not actually see any of the slide content, it is only used to synchronize events. By default, a server created and hosted by the Revealjs team is used for this: https://reveal-multiplex.glitch.me/. This server is used by default when you specify multiplex: true. Running your own server If you want to run your own version of this server its source code is here: https://github.com/reveal/multiplex/blob/master/index.js. You can then configure multiplex to use an alternate server as follows: --- title: "Presentation" format: revealjs: multiplex: url: 'https://myserver.example.com/ --- Note that Quarto calls the multiplex server behind the scenes to provision a id and secret for your presentation. If you want to provision your own id and secret you can do so at https://reveal-multiplex.glitch.me/ (or using your custom hosted server URL) and provide them explicitly in YAML: --- title: "Presentation" format: revealjs: multiplex: id: '1ea875674b17ca76' secret: '13652805320794272084' --- Note that the secret value will be included in only the speaker version of the presentation. Learning More See these articles lo learn more about using Reveal: Reveal Basics covers the basic mechanics of creating presentations. Advanced Reveal delves into transitions, animations, advanced layout and positioning, and other options available for customizing presentations. Reveal Themes talks about using and customizing existing themes as well as creating brand new themes.
{ "lastmod": "2023-07-05T19:35:15.755Z", "loc": "https://quarto.org/docs/presentations/revealjs/presenting.html", "source": "https://quarto.org/docs/presentations/revealjs/presenting.html" }
Stack Click the arrow to advance to the next image in the stack.
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/demo/mini/stack.html", "source": "https://quarto.org/docs/presentations/revealjs/demo/mini/stack.html" }
# Fill in the spot we created for a plot output$phonePlot <- renderPlot({ # Render a barplot }) # Fill in the spot we created for a plot output$phonePlot <- renderPlot({ # Render a barplot barplot(WorldPhones[,input$region]*1000, main=input$region, ylab="Number of Telephones", xlab="Year") })
{ "lastmod": "2023-07-05T19:35:15.739Z", "loc": "https://quarto.org/docs/presentations/revealjs/demo/mini/auto-animate-code.html", "source": "https://quarto.org/docs/presentations/revealjs/demo/mini/auto-animate-code.html" }
Advance the slide to see three different fragment states: Fade in > Turn red > Semi fade out
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/demo/mini/fragments-nested.html", "source": "https://quarto.org/docs/presentations/revealjs/demo/mini/fragments-nested.html" }
Absolute
{ "lastmod": "2023-07-05T19:35:15.739Z", "loc": "https://quarto.org/docs/presentations/revealjs/demo/mini/absolute.html", "source": "https://quarto.org/docs/presentations/revealjs/demo/mini/absolute.html" }
Fragments Click the arrow to advance through the fragments: Fade in Fade out Highlight red Fade in, then out Slide up while fading in
{ "lastmod": "2023-07-05T19:35:15.743Z", "loc": "https://quarto.org/docs/presentations/revealjs/demo/mini/fragments.html", "source": "https://quarto.org/docs/presentations/revealjs/demo/mini/fragments.html" }
Using Themes There are 11 built-in themes provided for Reveal presentations (you can also create your own themes). The default and dark themes use fairly classic typography and color schemes and are a good place to start. The default theme is used automatically — use the theme option to switch to an alternate theme. For example --- title: "Presentation" format: revealjs: theme: dark --- Here is the full list of available themes: beige blood dark default league moon night serif simple sky solarized Customizing Themes You can customize the built in themes by adding your own Sass theme file to the theme declaration. For example: --- title: "Presentation" format: revealjs: theme: [default, custom.scss] --- Here’s what the contents of custom.scss might look like: /*-- scss:defaults --*/ $body-bg: #191919; $body-color: #fff; $link-color: #42affa; /*-- scss:rules --*/ .reveal .slide blockquote { border-left: 3px solid $text-muted; padding-left: 0.5em; } Theme files use Sass (a variant of CSS that supports variables and other extended features) and are divided into sections. /*-- scss:defaults --*/ is used to define variables that affect fonts, colors, borders, etc. (note that variables start with a $) /*-- scss:rules --*/ is used to create CSS rules. Note that CSS rules that target Reveal content generally need to use the .reveal .slide prefix to successfully override the theme’s default styles. See the Sass Variables documentation for a list of what’s available to customize. Creating Themes Creating a new theme is just a matter of re-defining one or more of the default Sass variables (you don’t need to re-specify values that you don’t want to override) and adding any additional CSS rules you need to. See the Sass Variables documentation for a list of what can be customized within a theme. For example, here is the source code for the built in serif theme: /*-- scss:defaults --*/ // fonts $font-family-sans-serif: "Palatino Linotype", "Book Antiqua", Palatino, FreeSerif, serif !default; // colors $body-bg: #f0f1eb !default; $body-color: #000 !default; $link-color: #51483d !default; $selection-bg: #26351c !default; // headings $presentation-heading-font: "Palatino Linotype", "Book Antiqua", Palatino, FreeSerif, serif !default; $presentation-heading-color: #383d3d !default; /*-- scss:rules --*/ .reveal a { line-height: 1.3em; } In this theme file you’ll notice that the !default suffix is placed after variable definitions. This is to make sure that anyone using this theme can override the variable value (without that the value is defined as not overrideable). You can use a custom theme by just specifying it as the theme option (all theme files implicitly inherit from the default theme). For example: --- title: "Presentation" format: revealjs: theme: mytheme.scss --- Here is the source code for all of the built-in themes for inspiration and examples: https://github.com/quarto-dev/quarto-cli/tree/main/src/resources/formats/revealjs/themes Sass Variables Here’s a list of all Sass variables (and their default values) used by Reveal themes. Note that some variables are defined using other variables, and several of the color variables use the lighten() Sass function to create a lighter variant of another color. Variable Default $font-family-sans-serif “Source Sans Pro”, Helvetica, sans-serif $font-family-monospace monospace $presentation-font-size-root 40px $presentation-font-smaller 0.7 $presentation-line-height 1.3 $body-bg #fff $body-color #222 $text-muted lighten($body-color, 50%) $link-color #2a76dd $link-color-hover lighten($link-color, 15%) $selection-bg lighten($link-color, 25%) $selection-color $body-bg $border-color lighten($body-color, 30%) $border-width 1px $border-radius 3px $presentation-heading-font $font-family-sans-serif $presentation-heading-color $body-color $presentation-heading-line-height 1.2 $presentation-heading-letter-spacing normal $presentation-heading-text-transform none $presentation-heading-text-shadow none $presentation-h1-text-shadow none $presentation-heading-font-weight 600 $presentation-h1-font-size 2.5em $presentation-h2-font-size 1.6em $presentation-h3-font-size 1.3em $presentation-h4-font-size 1em $presentation-block-margin 12px $presentation-slide-text-align left $presentation-title-slide-text-align center $code-block-bg $body-bg $code-block-border-color lighten($body-color, 60%) $code-block-font-size 0.55em $code-color var(–quarto-hl-fu-color) $code-bg transparent $tabset-border-color $code-block-border-color $light-bg-text-color #222 $light-bg-link-color #2a76dd $light-bg-code-color #4758ab $dark-bg-text-color #fff $dark-bg-link-color #42affa $dark-bg-code-color #ffa07a You’ll notice that some of the Sass variables use a presentation- prefix and some do not. The presentation- prefixed variables are specific to presentations, whereas the other variables are the same as ones used for standard Quarto HTML Themes. Since all Quarto themes use the same Sass format, you can use a single theme file for both HTML / website documents and presentations. Learning More See these articles lo learn more about using Reveal: Reveal Basics covers the basic mechanics of creating presentations. Presenting Slides describes slide navigation, printing to PDF, drawing on slides using a chalkboard, and creating multiplex presentations. Advanced Reveal delves into transitions, animations, advanced layout and positioning, and other options available for customizing presentations.
{ "lastmod": "2023-07-05T19:35:15.755Z", "loc": "https://quarto.org/docs/presentations/revealjs/themes.html", "source": "https://quarto.org/docs/presentations/revealjs/themes.html" }
Overview Quarto supports a variety of formats for creating presentations, including: revealjs — reveal.js (HTML) pptx — PowerPoint (MS Office) beamer — Beamer (LaTeX/PDF) There are pros and cons to each of these formats. The most capable format by far is revealjs so is highly recommended unless you have specific requirements for Office or LaTeX output. Note that revealjs presentations can be presented as HTML slides or can be printed to PDF for easier distribution. Below we’ll describe the basic syntax for presentations that applies to all formats. See the format specific articles for additional details on their native capabilities. Creating Slides In markdown, slides are delineated using headings. For example, here is a simple slide show with two slides (each defined with a level 2 heading (##): --- title: "Habits" author: "John Doe" format: revealjs --- ## Getting up - Turn off alarm - Get out of bed ## Going to sleep - Get in bed - Count sheep You can also divide slide shows into sections with title slides using a level 1 header (#). For example: --- title: "Habits" author: "John Doe" format: revealjs --- # In the morning ## Getting up - Turn off alarm - Get out of bed ## Breakfast - Eat eggs - Drink coffee # In the evening ## Dinner - Eat spaghetti - Drink wine ## Going to sleep - Get in bed - Count sheep Finally, you can also delineate slides using horizontal rules (for example, if you have a slide without a title): --- title: "Habits" author: "John Doe" format: revealjs --- - Turn off alarm - Get out of bed --- - Get in bed - Count sheep The examples above all use level 2 headings for slides and level 1 headings for sections/title slides. You can customize this using the slide-level option (See the Pandoc documentation on structuring the slide show for additional details. Incremental Lists By default number and bullet lists within slides are displayed all at once. You can override this globally using the incremental option. For example: title: "My Presentation" format: revealjs: incremental: true You can also explicitly make any list incremental or non-incremental by surrounding it in a div with an explicit class that determines the mode. To make a list incremental do this: ::: {.incremental} - Eat spaghetti - Drink wine ::: To make a list non-incremental do this: ::: {.nonincremental} - Eat spaghetti - Drink wine ::: Multiple Columns To put material in side by side columns, you can use a native div container with class .columns, containing two or more div containers with class .column and a width attribute: :::: {.columns} ::: {.column width="40%"} contents... ::: ::: {.column width="60%"} contents... ::: :::: Learning More See these format specific articles for additional details on the additional capabilities of each format: revealjs — reveal.js (HTML) pptx — PowerPoint (MS Office) beamer — Beamer (LaTeX/PDF)
{ "lastmod": "2023-07-05T19:35:15.703Z", "loc": "https://quarto.org/docs/presentations/index.html", "source": "https://quarto.org/docs/presentations/index.html" }
Overview Many more complex projects have additional processing that needs to take place periodically (e.g. data import and preparation) or even before/after each render. Project scripts are a way to incorporate this processing into your workflow. Periodic Scripts You can use the quarto run command to run a TypeScript, R, Python, or Lua script. For example: Terminal quarto run import.py Available script interpreters for quarto run include: Language Interpreter TypeScript Deno (embedded in Quarto) Python Python from PATH (or launcher on Windows) R Rscript from PATH Lua Lua 5.3 (embedded in Pandoc) Using TypeScript or Lua enables you to create scripts with no additional installation requirements. On the other hand, if your project is already using Python or R then scripts in those languages might be more convenient. If you are using TypeScript, please be sure to consult the section below on Deno Scripts for additonal details on the Deno standard library and importing external scripts. Pre and Post Render You can arrange for one or more scripts to execute before and/or after each render using the pre-render and post-render project options. For example: project: type: website pre-render: prepare.py post-render: - compress.ts - fix-links.py Note that pre-render and post-render also support arbitrary shell commands. So you could for example use make to do data preparation this way: project: type: website pre-render: make prepare Pre and post render scripts are run with the main project directory. The following environment variables are passed to pre and post-render scripts (note that all paths are relative to the main project directory): Variable Description QUARTO_PROJECT_RENDER_ALL Set to “1” if this is a render of all files in the project (as opposed to an incremental render or a render for preview). This unset if Quarto is not rendering all files. QUARTO_PROJECT_OUTPUT_DIR Output directory QUARTO_PROJECT_INPUT_FILES Newline separated list of all input files being rendered (passed only to pre-render) QUARTO_PROJECT_OUTPUT_FILES Newline separated list of all output files rendered (passed only to post-render). If you have a pre-render step that is expensive, you may want only run it when the entire project is being rendered. Here’s how you would do this in the various supported script languages: TypeScriptPythonRLua if (!Deno.env.get("QUARTO_PROJECT_RENDER_ALL")) { Deno.exit(); } import os if not os.getenv("QUARTO_PROJECT_RENDER_ALL"): exit() if (!nzchar(Sys.getenv("QUARTO_PROJECT_RENDER_ALL"))) { quit() } if not os.getenv("QUARTO_PROJECT_RENDER_ALL") then os.exit(); end Deno Scripts If you want to create project scripts with TypeScript, quarto run enables you to use the Deno TypeScript interpreter bundled with Quarto. This interpreter also includes the complete Deno standard library. For example, to use the Deno YAML parser you would do this: import { parse } from "https://deno.land/std/encoding/yaml.ts"; const config = parse(Deno.readTextFileSync("_quarto.yml")); The reference to the Deno encoding library above uses a URL: it’s important to note that in spite of this the library is not downloaded from a remote server (in fact, importing from remote servers is disabled entirely in the Quarto Deno interpreter). Rather, the Deno standard library is shipped with Quarto, making standard library URLs available in an offline cache. You may come across example code that embeds versions directly in Deno library imports. For example: import { format } from "https://deno.land/[email protected]/datetime/mod.ts"; These version-bound imports will not work with Quarto (as its local standard library cache is populated with unversioned URLs). The correct form of the above import is thus: import { format } from "https://deno.land/std/datetime/mod.ts"; You may also see examples of Deno code that imports 3rd party libraries directly from URLs. As noted above, this functionality is not available in Quarto Deno scripts. Rather, you should download any external libraries you wish to use, include them with your project source code, and import them using relative file paths.
{ "lastmod": "2023-07-05T19:35:15.755Z", "loc": "https://quarto.org/docs/projects/scripts.html", "source": "https://quarto.org/docs/projects/scripts.html" }
Virtual environments provide a project-specific version of installed packages. This both helps you to faithfully reproduce your environment (e.g. if you are collaborating with a colleague or deploying to a server) as well as isolate the use of packages so that upgrading a package in one project doesn’t break other projects. There are several popular flavors of virtual environment, we will cover the following ones here: venv (built into Python 3) conda (built in to Anaconda/Miniconda) renv (package for managing R environments) Below we’ll provide some example workflows for using these tools with Quarto. In these examples we’ll assume that you are already within a project directory that contains Quarto documents (so the environment will be created as a sub-directory of the project). We’ll also cover using virtual environments with JupyterLab, RStudio, and VS Code. Using venv Here we’ll provide a brief run through of creating a venv for a Quarto project. See the full documentation on using virtual environments with Python for additional details. To create a new Python 3 virtual environment in the directory env: Platform Command Mac/Linux Terminal python3 -m venv env Windows Terminal py -m venv env To use the environment you need to activate it. This differs slightly depending on which platform / shell you are using: Shell Command Mac/Linux Terminal source env/bin/activate Windows (Command) Terminal env\Scripts\activate.bat Windows (PowerShell) Terminal env\Scripts\Activate.ps1 PowerShell Note Note that you may receive an error about running scripts being disabled when activating within PowerShell. If you get this error then execute the following command: Terminal Set-ExecutionPolicy -ExecutionPolicy Unrestricted -Scope CurrentUser Once you’ve activated the environment, you need to ensure that you have the packages required to render your documents. This will typically encompass jupyter / jupyterlab plus whatever other packages are used in your Python code. ip to install packages into your environment. For example: Platform Command Mac/Linux Terminal python3 -m pip install jupyter matplotlib pandas Windows Terminal py -m pip install jupyter matplotlib pandas Assuming you installed all of the required packages (likely more than just pandas and matplotlib) you should now be able to quarto render documents within the directory. To deactivate an environment use the deactivate command: Terminal deactivate Saving Environments To make your environment reproducible, you need to create a requirements.txt file that enumerates all of the packages in use. To do this use the pip freeze command: Platform Command Mac/Linux Terminal python3 -m pip freeze > requirements.txt Windows Terminal py -m pip freeze > requirements.txt You should generally check the requirements.txt file into version control. Restoring Environments To reproduce the environment on another machine you create an empty environment, activate it, and then pip install using requirements.txt: First, follow the instructions above for creating and activating a virtual environment for your platform/shell. Then, install packages from requirements.txt: Platform Command Mac/Linux Terminal python3 -m pip install -r requirements.txt Windows Terminal py -m pip install -r requirements.txt Using conda This section will cover the basics of creating and using conda environments with Quarto projects. See this article on managing project specific environments with Conda for additional details. To create a new environment in the directory env: Terminal conda create --prefix env python If this is the first time you’ve used conda in your shell, you may need to execute one of the following commands before using other conda tools: Shell Command Newer Mac (Zsh) Terminal conda init zsh Linux / Older Mac (Bash) Terminal conda init bash Windows (Command) Terminal conda init cmd.exe Windows (PowerShell) Terminal conda init powershell You will likely need to exit and restart your terminal for conda init to be reflected in your session. To use the environment you need to activate it, which you do as follows: Platform Command Mac/Linux Terminal conda activate ./env Windows Terminal conda activate .\env Once you’ve activated the environment, you need to ensure that you have the packages required to render your documents. This will typically encompass jupyter / jupyterlab plus whatever other packages are used in your Python code. Use conda install to install packages into your environment. For example: Terminal conda install jupyter conda install pandas matplotlib Assuming you installed all of the required packages (likely more than just pandas and matplotlib) you should now be able to quarto render documents within the directory. Use conda deactivate to exit an activated environment: Terminal conda deactivate Saving Environments To make your environment reproducible, you need to create a environment.yml file that enumerates all of the packages in use. Do this using the conda env export command: Terminal conda env export > environment.yml You should generally check the environment.yml file into version control. Restoring Environments To reproduce the environment on another machine you just pass the environment.yml file as an argument to conda env create: Terminal conda env create --prefix env -f environment.yml More information For more on conda’s environment.yml, see Conda’s Managing Environments documentation. Using renv The renv package provides functionality similar to the venv and conda, but for R packages. To create a new renv environment, install the renv package from CRAN then call the renv::init() function: install.packages("renv") renv::init() As part of initialization, your .Rprofile file is modified to ensure that the renv is activated automatically at the start of each R session. If you plan on using both R and Python in your project, you can have renv automatically create and manage a Python virtual environment as follows: renv::use_python() To install R packages use the standard R install.packages function. You can also install GitHub packages using the renv::install function. For example: install.packages("ggplot2") # install from CRAN renv::install("tidyverse/dplyr") # install from GitHub To install Python packages just use pip as described above from the built-in RStudio terminal. Saving Environments To record the current versions of all R (and optionally Python) packages, use the renv::snapshot() function: renv::snapshot() This will record an renv.lock file for R packages and a requirements.txt file for Python packages). These files should be checked into version control. Restoring Environments To reproduce the environment on another machine use the renv::restore() function: renv::restore() JupyterLab To use Jupyter or JupyterLab within a Python virtual environment you just need to activate the environment and then launch the Jupyter front end. For example: Shell Command Mac/Linux Terminal source env/bin/activate python3 -m jupyter lab Windows (Command) Terminal env\Scripts\activate.bat py -m jupyter lab Windows (PowerShell) Terminal env\Scripts\Activate.ps1 py -m jupyter lab All of the Python packages installed within the env will be available in your Jupyter notebook session. The workflow is similar if you are using conda environments. RStudio If you are using Quarto within RStudio it is strongly recommended that you use the current release of RStudio from https://www.rstudio.com/products/rstudio/download/ (the documentation below assumes you are using this build). renv If you are using renv, RStudio will automatically do the right thing in terms of binding Quarto to the R and/or Python packages in your project-local environments. If you need to install R packages, use install.packages; if you need to install Python packages, simply use pip or conda within the terminal as described above. venv / condaenv RStudio will automatically activate any venv or condaenv that it finds within a project directory. Just be sure to create an RStudio project within the same directory where you created your env and things will work as expected with no additional configuration. If you need to install Python packages, simply use pip or conda within the terminal as described above. VS Code If you create a virtual environment in the env/ directory as described above, Visual Studio Code should automatically discover that environment when you load a workspace from the environment’s parent directory. Note that this applies only to venv not Conda environments (which have a separate mechanism for binding to the current VS Code session). You can read more about VS Code support for virtual environments here: https://code.visualstudio.com/docs/python/environments.
{ "lastmod": "2023-07-05T19:35:15.755Z", "loc": "https://quarto.org/docs/projects/virtual-environments.html", "source": "https://quarto.org/docs/projects/virtual-environments.html" }
Overview You may have one more more environment variables that you want to make sure are set whenever you render your project. For example, you might be using environment variables to: Provide the URL of a server to download data from. Set the address of a proxy server (e.g. HTTP_PROXY). Provide credentials for accessing a remote server (note that below we cover best practices for using credentials stored in environment variables). Tune the behavior of executable code (e.g. OMP_NUM_THREADS, ARROW_IO_THREADS, etc.) Provide options for language interpreters (e.g. PYTHONINSPECT or TZDIR). Determine which versions of Python and R are used (e.g. QUARTO_PYTHON, QUARTO_R, PY_PYTHON, or RETICULATE_PYTHON). Quarto projects can define a set of standard environment variables as well as vary which environment variables are defined based on the active project profile. It’s also possible to use environment variables that are defined only on the local system and not checked in to version control. Environment File If you include an _environment file at the root level of your project alongside _quarto.yml the values defined within the file will be read and set into the environment when the project configuration is read. For example: _environment HTTP_PROXY="https://proxy.example.com/" OMP_NUM_THREADS=4 These environment variables will be available both within Quarto’s execution context as well as in child processes (e.g. Jupyter kernels). Note that variables defined in environment files do not take precedence over definitions that already exist in the external environment. Rather, they provide defaults that will be applied when no external variable of the same name is already defined. You can include comments in environment files, as well as reference other environment variables. For example: _environment # database server DATABASE_SERVER=https://db.example.com DATABASE_API=${DATABASE_SERVER}/api When referencing another environment variable, it must either also be defined within the same file or already exist in the external environment. See the complete environment variable parsing rules for additional details on the syntax of environment files. Profile Environments If you are using Project Profiles to adapt your projects for different scenarios, you can create a custom environment file that will be activated along with the profile. For example, if you have a profile named production, then the variables defined in _environment-production will be read and applied. Here, we customize the OMP_NUM_THREADS environment variable to use more cores when running in production: _environment-production OMP_NUM_THREADS=16 Note that profile environments are merged with the default _environment so you need only define the variables that vary in your profile and can rely on the defaults for others. Important If you have secrets (e.g. access tokens) that you need to specify using environment variables you shouldn’t use profile environments (as they are often checked in to version control). We’ll cover the recommended technique for this in Managing Secrets below. Local Environment When working on a project locally you may want to use different values for some environment variables. For example, you might want to add some variables that provide additional diagnostic output for Python execution. You can do this by creating an _environment.local file. The values in the local file will override those specified in the default file: _environment.local PYTHONINSPECT=1 PYTHONDEVMODE=1 Note that _environment.local is not intended to be checked in to version control. Rather, it’s designed for values that you want active only on your system. To facilitate this, Quarto automatically adds the following to your project .gitignore file: .gitignore /_*.local This is especially useful when your environment variables contain secrets, which we’ll explore in more depth in the following section. Managing Secrets Frequently, credentials or authorization tokens are provided to code via environment variables. In many cases these credentials are required to render the project (for example, if the project is accessing data in a remote database or web service). It’s especially critical that these credentials are not checked in to version control. Typically, this is accomplished by a combination of: When running on a server or CI service, provide the environment variable as an encrypted secret. Details on how to do this vary between services (GitHub Actions has deployed secrets, Posit Connect supports content variables, etc.) For local development, define variables in the _environment.local file (and ignore this file in version control, as Quarto does by default). For example, here we specify AWS credentials in a local environment file: _environment.local AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI One problem this leaves is ensuring that these variables are always specified. The next section on required variables covers how to do this. Required Variables If there are certain environment variables that need to be specified in order to render the project, you can create an _environment.required file. This file can be copied to _environment.local as a starting point for local authoring, and also serves as documentation for server environments regarding which variables need to be defined. Returning to the example of AWS credentials, this _environment.required file provides documentation that these credentials will be required to render the project: _environment.required AWS_ACCESS_KEY_ID= AWS_SECRET_ACCESS_KEY= Then, the .local file (which again, is not checked in to version control) would be populated with the actual credentials: _environment.local AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI Further, any server environment that wants to render this project could validate that the required variables have been specified, and fail to run (with an appropriate error message) if they are not.
{ "lastmod": "2023-07-05T19:35:15.755Z", "loc": "https://quarto.org/docs/projects/environment.html", "source": "https://quarto.org/docs/projects/environment.html" }
Quarto 1.3 includes the following new features: Confluence Publishing—Publish quarto documents and projects to Confluence spaces. Multi-Format Publishing—Simple discovery of other formats for HTML documents. Jupyter Cell Embedding—Embed code and outputs from Jupyter Notebooks in Quarto documents. Article Grid Customization—Customize the widths within the article grid in HTML documents. Code Block Annotation—Use annotation to provide contextual comments to help readers understand code. Quarto Book AsciiDoc Support—Output Quarto books to AsciiDoc files Website Navigation Improvements—Improved navigation for Quarto websites. Mermaid Diagram Theming—Mermaid diagram’s appearance automatically matches your document’s theme (or customize it) PDF: SVG and Remote Images—Improved handling for SVG images and remote images in PDF documents. kbd Shortcode—Show well formatted keyboard shortcuts in Quarto documents. Extensions: Quarto AST—Use custom AST nodes for Quarto types like Callout when writing extensions. Extensions: HTML Tables—HTML tables are now processed and accessible to Lua filters in all formats (not just HTML). See the Pre-Release Download Page for a complete list of all the changes and bug fixes.
{ "lastmod": "2023-07-05T19:35:15.703Z", "loc": "https://quarto.org/docs/prerelease/1.3/index.html", "source": "https://quarto.org/docs/prerelease/1.3/index.html" }
Pre-release Feature This feature is new in the upcoming Quarto 1.3 release. To use the feature now, you’ll need to download and install the Quarto pre-release. Overview Quarto now supports custom AST nodes in Pandoc filters. This allows more flexibility in defining and using Lua filters. We will slowly roll out more extensive changes of the AST, but currently, the following objects are custom AST nodes: Callouts Tabsets Conditional Blocks Example: Callouts In previous versions of Quarto, callouts would be represented directly as a div with a class starting with callout, and the contents laid out in a particular way. While authoring documents, this syntax remains unchanged. But when processing the document, the callout divs are now represented as a custom AST node, which can be processed directly in Lua filters. In Quarto 1.3, callouts can be captured in Lua filters more directly. For example, here is a filter that forces every callout to be of type “caution”: function Callout(callout) -- do something with the callout callout.type = "caution" -- note that custom AST nodes are passed by reference. You can -- return the value if you choose, but you do not need to. end Finally, custom AST node constructors are available in the quarto object: quarto.Callout, quarto.Tabset, etc. See the pages above for details.
{ "lastmod": "2023-07-05T19:35:15.703Z", "loc": "https://quarto.org/docs/prerelease/1.3/ast.html", "source": "https://quarto.org/docs/prerelease/1.3/ast.html" }
Pre-release Feature This feature is new in the upcoming Quarto 1.3 release. To use the feature now, you’ll need to download and install the Quarto pre-release. Overview In Quarto 1.3, we have made some changes to how tables are processed. Recent Pandoc versions have added support for parsing HTML tables into Pandoc’s native data structures (including features such as rowspans and colspans), and Quarto now leverages this to make it easier to produce properly formatted tables in more formats. HTML tables are now processed in every format Specifically, Quarto will now attempt to parse HTML tables in RawBlock nodes in html format and convert them to Markdown tables, regardless of output format (intentionally including non-HTML formats). As a result, you can now use HTML table syntax in your documents and they will be properly converted to Markdown tables for all formats, and libraries which emit computational tables in HTML format can work in other output formats. In addition, this will allow Lua filters to manipulate the content of tables specified in HTML format. Note If you’re a library author, we hope that you will consider emitting HTML tables in your output. This will allow your users to use the full power of Quarto’s table processing in all formats. With that said, it’s possible that our processing of HTML tables interferes with your library’s processing. If this is the case, you can disable Quarto’s processing of HTML tables by adding the following data attribute to your table: <table data-quarto-disable-processing="true"> ... </table> Bootstrap classes can be added to tables Bootstrap table classes given as attributes next to a table caption are now inserted into the <table> element. The classes permitted are those that apply expressly to the entire table, and these are: "primary", "secondary", "success", "danger", "warning", "info", "light", "dark", "striped", "hover", "active", "bordered", "borderless", "sm", "responsive", "responsive-sm", "responsive-md", "responsive-lg", "responsive-xl", "responsive-xxl". For example, the following Markdown table will be rendered with row stripes and the rows will also be highlighted on hover: | fruit | price | |--------|--------| | apple | 2.05 | | pear | 1.37 | | orange | 3.09 | : Fruit prices {.striped .hover} Embedded Markdown content can be specified In addition, Quarto now supports the specification of embedded Markdown content in tables. This is done by providing a data attribute qmd or qmd-base64 in an embedded span or div node. These nodes can appear anywhere that such content is allowed: table headers, footers, cells, captions, etc. For example, consider the following table: <table> <caption><span data-qmd="As described in @Lovelace1864, computers are great."></span></caption> <thead> <tr> <th><span data-qmd="_Header 1_"></span></th> <th><span data-qmd="_Header 2_"></span></th> </tr> </thead> <tbody> <tr> <td><span data-qmd=""></span></td> <td>Regular output</td> </tr> </tbody> </table> The span nodes with the data-qmd attribute will be processed as embedded Markdown content. This allows you to embed arbitrary Markdown content in your tables, including citations, videos, etc. One thing to keep in mind is that the content of data-qmd needs to be escaped properly. Authors of libraries which generate table outputs should consider using the data-qmd-base64 attribute, which will be decoded and then processed by Quarto. Limitations Quarto doesn’t support processing of: nested <table> elements. invalid HTML tables. Make sure your emitted HTML passes validation.
{ "lastmod": "2023-07-05T19:35:15.703Z", "loc": "https://quarto.org/docs/prerelease/1.3/tables.html", "source": "https://quarto.org/docs/prerelease/1.3/tables.html" }
In Quarto 1.3, conditional blocks are represented as a custom AST node. You can create conditional block AST nodes in Lua filters with the quarto.ConditionalBlock constructor. The constructor takes a single parameter, a table with entries node, behavior, and condition, as described below. In Lua filters, conditional blocks are represented as a table with the following fields: node: the div containing the content behavior: either content-visible or content-hidden condition: a list of 2-element lists, such as { { "unless-format", "html" } } (optional in the constructor, default value {}). The first element of each sublist must be one of when-format, unless-format, when-profile, and unless-profile. The second element is the relevant format or profile.
{ "lastmod": "2023-07-05T19:35:15.703Z", "loc": "https://quarto.org/docs/prerelease/1.3/custom-ast-nodes/conditional-block.html", "source": "https://quarto.org/docs/prerelease/1.3/custom-ast-nodes/conditional-block.html" }
Pre-release Feature This feature is new in the upcoming Quarto 1.4 release. To use the feature now, you’ll need to download and install the Quarto pre-release. Quarto v1.4 includes support for the typst output format. Typst is a new open-source markup-based typesetting system that is designed to be as powerful as LaTeX while being much easier to learn and use. Typst creates beautiful PDF output with blazing fast render times. Getting Started To try out the typst format: Download and install the latest pre-release of Quarto 1.4 (ensure you have installed Quarto v1.4.145 or higher). Create a document that uses format: typst. For example: --- title: "My document" format: typst --- Hello, typst! Rendering or previewing this document will invoke the Typst CLI to create a PDF from your markdown source file. Note that Quarto includes version 0.5 of the Typst CLI so no separate installation of Typst is required. Typst Format When authoring a Typst document you’ll be using a Quarto format that is in turn based on a Typst template, which defines its structure, layout, and available options. The default Typst format and template that ships with Quarto (format: typst) includes options for specifying title, author, and abstract information along with basic layout and appearance (numbering, margins, fonts, columns, etc.). The following options are available for customizing Typst output: Option Description title Main document title author One or more document authors. date Date of publication abstract Article abstract toc Include a table of contents. number-sections Apply numbering to sections and sub-sections section-numbering Schema to use for numbering sections, e.g. 1.1.a. margin Margins: x, y, top, bottom, left, right. Specified with units (e.g. y: 1.25in or x: 2cm). papersize Paper size: a4, us-letter, etc. See the docs on paper sizes for all available sizes. fontsize Font size (e.g., 12pt) section-numbering Schema to use for numbering sections, e.g. 1.1.a. columns Number of columns for body text. include-in-header .typ file to include in header include-before-body .typ file to include before body include-after-body .typ file to include after the body keep-typ Keep the intermediate .typ file after render. bibliography .bib file to use for citations processing bibliographystyle Style to use with Typst’s bibliography processing - See the doc about bibliography to see supported style. citeproc If true, Pandoc’s citeproc will be used for citation processing instead of Typst’s own system (which is the default). csl .csl file to use when Pandoc’s citeproc is used. For example: --- title: "My Document" format: typst: toc: true section-numbering: true columns: 2 bibliography: refs.bib bibliographystyle: chicago-author-date --- See the section below on Custom Formats for details on creating your own specialized formats for use with Typst. Raw Blocks If you want to use raw typst markup, use a raw typst block. For example: ```{=typst} #set par(justify: true) == Background In the case of glaciers, fluid dynamics principles can be used to understand how the movement and behavior of the ice is influenced by factors such as temperature, pressure, and the presence of other fluids (such as water). ``` To learn more about typst markup, see the tutorial here: https://typst.app/docs/tutorial/. Bibliography Typst comes with its own citation processing system for Bibliography and using format: typst defaults to it. If you prefer to use Pandoc’s citation processing with a .csl file (e.g to use same .csl for a HTML and PDF document), set citeproc: true explicitly in YAML header. --- title: Typst doc using citeproc format: typst citeproc: true bibliography: refs.bib csl: https://www.zotero.org/styles/apa-with-abstract --- Typst File (.typ) The rendering process produces a native Typst file (.typ) which is then compiled to PDF using the Typst CLI. This intermediate file is then automatically removed. If you want to preserve the .typ file, use the keep-typ option. For example: --- title: "My Document" format: typst: keep-typ: true --- You can compile a .typ file to PDF directly using the quarto typst compile command in a terminal. For example: Terminal $ quarto typst compile article.typ The quarto typst command uses the version of Typst built in to Quarto and support all Typst CLI actions and flags. For example, to determine the version fo Typst embedeed in Quarto: Terminal $ quarto typst --version Known Limitations Cross references are supported for figures, sections, and equations (but not subfigures, tables ,or theorems as these aren’t yet supported in typst) Callouts are not yet supported (they become block quotes with a bold heading) Figure panels/layout are not currently supported. Advanced page layout (panel layout, margin layout, etc.) does not work Various other small things might not yet be implemented, please let us know if you see things that could use improvement! Custom Formats You can create highly customized output with Typst by defining a new format based on a custom Typst template. The Typst team has created several useful templates, a few which which have been adapted for use with Quarto as custom formats. These formats include: Format Usage IEEE quarto use template quarto-ext/typst-templates/ieee AMS quarto use template quarto-ext/typst-templates/ams Letter quarto use template quarto-ext/typst-templates/letter Fiction quarto use template quarto-ext/typst-templates/fiction Dept News quarto use template quarto-ext/typst-templates/dept-news The source code for these formats is available at https://github.com/quarto-ext/typst-templates. To create a new custom Typst format (or package an existing Typst template for use with Quarto) use the quarto create command to get started: Terminal $ quarto create extension format Then, choose typst as the base format and provide a name for the extension (e.g. letter). A sample Typst format extension will be created based on the code used in the default template that ships with Quarto. It will include the following files which you can edit to implement your custom format: To implement the custom format, edit the following files: File Description _extension.yml Basic extension metadata (name, author, description, etc.) and format definition. README.md Documentation on how to install and use the format. template.qmd A starter document that demonstrates the basics of the format. typst-template.typ The core Typst template function (documentation on creating Typst templates can be found here: https://typst.app/docs/tutorial/making-a-template/). typst-show.typ File that calls the template’s function (mapping Pandoc metadata to function arguments). Additional resources you might find useful when creating custom formats include: The official Typst tutorial on Making a Template List of third party templates from the Awesome Quarto repo. Template Partials Note This section covers advanced customization of Typst format output and can be safely ignored unless you have found the method of defining custom Typst formats described above too limited. Above we describe a method of creating a Typst format based on specifying two template partials (typst-template.typ and typst-show.typ). These partials customize components of the default Typst Pandoc template, but leave some of the core scaffolding including definitions required by Pandoc for its Typst output as well as handling of bibliographies and footnotes (this means that your own custom Typst formats do not need to explicitly handle them). If you would like to fully override the Pandoc template used for rendering Typst, use the template option in your custom format (rather than template-partials) and provide an alternate implementation of the default template. For example, your _extensions.yml might look like this: _extensions.yml --- title: Typst Custom Format author: Jane Smith version: "0.2.0" quarto-required: ">=1.4.11" contributes: formats: typst: template: template.typ template-partials: - typst-template.typ - typst-show.typ --- Use the source code of the default template as a starting point for your template.typ. Note that you can call all of the template partials provided by Quarto (e.g. biblio.typ() or notes.typ() from within your custom template implementation. The AMS format provides an example of redefining the main template (in that case, it is to prevent automatic bibliography processing by Quarto in deference to the built-in handling of the Typst AMS template).
{ "lastmod": "2023-07-05T19:35:15.703Z", "loc": "https://quarto.org/docs/prerelease/1.4/typst.html", "source": "https://quarto.org/docs/prerelease/1.4/typst.html" }
Gallery Quarto can produce a wide variety of output formats. Here are some examples: Articles & Reports Presentations Interactive Docs Websites Books Articles and reports with Python and R Create data-driven presentations Engage readers with interactivity Publish collections of articles as a website Create multi-format books Prevoius Next Articles & Reports Write a single markdown file and create output in a variety of formats. HTML for web publishing PDF for high quality print MS Word for Office workflows HTML with advanced layout PDF with advanced layout Presentations Create presentations (slide show) in a variety of formats. RevealJS HTML presentations Beamer PDF presentations PowerPoint presentations Streamlining with R An educator's perspective of the tidyverse An anthology of experimental designs The untold story of palmerpenguins Outrageously efficient EDA Improvements in textrecipes Interactive Docs Engage readers and deliver more insights with interactive documents. Observable reactive JavaScript Shiny web framework for R Jupyter interactive widgets Websites Publish collections of articles as a website quarto.org documentation R-Manuals documentation Quarto tip a day blog nbdev from fast.ai Practical Deep Learning from fast.ai Beatriz Milz personal website + blog Mike Mahoney personal website + blog ForBo7 // Salman Naqvi personal site + blog + works LTM Data Workflows w/ Arrow workshop Julia Workshop for Data Science course STA 210 - Regression Analysis course The MockUp blog mrgsolve documentation NASA & OpenScapes website 2021 Cloud Hackathon event Making shareable docs with Quarto tutorial Data Science in a Box course website Wannabe Rstats-fu blog Hamel Husain's Professional Site blog + notes Python for Data Science course website + notebooks fluidsyndicate open source material for performances Real World Data Science Ethical, impactful data science by the RSS Hertie Coding Club Website platform to learn coding skills Books Publish a book in multiple formats Modern Polars Hands on Programming with R Visualization Curriculum Python for Data Analysis, 3E R for Data Science, 2E R Packages mlr3book Telling Stories with Data Geocomputation with Python utilitR documentation (French) Analyse et conception de logiciels (French) Time Series Analysis Causal Inference in R R for Clinical Study Reports and Submission Cookbook Polars for R No matching items
{ "lastmod": "2023-07-05T19:35:15.299Z", "loc": "https://quarto.org/docs/gallery/index.html", "source": "https://quarto.org/docs/gallery/index.html" }
Overview Posit Connect is a publishing platform for secure sharing of data products within an organization. Use Posit Connect when you want to publish content within an organization rather than on the public internet. There are several ways to publish Quarto content to Posit Connect: Use the quarto publish command to publish static content rendered on your local machine. Use the rsconnect-python Python package or quarto R package to publish code for rendering on an Posit Connect server (e.g. for a scheduled report). Use Connect’s support for Git backed content to automatically re-publish content when code is checked in to a Git repository. Use a Continuous Integration (CI) service like Jenkins, Airflow, or GitHub Actions, to render and publish to Connect. Each of these options is covered in detail below. If you are just getting started, we strongly recommend using the first approach (quarto publish). Then, as your needs evolve, you can consider other more sophisticated options. Publish Command The quarto publish command is the easiest way to publish locally rendered content. From the directory where your project is located, execute the quarto publish command for Connect: Terminal quarto publish connect If you haven’t previously published to Connect you’ll be prompted to enter your server’s URL: Terminal $ quarto publish connect ? Server URL: › You’ll then need to provide a Connect API Key: Terminal $ quarto publish connect ? Server URL: › https://connect.example.com/ ? API Key: › After authenticating, your content will be rendered and published, and then a browser will open to view its admin page on Connect. A record of your previous publishes will be stored in a _publish.yml file within the project or document directory. This file stores the service, id, and URL of the published content. For example: - source: project connect: - id: "3bb5f59f-524a-45a5-9508-77e29a1e8bf0" url: "https://connect.example.com/content/3bb5f59f-524a-45a5-9508-77e29a1e8bf0/" Account information is not stored in this file, so it is suitable for checking in to version control and being shared by multiple publishers. You can customize this behavior of quarto publish by providing the following command line options: Option Behavior --no-prompt Do not prompt to confirm publish actions. --no-browser Do not open a browser after publish. --no-render Do not re-render prior to publish To publish a document rather than a website or book, provide the path to the document: Terminal quarto publish connect document.qmd Publishing with Code In the preceding example, we rendered content locally and then published it to Connect. In some cases, however, you may want to publish your source code to Connect and then have it rendered on the server (for example, to create a scheduled report that is updated with new data automatically). The tools for publishing code differ depending on whether you are using the Knitr (R) or Jupyter (Python) engine, so we’ll cover them separately below. Note that Quarto must be installed on the Connect server before you attempt to publish with code (this is typically done by an administrator, see the Quarto Installation documentation for additional details). Knitr (R) The quarto R package includes a set of publishing functions that you can use for publishing Quarto projects with R code to Posit Connect. For example, here we publish a document and a website: library(quarto) quarto_publish_doc( "document.qmd", server = "rsc.example.com", account = "njones", render = "server" ) quarto_publish_site( server = "rsc.example.com", account = "njones", render = "server" ) The render = "server" argument is what specifies that you want code rather than just content published. Note that once you’ve published for the first time you can update without providing the explicit arguments: quarto_publish_site() See the article on Quarto Publishing from R for additional details on using these functions. RStudio IDE If you are using the RStudio IDE, there is also support for push-button publishing to Posit Connect. Use the publish button from the source editor or viewer pane to publish a document or a website: See the Connect documentation on Publishing from the RStudio IDE for additional details. Jupyter (Python) The rsconnect-python Python package provides a command line interface (CLI) that you can use to publish Quarto documents and websites that use Jupyter to Posit Connect. To use the CLI: First, install the rsconnect-python package and configure an Posit Connect server for publishing: https://docs.rstudio.com/connect/user/connecting-cli/ Then, use the rsconnect deploy quarto command from your project directory: Terminal rsconnect deploy quarto See the complete documentation on Publishing Quarto Content for additional details on using the CLI for publishing to Connect. Notebook Plugin If you are using the classic Jupyter Notebook you can install the rsconnect-jupyter notebook plugin to enable push button publishing of Jupyter notebooks: First, follow the directions in the rsconnect-jupyter User Guide to install the plugin. Then, click the publish button from a notebook you wish to publish. You’ll be prompted to configure a Connect server and then be presented with a publishing dialog: See the article on Publishing Jupyter Notebooks for complete documentation on using the plugin. Publishing from Git Content may be deployed to Posit Connect directly from a remote Git repository. Content will automatically fetch from the associated remote Git repository and re-deploy. This allows for integration with Git-centric workflows and continuous deployment automation. In order to deploy Git-backed content to Posit Connect you’ll follow a two step process: Create and commit a manifest file (this includes information on the R or Python dependencies required to render your content) Link Posit Connect to the Git repository Note that Quarto must be installed on the Connect server before you attempt to publish from Git (this is typically done by an administrator, see the Quarto Installation documentation for additional details). Creating a Manifest Consult the Connect documentation on Git Backed Content for complete details on creating manifests and checking them in to your repository. To give you a general idea of how this works, here is some sample code that creates a manifest for Knitr and Jupyter projects: # write a manifest for a Knitr project install.packages("rsconnect") # if required rsconnect::writeManifest() Terminal # write a manifest for a Jupyter notebook pip install rsconnect-python # if required rsconnect write-manifest notebook MyNotebook.ipynb See the documentation on Git Backed Content for complete details on creating manifests. Connecting a Repository Connect users must have at least the publisher role in order to create new content from a Git repository. On the Content page, there is a button near the top labeled Publish. Clicking on this button will expand a menu which contains an item called “Import from Git”, which may be clicked to launch a new content wizard. You’ll be prompted to provide your repository URL, branch to publish from, and target directory to publish from (e.g., the one containing your manifest.json). See the documentation on Git Backed Content for complete details on connecting Git repositories to Connect. Continuous Integration You can also deploy Quarto content using a Continuous Integration (CI) service like Jenkins, Airflow, or GitHub Actions. In most cases, this will entail scripting the quarto publish command, however in the case of GitHub Actions, you can take advantage of the standard Quarto publish action. When publishing to Connect from a CI service you’ll need to consider whether you want to execute your Python or R code directly on the CI server or whether you want to take advantage of previously frozen execution results. We’ll explore this possibility first and then proceed to the specifics of how to publish from CI. Freezing Computations Depending on how complicated your run-time requirements (packages, database credentials, etc.) are, you might find it more convenient to restrict execution of Python and R code to local contexts that have the required software and credentials. To make sure that R, Python, and Julia code is only executed locally, configure your project to use Quarto’s freeze feature by adding this to your _quarto.yml: _quarto.yml execute: freeze: auto Now, fully re-render your site: Terminal quarto render If you have executable code in your project you’ll notice that a _freeze directory has been created at the top level of your project. This directory stores the results of computations and should be checked in to version control. Whenever you change a .qmd file with executable code, it will automatically be re-run during your next render and the updated computations will be stored in _freeze. If you’d rather have CI publishing execute all Python and R code contained in your project, you’ll need to ensure that the requisite version of these tools (and any required packages) are installed on the CI server. How to do this is outside the scope of this article—to learn more about saving and restoring dependencies, see the article on Virtual Environments. Publish Command You can publish Quarto content to Connect using any CI service by scripting the quarto publish command. To do this, you’ll need to make sure that your Connect server address and credentials are available as environment variables on the CI server. Variable Description CONNECT_SERVER Address of Posit Connect server (e.g., https://connect.example.com). CONNECT_API_KEY Posit Connect API Key You will furthermore need to specify the ID of the target content to update. This will most frequently be drawn from the _publish.yml file that is saved into your project directory during publishing. For example: _publish.yml - source: project connect: - id: 4f2ffc46-24b0-4cc7-a854-c5eb671e0dd7 url: 'https://connect.example.com/content/4f2ffc46-24b0-4cc7-a854-c5eb671e0dd7/' Assuming that you have a _publish.yml like the above, you can publish to Connect from CI with the following commands: Terminal export CONNECT_SERVER=https://connect.example.com/ export CONNECT_API_KEY=7C0947A852D8 quarto publish connect Alternatively, if you don’t have a _publish.yml file, you can specify the ID on the command line as follows: Terminal quarto publish connect --id 4f2ffc46-24b0-4cc7-a854-c5eb671e0dd7 GitHub Actions If your CI service is GitHub Actions then you can take advantage of Quarto’s standard publish action to automate deploying to Connect. Server Credentials Before creating the publish action, you need to ensure that your repository has the credentials required for publishing to Connect. You can do this as follows: If you don’t already have one, create an Posit Connect API Key from the requisite Connect server and then copy it to the clipboard. Add the Connect API Key to your repository’s action Secrets (accessible within repository Settings). You will see a New repository secret button at the top right: Click the button and add the API Key from step 1 as a secret named CONNECT_API_KEY: Publish Action To setup your publish action, create a .github/workflows/publish.yml file in your repository. If you are Freezing Computations (i.e. not running Python or R code within your action), then the file would look something like this: .github/workflows/publish.yml on: workflow_dispatch: push: branches: main name: Quarto Publish jobs: build-deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2 - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: connect CONNECT_SERVER: https://connect.example.com CONNECT_API_KEY: ${{ secrets.CONNECT_API_KEY }} Once you’ve pushed your updated repository (including the publish action and _freeze directory) to GitHub, your action will run with this and subsequent commits, automatically rendering and publishing to Connect. Executing Code If you prefer, you can also configure GitHub Actions to execute Python or R code as part of rendering. While this might reflexively seem like the best approach, consider the following requirements imposed when you execute code within a CI service like GitHub Actions: You need to reconstitute all of the dependencies (R, Python, or Julia plus the correct versions of required packages) in the CI environment. If your code requires any special permissions (e.g. database or network access) those permissions also need to be present on the CI server. Your project may contain documents that can no longer be easily executed (e.g. blog posts from several years ago that use older versions of packages). These documents may need to have freeze individually enabled for them to prevent execution on CI. Prerequisites The best way to ensure that your code can be executed within a GitHub Action is to use a virtual environment like venv or renv with your project (below we’ll provide example actions for each). If you aren’t familiar with using these tools check out the article on using Virtual Environments with Quarto to learn more. Once you’ve decided to execute code within your GitHub Action you can remove the freeze: auto described above from your _quarto.yml configuration. Note that if you want to use freeze selectively for some documents or directories that is still possible (for a directory, create a _metadata.yml file in the directory and specify your freeze configuration there—this is what Quarto does by default for the posts folder of blog projects). Example: Jupyter with venv Here is a complete example of a GitHub Action that installs Python, Jupyter, and package dependencies from requirements.txt, then executes code and renders output to Connect: .github/workflows/publish.yml on: workflow_dispatch: push: branches: main name: Quarto Publish jobs: build-deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2 - name: Install Python and Dependencies uses: actions/setup-python@v4 with: python-version: '3.10' cache: 'pip' - run: pip install jupyter - run: pip install -r requirements.txt - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: connect CONNECT_SERVER: https://connect.example.com CONNECT_API_KEY: ${{ secrets.CONNECT_API_KEY }} Example: Knitr with renv Here is a complete example of a GitHub Action that installs R and package dependencies from renv.lock, then executes code and renders output to Connect: .github/workflows/publish.yml on: workflow_dispatch: push: branches: main name: Quarto Publish jobs: build-deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2 - name: Install R uses: r-lib/actions/setup-r@v2 with: r-version: '4.2.0' - name: Install R Dependencies uses: r-lib/actions/setup-renv@v2 with: cache-version: 1 - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: connect CONNECT_SERVER: https://connect.example.com CONNECT_API_KEY: ${{ secrets.CONNECT_API_KEY }} Additional Options It’s possible to have a Quarto project in a larger GitHub repository, where the Quarto project does not reside at the top-level directory. In this case, add a path input to the invocation of the publish action. For example: - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: connect path: subdirectory-to-use CONNECT_SERVER: https://connect.example.com CONNECT_API_KEY: ${{ secrets.CONNECT_API_KEY }} By default, quarto publish will re-render your project before publishing it. However, if you store the rendered output in version control, you don’t need the GitHub action to re-render the project. In that case, add the option render: false to the publish action: - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: connect render: false CONNECT_SERVER: https://connect.example.com CONNECT_API_KEY: ${{ secrets.CONNECT_API_KEY }}
{ "lastmod": "2023-07-05T19:35:15.795Z", "loc": "https://quarto.org/docs/publishing/rstudio-connect.html", "source": "https://quarto.org/docs/publishing/rstudio-connect.html" }
Overview There are a wide variety of ways to publish documents, presentations, and websites created using Quarto. Since content rendered with Quarto uses standard formats (HTML, PDFs, MS Word, etc.) it can be published anywhere. Additionally, there is a quarto publish command available for easy publishing to various popular services (GitHub, Netlify, Posit Connect, etc.) as well as various tools to make it easy to publish from a Continuous Integration (CI) system. Getting Started To get started, review the documentation for using one of the following publishing services: Destination Description Quarto Pub Publishing service for Quarto documents, websites, and books. Use Quarto Pub when you want a free, easy to use service for publicly available content. GitHub Pages Publish content based on source code managed within a GitHub repository. Use GitHub Pages when the source code for your document or site is hosted on GitHub. Posit Connect Publishing platform for secure sharing of data products within an organization. Use Posit Connect when you want to publish content within an organization rather than on the public internet. Netlify Professional web publishing platform. Use Netlify when you want support for custom domains, authentication, previewing branches, and other more advanced capabilities. Confluence Publishing platform for supporting team collaboration. Use Confluence to share documents in team Spaces. Other Services Content rendered with Quarto uses standard formats (HTML, PDFs, MS Word, etc.) that can be published anywhere. Use this if one of the methods above don’t meet your requirements. If you don’t know which to choose, try Quarto Pub which is a free service for publicly available content. If you are publishing to a destination not listed above, choose Other Services. These articles cover both straightforward direct publishing as well as Continuous Integration (CI) publishing with GitHub Actions. If you want to publish using CI and aren’t using GitHub Actions, the article on Publishing with CI provides additional details and documentation.
{ "lastmod": "2023-07-05T19:35:15.795Z", "loc": "https://quarto.org/docs/publishing/index.html", "source": "https://quarto.org/docs/publishing/index.html" }
Overview Quarto Pub is a free publishing service for content created with Quarto. Quarto Pub is ideal for blogs, course or project websites, books, presentations, and personal hobby sites. It’s important to note that all documents and sites published to Quarto Pub are publicly visible. You should only publish content you wish to share publicly. There are two ways to publish content to Quarto Pub (both are covered in more detail below): Use the quarto publish command to publish content rendered on your local machine (this is the recommend approach when you are getting started). If you are using GitHub, you can use a GitHub Action to automatically render your project and publish the resulting content whenever your code changes. Before attempting your first publish, be sure that you have created a free Quarto Pub account. Note Quarto Pub sites are publicly visible, can be no larger than 100 MB and have a softlimit of 10 GB of bandwidth per month. If you want to authenticate users, host larger sites, or use a custom domain, consider using a professional web publishing service like Netlify instead. Publish Command The quarto publish command is the easiest way to publish locally rendered content. From the directory where your project is located, execute the quarto publish command for Quarto Pub: Terminal quarto publish quarto-pub If you haven’t published to Quarto Pub before, the publish command will prompt you to authenticate. After confirming that you want to publish, your content will be rendered and deployed, and then a browser opened to view your site. _publish.yml The _publish.yml file is used to to specify the publishing destination. This file is automatically created (or updated) whenever you execute the quarto publish command, and is located within the project or document directory. The service, id, and URL of the published content is specified in _publish.yml. For example: - source: project quarto-pub: - id: "5f3abafe-68f9-4c1d-835b-9d668b892001" url: "https://njones.quarto.pub/blog" If you have an existing Quarto Pub site that you want to publish to, you should manually create a _publish.yml file that looks like the example above, but with the appropriate id and url values for your site. Account information is not stored in _publish.yml, so it is suitable for checking in to version control and being shared by multiple publishers. Options You can customize the behavior of quarto publish by providing the following command line options: Option Behavior --no-prompt Do not prompt to confirm publish actions. --no-browser Do not open a browser after publish. --no-render Do not re-render prior to publish To publish a document rather than a website or book, provide the path to the document: Terminal quarto publish quarto-pub document.qmd Managing Sites If you want to change the “slug” (or URL path) of a published site or remove the site entirely, you can use the site management interface at https://quartopub.com, which will display a list of all of your published sites: Click on a site to navigate to an admin page that enables you to change the slug, make the site the default one for your account, or remove the site entirely: User Default Site In addition to publishing documents and sites to paths within your Quarto Pub sub-domain (e.g. https://username.quarto.pub/mysite/) you can also designate one of your sites as the default site that users see when they navigate to your main sub-domain (e.g. https://username.quarto.pub). This is an ideal place to publish a blog or personal home page. To promote one of your sites to the default site, go to your admin page at https://quartopub.com, navigate to the site you want to promote, check the Default Site option, then Save your modified options: Multiple Accounts If you are have multiple Quarto Pub accounts it’s important to understand the relationship between the use of accounts in the CLI interface (quarto publish) and the use of accounts in your browser (for authenticating and managing sites). When using quarto publish, there are a couple of scenarios where a web browser is launched: When you need to authorize the Quarto CLI to access your account. After publishing to open the admin page for your published site. Before publishing with a Quarto Pub account from the CLI you should always be sure to log in to that account within your default web browser. This ensures that when the CLI launches the browser that it binds to the correct Quarto Pub account. Access Tokens When you publish to Quarto Pub using quarto publish an access token is used to grant permission for publishing to your account. If no access token is available for a publish operation then the Quarto CLI will automatically launch a browser to authorize one: $ quarto publish quarto-pub ? Authorize (Y/n) › ❯ In order to publish to Quarto Pub you need to authorize your account. Please be sure you are logged into the correct Quarto Pub account in your default web browser, then press Enter or 'Y' to authorize. Authorization will launch your default web browser to confirm that you want to allow publishing from Quarto CLI. An access token will be generated and saved locally by the Quarto CLI. You can list and remove saved accounts using the quarto publish accounts command: $ quarto publish accounts ? Manage Publishing Accounts ❯ ✔ Quarto Pub: [email protected] ✔ Netlify: [email protected] ❯ Use the arrow keys and spacebar to specify accounts you would like to remove. Press Enter to confirm the list of accounts you wish to remain available. You can also view (and revoke) access tokens from the admin interface at https://quartopub.com: Within this interface you’ll see any token you’ve created from the Quarto CLI. You may revoke this token if you no longer wish it to be active. Click the New Token button to create additional tokens that can be used for publishing non-interactively (e.g. from a CI service): Once you have an access token you can use it with quarto publish by defining the QUARTO_PUB_AUTH_TOKEN environment variable. For example: Terminal # token created at https://quartopub.com/profile/ export QUARTO_PUB_AUTH_TOKEN="qpa_k4yWKEmlu5wkvx173Ls" # publish to quarto-pub site specified within _publish.yml quarto publish quarto-pub See the article on Publishing with CI for additional details on non-interactive use of quarto publish. GitHub Action Using the quarto publish quarto-pub command to publish locally rendered content is the most simple and straightforward way to publish. Another option is to use GitHub Actions to render and publish your site (you might prefer this if you want execution and/or rendering to be automatically triggered from commits). There are a few different ways to approach rendering and publishing content. Below, we’ll provide a how-to guide for publishing with GitHub Actions. For more conceptual background on the various approaches, see the discussion on Rendering for CI. Publish Record Prior to attempting to publish with a GitHub Action, you should have completed at least one publish using the Publish Command (described immediately above). This publish will create a _publish.yml file that records the publishing destination to be used by the GitHub Action. For example: - source: project quarto-pub: - id: "5f3abafe-68f9-4c1d-835b-9d668b892001" url: "https://njones.quarto.pub/blog" You can also manually create a _publish.yml file that looks like the example above, but with the appropriate id and url values for your site. Do not proceed to the next step(s) until you have a _publish.yml that indicates your publishing destination. Freezing Computations To make sure that R, Python, and Julia code is only executed locally, configure your project to use Quarto’s freeze feature by adding this to your _quarto.yml: _quarto.yml execute: freeze: auto Now, fully re-render your site: Terminal quarto render If you have executable code in your project you’ll notice that a _freeze directory has been created at the top level of your project. This directory stores the results of computations and should be checked in to version control. Whenever you change a .qmd file with executable code, it will automatically be re-run during your next render and the updated computations will be stored in _freeze. Note that an alternative approach is to execute the code as part of the GitHub Action. For now we’ll keep things simpler by executing code locally and storing the computations by using freeze. Then, further below, we’ll cover [Executing Code] within a GitHub Action. Publish Action Add a publish.yml GitHub Action to your project by creating this YAML file and saving it to .github/workflows/publish.yml: .github/workflows/publish.yml on: workflow_dispatch: push: branches: main name: Quarto Publish jobs: build-deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2 - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: quarto-pub QUARTO_PUB_AUTH_TOKEN: ${{ secrets.QUARTO_PUB_AUTH_TOKEN }} Quarto Pub Credentials The final step is to configure your GitHub Action with the credentials required for publishing. To do this you need to create a Quarto Pub personal access token and then configure your GitHub action to be able to read it: If you don’t already have an access token, go to the Quarto Pub account profile page, and click on New Token to create a token. Give this token a memorable name, and copy the token to the clipboard. Add the Quarto Pub access token to your repository’s action Secrets (accessible within repository Settings). You will see a New repository secret button at the top right: Click the button and add the personal access token from step 1 as a secret named QUARTO_PUB_AUTH_TOKEN: Ignoring Output It’s important to note that you don’t need to check your _site or _book directory into version control (if you have done this in the past you know it makes for very messy diffs!). Before proceeding you should add the output directory of your project to .gitignore. For example: .gitignore /.quarto/ /_site/ If you’ve already checked these files into source control you may need to remove them explicitly: Terminal git rm -r _site Commit to Publish Once you’ve specified your publishing action and Quarto Pub credentials, and pushed your updated repository (including the _freeze directory) to GitHub, your action will run with this and subsequent commits, automatically rendering and publishing to Quarto Pub. Executing Code If you prefer, you can also configure a GitHub Action to execute R, Python, or Julia code as part of rendering. While this might reflexively seem like the best approach, consider the following requirements imposed when you execute code within a CI service like GitHub Actions: You need to reconstitute all of the dependencies (R, Python, or Julia plus the correct versions of required packages) in the CI environment. If your code requires any special permissions (e.g. database or network access) those permissions also need to be present on the CI server. Your project may contain documents that can no longer be easily executed (e.g. blog posts from several years ago that use older versions of packages). These documents may need to have freeze individually enabled for them to prevent execution on CI. Prerequisites The best way to ensure that your code can be executed within a GitHub Action is to use a virtual environment like venv or renv with your project (below we’ll provide example actions for each). If you aren’t familiar with using these tools check out the article on using Virtual Environments with Quarto to learn more. Once you’ve decided to execute code within your GitHub Action you can remove the freeze: auto described above from your _quarto.yml configuration. Note that if you want to use freeze selectively for some documents or directories that is still possible (for a directory, create a _metadata.yml file in the directory and specify your freeze configuration there—this is what Quarto does by default for the posts folder of blog projects). Example: Jupyter with venv Here is a complete example of a GitHub Action that installs Python, Jupyter, and package dependencies from requirements.txt, then executes code and renders output to Quarto Pub: .github/workflows/publish.yml on: workflow_dispatch: push: branches: main name: Quarto Publish jobs: build-deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2 - name: Install Python and Dependencies uses: actions/setup-python@v4 with: python-version: '3.10' cache: 'pip' - run: pip install jupyter - run: pip install -r requirements.txt - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: quarto-pub QUARTO_PUB_AUTH_TOKEN: ${{ secrets.QUARTO_PUB_AUTH_TOKEN }} Example: Knitr with renv Here is a complete example of a GitHub Action that installs R and package dependencies from renv.lock, then executes code and renders output to Quarto Pub: .github/workflows/publish.yml on: workflow_dispatch: push: branches: main name: Quarto Publish jobs: build-deploy: runs-on: ubuntu-latest steps: - name: Check out repository uses: actions/checkout@v3 - name: Set up Quarto uses: quarto-dev/quarto-actions/setup@v2 - name: Install R uses: r-lib/actions/setup-r@v2 with: r-version: '4.2.0' - name: Install R Dependencies uses: r-lib/actions/setup-renv@v2 with: cache-version: 1 - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: quarto-pub QUARTO_PUB_AUTH_TOKEN: ${{ secrets.QUARTO_PUB_AUTH_TOKEN }} Additional Options It’s possible to have a Quarto project in a larger GitHub repository, where the Quarto project does not reside at the top-level directory. In this case, add a path input to the invocation of the publish action. For example: - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: quarto-pub path: subdirectory-to-use QUARTO_PUB_AUTH_TOKEN: ${{ secrets.QUARTO_PUB_AUTH_TOKEN }} By default, quarto publish will re-render your project before publishing it. However, if you store the rendered output in version control, you don’t need the GitHub action to re-render the project. In that case, add the option render: false to the publish action: - name: Render and Publish uses: quarto-dev/quarto-actions/publish@v2 with: target: quarto-pub render: false QUARTO_PUB_AUTH_TOKEN: ${{ secrets.QUARTO_PUB_AUTH_TOKEN }}
{ "lastmod": "2023-07-05T19:35:15.795Z", "loc": "https://quarto.org/docs/publishing/quarto-pub.html", "source": "https://quarto.org/docs/publishing/quarto-pub.html" }
Quarto 1.3 Feature This feature is new in Quarto 1.3, which you can download at https://quarto.org/docs/download/ Overview Atlassian Confluence is a publishing platform for supporting team collaboration. Confluence has a variety of hosting options which include both free and paid subscription plans. Quarto provides support for publishing individual documents, as well as projects composed of multiple documents, into Confluence Spaces. A Quarto Document Published to Confluence A Quarto Project Published to Confluence Managing Confluence content with Quarto allows you to author content in Markdown, manage that content with your usual version control tools like Git and GitHub, and leverage Quarto’s tools for including computational output. The next section, Confluence Publishing Basics, walks through the process of publishing a single page to Confluence, including how to set up your Confluence account in Quarto, and how to specify a destination for your document in your Confluence Space. Before you use Confluence Publishing for your own project you’ll want to read the remaining sections on this page: Publishing Projects describes how to publish a collection of documents, including how your project structure translates to the structure of pages in your Confluence Space. Publishing Workflow describes the model for making updates to Confluence pages published from Quarto, including the page permissions that are set when you publish from Quarto. Authoring for Confluence describes some of the differences between authoring for Confluence and authoring for a Quarto website. Publishing Settings covers how to manage your publishing settings. Be Careful with Sensitive or Confidential Content Publishing Quarto documents to a public Confluence space will make the content of those documents public. It is your responsibility to understand the permissions of your Confluence Space and verify your publishing destination to protect against any sensitive or confidential content from being made publicly available. Confluence Publishing Basics To demonstrate the process of publishing to Confluence, we’ll take a single document, confluence-demo.qmd, and publish it as a page to a Confluence space. Here’s the contents of confluence-demo.qmd: --- title: Confluence Demo format: confluence-html --- ## Overview Write your content in Quarto documents and publish to Confluence. Notice that the format is set to confluence-html in the document YAML. This allows the local preview of the document to mimic the eventual appearance on Confluence. You can preview your document locally as you would any other Quarto document, by using the Render command in VS Code and RStudio, or by using quarto preview from the command line: Terminal quarto preview confluence-demo.qmd The result of previewing confluence-demo.qmd locally is shown below: The preview attempts to provide an accurate idea of how your content will look. However, some items in the preview are merely placeholders, like the publishing date, author, and read time in the header. When the document is published to Confluence, these items will be generated by Confluence. To publish a document to Confluence use quarto publish confluence followed by the file name: Terminal quarto publish confluence confluence-demo.qmd Unless you’ve published to Confluence before, you’ll be prompted to set up an account and select a destination for your page. Setting Up Your Account When you publish to Confluence for the first time, you’ll be prompted to set up a Confluence account in Quarto. To prepare, log in to Confluence, and navigate to the space, or page within a space, which you wish to publish to. You’ll first be prompted for your Confluence Domain. This is the first part of the URL to the Confluence page you wish to publish to. For example: Terminal ? Confluence Domain: › ❯ e.g. https://mydomain.atlassian.net/ Next, you’ll be asked to enter the Email Address for the account used in this Confluence Domain (if you are unsure, look at your account profile on Confluence): Terminal ? Confluence Account Email: › Finally, you’ll be asked for an API Token: Terminal ? Confluence API Token: › ❯ Create an API token at https://id.atlassian.com/manage/api-tokens Confluence API Tokens are specific to your account. You’ll need to create a token, copy, and then paste it into this prompt. For more information on Access Tokens please see the Confluence Documentation on API Tokens. Quarto saves this account information (domain, email and token) so it can be used for future calls to quarto publish confluence. The final prompt will ask you to select a destination for your page. Selecting a Destination Pages in Confluence are arranged in a hierarchy: every page has a parent. When you publish from Quarto to Confluence you’ll be asked to specify the parent for your page by providing its URL: Terminal ? Space or Parent Page URL: › ❯ Browse in Confluence to the space or parent, then copy the URL If you want your page to be at the top level of your space, specify the space itself, e.g.: https://domain.atlassian.net/wiki/spaces/ABBR Otherwise, specify the URL for the parent page, e.g.: https://domain.atlassian.net/wiki/spaces/ABBR/pages/123456 Once the destination is specified, Quarto will render the page for publishing, publish it to Confluence, and open a browser to view the published page. An example of the published version of confluence-demo.qmd is shown below: In the sidebar navigation this page is listed at the top level under Pages because the destination was set to the space URL. Publishing Projects To publish a collection of documents, organize your documents in a Quarto project, and use the confluence project type. Here’s a minimal _quarto.yml file for a Confluence project: _quarto.yml project: type: confluence Include this file in a project directory, then arrange your .qmd or .ipynb documents into whatever hierarchy you want to use for publishing. For example: _quarto.yml index.qmd team.qmd projects/ planning.qmd retrospectives.qmd Alternatively, to get started with a template project in a new directory, use quarto create: Terminal quarto create project confluence As with documents, you can preview your project using the Render command in VS Code and RStudio, or by using quarto preview from the command line: Terminal quarto preview The project preview produces an HTML website with navigation automatically added to the sidebar. This navigation is for convenience, the navigation for the published pages will be handled internally by Confluence. Tip The project preview attempts to style your content as it will appear on Confluence, however, you may notice some differences in appearance. To publish your project run quarto publish confluence from your project folder: Terminal quarto publish confluence You’ll be walked through the same steps as publishing a single document, setting up an account, if needed, and selecting a destination for your project on Confluence, before publishing your project to Confluence. Project Structure The hierarchy of documents inside folders in your project will be respected in the publishing process. Confluence’s concept of folders is that pages can have children, so your folders will be represented by pages in Confluence. When a project is published, a single page is created in Confluence to hold it. Documents at the top level of the project are published as pages nested under this project page. Folders inside the project are represented by a page, and any documents (or other folders) inside the folder are represented as pages nested under the folder page. As an example, consider the following project structure: example-project/ ├── _quarto.yml ├── project-roadmap.qmd ├── reports-folder │ ├── 2023-01.qmd │ └── 2023-03.qmd └── team-members.qmd The Confluence structure resulting from publishing this project to the top level of the space is shown below: The titles used in the Confluence sidebar navigation are taken from the page and project title, as specified in the document YAML and _quarto.yml respectively, and generated from the folder name for folders. Quarto may add some additional characters to meet the Confluences requirement that every page in a space has a unique name. index.qmd Pages in Confluence that represent folders will have no content unless an index.qmd is found inside the folder. If an index.qmd file exists its content will populate the folder page. For example, consider the following index.qmd: index.qmd --- title: Reports --- Monthly reports on project progress Adding this to the folder reports-folder and re-publishing the site, changes the name of the page representing this folder to “Reports” and adds this contents to the page. Publishing Workflow In Confluence, many people are able to make direct edits to pages. However, managing your content from Quarto requires a shift in perspective: edits to pages are made only in the Quarto project, and only one account should publish those changes to Confluence. Publishing to Confluence is a one-way street: there is no way to bring back content edits from Confluence to your Quarto project. Edits that are made on Confluence will be overwritten next time the page is published from Quarto. Updating a page requires editing the document in Quarto, and rerunning: Terminal quarto publish confluence To help avoid a situation where someone inadvertently edits a page being managed in Quarto, the permissions for pages are set when you publish so everyone with access to the space can view the page, but only you, the publisher, can edit the page. Permission to edit the page includes publishing updates, so any updates to a page need to be published from the same account as the original publish. Publishing without Control over Permissions We attempt to detect if you are publishing to a destination where you do not have control over page permissions and you’ll receive a warning. You may proceed with the publish, but any page you publish can be both viewed and edited by anyone with access to the space. If you delete a page on Confluence, and republish it from Quarto, you’ll see the error: ERROR: API Error: 404 - Not Found This occurs because Quarto stores and reuses the location of your page on Confluence in _publish.yml. If the page is deleted on Confluence, this location will no longer exist. To solve the problem, delete the corresponding entry in _publish.yml, and publish again. You’ll then be prompted to set the destination. You can read more about _publish.yml in the Publishing Settings section. Authoring Authoring for Confluence is very similar to authoring HTML documents and Quarto webpages. However, you should be aware of some key limitations as well as some features specific to Confluence publishing. Content Limitations The confluence-html format supports nearly all of the standard Quarto markdown content types, including tables, callouts, and cross references. However, there is currently no support for Citations, Videos, Diagrams, Tabsets, or Equations. In the future, we may add these features if there is a Confluence equivalent that can support the functionality. Links When creating links between pages in your Confluence Project, you can provide the source file as the link target (rather than the path to the Confluence page). You can also add hash identifiers (#) to the source file if you want to link to a particular section in the document. For example: [about](about.qmd) [about](about.qmd#section) Raw Confluence Blocks Raw Confluence blocks allow you to include content that should pass through Quarto unchanged and be interpreted directly by Confluence. For example, Confluence’s Storage Format includes specific tags for a task list. To include a Confluence task list in your document, use these tags inside a raw Confluence block: ```{=confluence} <ac:task-list> <ac:task> <ac:task-status>incomplete</ac:task-status> <ac:task-body>task list item</ac:task-body> </ac:task> </ac:task-list> ``` When published to Confluence this results in the following list: Website Limitations Confluence projects are a special type of website that don’t support the traditional Website features like Listings, Themes and Navigation (as these things are taken care of internally by Confluence). Confluence Limitations As discussed in Publishing Workflow edits to page content made in Confluence are overwritten when content is published from Quarto. This is also the case for any inline comments made on Confluence. Page level emojis and page level comments are preserved across publishes. Publishing Settings Once you have published to Confluence, you might be interested in understanding how to manage your publishing and account settings. _publish.yml The _publish.yml file is used to specify the publishing destination. This file is automatically created (or updated) whenever you execute the quarto publish command, and is located within the project or document directory. The service, id, and URL of the published content is specified in _publish.yml. For example: - source: project confluence: - id: "5f3abafe-68f9-4c1d-835b-9d668b892001" url: "https://myteam.atlassian.net/wiki/spaces/TEAMSPACE/pages/123456/Plan" The next time you publish the same document or project, the _publish.yml file will be used to provide account and space information so that you are not prompted for this information again. If you have an existing Confluence Space that you want to publish to, you should manually create a _publish.yml file that looks like the example above, but with the appropriate id and url values for your document. Account information is not stored in _publish.yml, so it is suitable for checking in to version control and being shared by multiple publishers. Account Management You can list and remove saved Confluence accounts using the quarto publish accounts command: $ quarto publish accounts ? Manage Publishing Accounts ❯ ✔ Confluence: [email protected] ✔ Netlify: [email protected] ❯ Use the arrow keys and spacebar to specify accounts you would like to remove. Press Enter to confirm the list of accounts you wish to remain available.
{ "lastmod": "2023-07-05T19:35:15.759Z", "loc": "https://quarto.org/docs/publishing/confluence.html", "source": "https://quarto.org/docs/publishing/confluence.html" }
Overview Journal article formats often require fine grained control of generated output as well as the ability to use Journal-specific commands and directives. This can be achieved for Quarto formats by providing custom Pandoc templates (LaTeX and/or HTML). Often these templates are a mix of Journal-specific LaTeX and standard directives required by Pandoc. This article describes how to create custom Journal templates that behave well with Pandoc and produce high-fidelity publisher ready output. Templates Quarto uses Pandoc templates to generate the rendered output from a markdown file. A Pandoc template is a mix of format specific content and variables. The variables will be replaced with their values from a rendered document. For example, the most basic template looks like: mytemplate.tex \documentclass{scrartcl} \begin{document} $body$ \end{document} In the above template, the $body$ variable will be replaced with the LaTeX that is generated from the body of the document. If the body text is Hello **world**! in Markdown, the value of $body$ will be Hello \textbf{world}!. By providing your own custom template used when rendering, you have complete control of the final output. You can provide this custom template to be used when rendering like this: format: pdf: template: mytemplate.tex For more complete information about template syntax, see Template syntax. Template Partials Replacing an entire template gives you complete control of the rendered output, but many features of Pandoc and Quarto depend upon code and variables that appear in the built in templates. If you replace the entire template and omit these variables, features will not work properly. It’s therefore recommended that you take one of two approaches when authoring templates: Selectively replace partials that exist within the master LaTeX or HTML template. Replace the entire LaTeX or HTML template, but then include partials provided with Quarto to ensure that your template takes advantage of all Pandoc and Quarto features. Below we’ll cover both of these approaches. Note that after reviewing this documentation you may also want to check out the source code of formats published on quarto-journals for additional examples. Replacing Partials For LaTeX / PDF and HTML output, Quarto provides built in templates that are composed of a set of ‘partial’ template files. For these formats, you may replace portions of Quarto’s built in template, allowing you to customize just a portion of the template without needing to replace the whole thing. A simple partial to provide custom handling of the document title in LaTeX looks like: title.tex \title{$title$} \author{$for(author)$$author$$sep$ \and $endfor$} \date{$date$} You provide this partial to Quarto like: format: pdf: template-partials: - title.tex When Quarto renders a document with a partial, it will use the built in template but replace a portion of the template with the provided partial. In the above case, the LaTeX title will be replaced with the implementation provided as the partial, while the rest of the built in template will be used. Note that the name of the partial files is important. You choose which portion of the template to replace by providing a partial with that name. You can see the list of partials available in HTML Partials and LaTeX Partials below. Including Partials In addition to replacing built in partials with your own, you may also choose to use built in partials when composing your own template. This allows you to create a template that takes advantage of the capabilities and options provided by Quarto and Pandoc without copying and maintaining the entire template code. For example, you can use the $pandoc.tex()$ partial to include pandoc configuration for text highlighting, tables, graphics, tight lists, citations, and header includes: my-template.tex \documentclass{scrartcl} $pandoc.tex()$ \begin{document} $body$ \end{document} This modular approach means that is easier to implement templates that: Include required elements of Pandoc templates Support general Pandoc features and options Provide only the minimal LaTeX or HTML rather than being required to provide all of it LaTeX Partials View the Quarto LaTeX template and partials source code here. Note that latex.template is a copy of the complete Pandoc template that the Quarto template and partials is based upon. template.tex The core LaTeX template which includes the basic document skeleton plus the following partials. This can’t be replaced as a partial, instead use the template option to provide your own template. doc-class.tex Contains the document class declaration and options. By default we provide the identical document class that Pandoc provides, implementing many features. If you override this (which will be common), you will need to either implement support for the document class options or be aware that those options (e.g. font-size, paper-size, classoption, etc…) will not be supported in your output. title.tex Provides configuration of document metadata for writing the title block. Note that in addition to these templates and partials, Quarto will also make normalized authors and affiliations data available to the template, making is easy to write custom title blocks against a standard schema. before-body.tex Implements the frontmatter, title page, and abstract. after-body.tex Provides a placeholder to attach content at the end of the body. toc.tex Creates the table of contents, list of figures, and list of tables. before-bib.tex Placed after the content of the document, but before the bibliography. By default contains nothing. (Placed here as a couple of templates seemed to have commands here, but I think we may be able to remove). biblio.tex Creates the bibliography. pandoc.tex This includes configuration for text highlighting, tables, graphics, tight lists, citations, and header includes. In general, this partial must always be included within your custom template. In some circumstances, you may know that certain capabilities will not be needed, so you this partial is further composed of the following partials, which could be used if sensible: tightlist.tex Provides the tight list command. tables.tex Provides configuration for the output of tables, table captioning, and footnotes within tables. graphics.tex Provides image scaling and placement configuration. citations.tex When using CSL references, provides configuration and commands for outputting the bibliography. See the full source code for the Quarto LaTeX template to see how these partials are invoked by default. HTML Partials View the Quarto html template and partials source code here. Note that html.template is a copy of the complete Pandoc template that the Quarto template and partials is based upon. Quarto’s HTML template is broken down into the following components: template.html The core HTML template which includes the basic document skeleton plus the following partials. This can’t be replaced as a partial, instead use the template option to provide your own template. metadata.html Populates basic document metadata into the HTML document head. More advanced metadata elements are not currently implemented within this template (e.g. social media, academic metadata) but are implemented as post processors. title-block.html Provides the title block for the document.  toc.html Provide the table of contents target for the document Revealjs Partials View the Quarto Revealjs template and partials source code here. Note that revealjs.template is a copy of the complete Pandoc template that the Quarto template and partials is based upon. template.html The core Revealjs templates which includes the basic presentation skeleton plus the following partials. This can’t be replaced as a partial, instead use the template option to provide your own template. title-slide.html HTML used for the presentation title slide. toc-slide.html HTML used for the presentation table of contents.
{ "lastmod": "2023-07-05T19:35:15.675Z", "loc": "https://quarto.org/docs/journals/templates.html", "source": "https://quarto.org/docs/journals/templates.html" }
Overview This article provide a guide to creating your own custom Journal formats. As a supplement to this guide we also recommend the following learning resources: The source code for the Journal article formats available from the quarto-journals GitHub organization. The GitHub template repository for creating new Journal formats. The code in the template repository is heavily annotated so creating a new repository using this template and experimenting with it is an excellent way to learn. Journal custom formats can be used just like normal Quarto formats (e.g. pdf and html): You can specify a custom format beneath the format key just like a built-in format. For example: ---- title: "My Document" format: acm-pdf: toc: true --- Custom formats all derive from one of the base formats, and include that base format as a suffix. Formats can also provide multiple variations that derive from distinct base formats. For example: ---- title: "My Document" toc: true format: acm-pdf: default acm-html: default --- Note that we moved the toc option to the top level since it is shared between both of the formats. Custom formats can also be used with the --to argument to quarto render. For example: Terminal quarto render document.qmd --to acm-pdf Quick Start Here we’ll describe how to create a simple Journal article format extension. We’ll use the quarto create command to do this. If you are using VS Code or RStudio you should execute quarto create within their respective integrated Terminal panes. To get started, execute quarto create extension journal within the parent directory where you’d like the format to be created: Terminal $ quarto create extension journal ? Extension Name › aps As shown above, you’ll be prompted for an extension name. Type aps (an acronym for a fictional academic association) and press Enter—the Journal format extension is then created: Creating extension at /Users/jjallaire/quarto/dev/aps: - Created README.md - Created template.qmd - Created _extensions/aps/aps.lua - Created _extensions/aps/styles.css - Created _extensions/aps/_extension.yml - Created _extensions/aps/header.tex - Created bibliography.bib If you are running within VS Code or RStudio a new window will open with the extension project. Here’s what the contents of the files in _extensions/aps/ look like: _extensions/aps/_extension.yml title: Aps author: J.J. Allaire version: 1.0.0 quarto-required: ">=1.2.222" contributes: formats: common: toc: true filters: - aps.lua pdf: include-in-header: header.tex html: css: styles.css The main _extension.yml config file defines the output formats available for this Journal. Here we defined pdf and html formats, which will be available to Quarto documents as aps-pdf and aps-html, respectively. The config file also points to a number of other files that are used to customize the appearance of the Journal article: header.tex — Custom LaTeX header directives styles.css — Custom CSS for HTML output aps.lua — Lua filter for various custom transformations Finally, the template.qmd provides a base example article for users of the format: template.qmd --- title: Aps Template format: aps-pdf: keep-tex: true aps-html: default author: - name: Sarah Malloc affiliations: - name: An Organization department: The Department address: 1 Main St city: Boston country: USA postal-code: 02210-1022 - A second affilication orcid: 0000-0000-0000-0000 email: [email protected] url: https://example.org/ - name: Eliza Dealloc affiliations: - Another Affiliation abstract: | This document is a template demonstrating the Aps format. keywords: [template, demo] bibliography: bibliography.bib --- ## Introduction {#sec-intro} *TODO* Create a template that demonstrates the appearance, formatting, layout, and functionality of your format. Learn more about journal formats at <https://quarto.org/docs/journals/>. To develop your format, render/preview template.qmd, and then make changes to the various files in the _extensions directory (the preview will automatically refresh when you change these files). Example: ACM Format The Quick Start above creates a very simple Journal article format. Here we’ll walk through some of the code for a more complex example, the ACM Format available from quarto-journals. Before proceeding to the example we recommend you review these articles which cover some foundations that will be made use of in the example: Article Templates Authors & Affiliations Format Components Here is what the source code repository for the ACM extension looks like: .gitignore .quartoignore LICENSE README.md bibliography.bib template.qmd _extensions/ acm/ _extension.yml acm_proc_article-sp.cls sensys-abstract.cls include-in-header.tex acm-sig-proceedings.csl partials/ doc-class.tex title.tex before-bib.tex For the time being we’ll ignore all of the files above the _extensions directory (those files aren’t strictly part of the extension but rather provide documentation and a starter template—we’ll describe their usage below). The _extensions directory contains one or more extension—in this case it contains the acm format extension. The _extension.yml file declares the format extension and provides default metadata and options for articles created for the format (we’ll do a deep dive into its contents below). The acm_proc_article-sp.cls and sensys-abstract.cls files are LaTeX class files used by the ACM. The include-in-header.tex file provides some standard content included in the preamble of ACM articles. The acm-sig-proceedings.csl is a Citation Style Language (CSL) file that enables rendering of citations and bibliographies according to the standards of the ACM. The partials directory contains some .tex files that override various parts of the standard Pandoc LaTeX template (see Article Templates to learn more about partials). Here’s what the contents of _extension.yml look like: title: ACM Journal Format author: Charles Teague version: 0.1.0 quarto-required: ">=1.2.0" contributes: format: common: csl: acm-sig-proceedings.csl number-sections: true pdf: shift-heading-level-by: -1 template-partials: - partials/before-bib.tex - partials/doc-class.tex - partials/title.tex include-in-header: - include-in-header.tex As you can see, many of the files located in the _extensions/acm folder are referenced here. Also note that while there are several options declared for the pdf format, there are also some options declared in common—these options will be applied to pdf and will also be applied to other format variants (e.g. HTML) when they are developed. Format Template Now let’s return to the files outside of the _extensions directory. The LICENSE and README.md files provide documentation that is good form to include in all extensions. The .gitignore files masks selected files out of version control. The remainder of the files provide a format template that make it easier for users to get started with your format. For any custom format that includes a template.qmd, users can get started with the format with a command like this: Terminal quarto use template quarto-journals/acm The files included within the ACM template are: template.qmd is a starter template for using the format. Here’s what the YAML document options for the template look like: --- title: Short Paper author: - name: Alice Anonymous email: [email protected] affiliation: Some Institute of Technology - name: Bob Security email: [email protected] affiliation: Another University abstract: | This is the abstract. It consists of two paragraphs. format: acm-pdf: keep-tex: true bibliography: bibliography.bib --- bibliography.bib is a sample bibliography referenced by template.qmd Note that the schema for author information used here is relatively straightforward. See the article on Authors & Affiliations to learn about more sophisticated schemas for author information. You can also include other files alongside template.qmd and they will be copied as well. Note that by default, Quarto will exclude common Github repository files when copying an extension template. This includes any file name or directory starting with a . (e.g. .gitignore), README.md, LICENSE, etc.. If you’d like, you can place a .quartoignore file in the root of your repository with each line of the file being a glob describing file(s) to ignore (using syntax like a .gitignore file). Distributing Formats You can distribute format extensions in one of two ways: As a template that includes both the format in the _extensions directory and the template.qmd (which is automatically renamed to match the name of the enclosing directory). As a plain format with no template scaffolding (this is useful for adding the format to an existing document or project). If you have a GitHub repository containing the files enumerated above in the acm example, users could install your extension and associated template as follows (where quarto-journals is the GitHub organization hosting the repo): Terminal quarto use template quarto-journals/acm This is often the preferred way to get started with a format as it provides the user with a working document right out of the box. It’s also possible to install only the format if you working with an existing project: Terminal quarto add quarto-journals/acm Note that it is possible to bundle and distribute extensions as simple gzip archives (as opposed to using a GitHub repository as described above). See the article on Distributing Extensions for additional details. Common Metadata If you have metadata that is common to any output format when your format extension is targeted, you can place that metadata under the common key. For example: contributes: format: common: filters: - filter.lua shortcodes: - quarto-ext/fancy-text html: # html-specifc pdf: # pdf-specifc Format Resources You can usually include other files and resources within a format extension by placing those files within the extension directory and using relative paths to reference them in your _extension.yml metadata file. These relative paths will be properly handled as your extension’s metadata is merged with the rendered document metadata. If there are resources that you need to have copied to the input directory as a part of rendering the document (for example, a bst file for LaTeX bibliographies or a logo or other file referenced from a LaTeX template), you can provide format-resources, which is a list of file paths1. Each of these files will be copied into the directory containing the input that is being rendered when the document is rendered. For example: contributes: format: pdf: format-resources: - plos2015.bst Extension Embedding In some cases format extensions will want to make use of other extensions. This is permitted, but adding extensions for use within a custom format must be done with a special command line flag to ensure they are embedded correctly. For example, here we want to make the fancy-text extension (which provides special formatting for the words \(\LaTeX\) and BibTEX) available for users of the jss custom format: Terminal quarto add quarto-ext/fancy-text --embed quarto-journals/jss This will add the quarto-ext/fancy-text extension into the quarto-journals/jss extension in the _extensions folder. By embedding an extension you make it available without creating the potential for conflict with other versions of the extension that uses might already have installed. Learning More Here are some additional learning resources you may find valuable: The source code for the Journal article formats available from the quarto-journals GitHub organization. The GitHub template repository for creating new Journal formats. The code in the template repository is heavily annotated so creating a new repository using this template and experimenting with it is an excellent way to learn. In depth treatment of creating Article Templates for Journals (including how to use partials to compose templates) Review of the schema and options for expressing and rendering Authors & Affiliations. Footnotes This is most common in the the case of PDF based formats which have a secondary step of converting the LaTeX produced by Pandoc into a PDF. If there are files that are referenced indirectly by the LaTeX, they will need to be discoverable and should typically be copied into the same directory that contains the LaTeX input.↩︎
{ "lastmod": "2023-07-05T19:35:15.675Z", "loc": "https://quarto.org/docs/journals/formats.html", "source": "https://quarto.org/docs/journals/formats.html" }
Overview Quarto can render Jupyter notebooks represented as plain text (.qmd) or as a normal notebook file (.ipynb). The Quarto VS Code Extension includes many tools that enhance working these documents, including: Integrated render and preview for Quarto documents. Syntax highlighting for markdown and embedded languages Completion and diagnostics for YAML options Completion for embedded languages (e.g. Python, R, Julia, etc.) Commands and key-bindings for running cells and selected lines. Live preview for LaTeX math as well as Mermaid and Graphviz diagrams The Quarto extension integrates directly with the Jupyter, R, and Julia extensions. For example, here the Quarto extension runs a Python cell and shows contextual help for Python functions: You can install the Quarto extension from the VS Code Extension Marketplace or the Open VSX Registry. VS Code Editors Depending on your preference and the task at hand, you can author documents for rendering by Quarto using three different editors within VS Code: The source code editor for editing .qmd documents as text. The Visual Editor for WYSIWYG editing of .qmd documents. The Notebook Editor for editing .ipynb notebooks. We’ll cover the the source code editor below, however you might also want to consult the documentation for the Visual Editor or Notebook Editor after you’ve become familar with the basics. Render and Preview The Quarto VS Code extension includes commands and keyboard shortcuts for rendering Quarto documents (both standalone and within websites or books). After rendering, quarto preview is used behind the scenes to provide a preview pane within VS Code alongside your document: To render and preview, execute the Quarto: Render command. You can alternatively use the Ctrl+Shift+K keyboard shortcut, or the Render button at the top right of the editor: Note that on the Mac you should use Cmd rather than Ctrl as the prefix for all Quarto keyboard shortcuts. Additionally, there are commands available to render specific formats. Here is a complete list of the supported render commands: Quarto: Render Quarto: Render HTML Quarto: Render PDF Quarto: Render DOCX The Quarto: Render command renders the default format of the currently active document. The other commands render specific formats (regardless of the document’s default format). The Ctrl+Shift+K keyboard shortcut will re-execute the most recently executed render command. Embedded preview is currently supported for HTML and PDF based formats (including revealjs and beamer slideshows). However, for Word and other formats you need to use an appropriate external program to preview the output. Render on Save 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. However, you can configure the Quarto extension to automatically render whenever you save. You can do this either within VS Code settings or within the YAML options for your project or document. To configure the VS Code setting, search for quarto.render in settings and you’ll find the Render on Save option: 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: editor: render-on-save: true External Preview If you prefer to use an external browser for preview (or have no preview triggered at all by rendering) you can use the Preview Type option to specify an alternate behavior: Code Cells There are a variety of tools that make it easier to edit and execute code cells. Editing tools include syntax highlighting, code folding, code completion, and signature tips: For Python, R, and Julia cells, commands are available to execute the current cell, previous cells, or the currently selected line(s). Cell output is shown side by side in the Jupyter interactive console: Here are all of the commands and keyboard shortcuts available for executing cells: Quarto Command Keyboard Shortcut Run Current Cell ⇧⌘ Enter Run Selected Line(s) ⌘ Enter Run Next Cell ⌥⌘ N Run Previous Cell ⌥⌘ P Run All Cells ⌥⌘ R Run Cells Above ⇧⌥⌘ P Run Cells Below ⇧⌥⌘ N You can quickly insert a new code cell using the Ctrl+Shift+I keyboard shortcut. Enhanced features for embedded languages (e.g. completion, code execution) can be enabled by installing the most recent version(s) of these extensions: Python Extension R Extension Julia Extension Execution Directory Embedded language extensions handle the working directory for execution in distinct ways: The Python Extension runs code within the directory of the source file from which code is executed. You can customize this behavior using the jupyter.notebookFileRoot option. The R Extension runs code within the working directory of the R session running in the R Interactive terminal. You can change this directory manually using setwd(). The Julia Extension runs code within the working directory of the Julia session running in the Julia REPL terminal. You can change this direcdtory manually using cd(). Contextual Assistance Execute the Quarto: Show Assist Panel command to show a panel in the sidebar that shows contextual assistance depending on the current cursor location: Help/documentation is shown when editing code A realtime preview of equations is shown when editing LaTeX math Thumbnail previews are shown when your cursor is located on a markdown image. For example, below help on the matplotlib plot() function is shown automatically when the cursor is located on the function: Live Preview While editing LaTeX math or Mermaid and Graphviz diagrams, click the Preview button above the code (or use the Ctrl+Shift+L keyboard shortcut) to open a live preview which will update automatically as you edit. Here we see a preview of the currently edited LaTeX equation displayed in the Quarto assist panel: Here we see a Graphviz diagram preview automatically updated as we edit: YAML Intelligence YAML code completion is available for project files, YAML front matter, and executable cell options: If you have incorrect YAML it will also be highlighted when documents are saved: Code Snippets Code snippets are templates that make it easier to enter repeating code patterns (e.g. code blocks, callouts, divs, etc.). Execute the Insert Snippet command within a Quarto document to insert a markdown snippet: IntelliSense VSCode uses IntelliSense to suggest snippets or possible values for a specific function while typing. This is turned off by default for snippets, but not for values. To enable snippet suggestions in IntelliSense while typing or when selecting a text snippet and pressing ctrl+space, the setting editor.snippetSuggestions needs to be set to a value other than none (for example to inline). Press F1 and search for Preferences: Open Settings (UI) or File > Preferences > Settings Search for following term @lang:quarto editor.snippetSuggestions. Editor: Snippet Suggestions should show up. Change value to a not-none value. Document Navigation If you have a large document use the outline view for quick navigation between sections: You can also use the Go to Symbol in Editor command or keyboard shortcut Ctrl+Shift+O for type-ahead navigation of the current document’s outline. Use the Go to File command Ctrl+P to navigate to other files and the Go to Symbol in Workspace command Ctrl+T for type-ahead navigation to all headings in the workspace: Learning More Besides the traditional source editor described above, you can also use one of the following other editors depending on your preferences and task at hand: The Visual Editor for WYSIWYG editing of .qmd documents. The Notebook Editor for editing .ipynb notebooks.
{ "lastmod": "2023-07-05T19:35:15.859Z", "loc": "https://quarto.org/docs/tools/vscode.html", "source": "https://quarto.org/docs/tools/vscode.html" }
Overview RStudio v2022.07 and later includes support for editing and preview of Quarto documents (the documentation below assumes you are using this build or a later version). If you are using Quarto within RStudio it is strongly recommended that you use the latest release of RStudio (v2023.03). You can download RStudio v2023.03 from https://posit.co/download/rstudio-desktop/. Creating Documents Use the File : New File : Quarto Document… command to create new Quarto documents: Render and Preview Use the Render button to preview documents as you edit them: If you prefer to automatically render whenever you save you can check the Render on Save option on the editor toolbar. The preview will appear alongside the editor: The preview will update whenever you re-render the document. Side-by-side preview works for both HTML and PDF output. Projects If you want to create a new project for a Quarto document or set of documents, use the File : New Project… command, specify New Directory, then choose Quarto Project: You can use this UI to create both vanilla projects as well as websites and books. Options are also provided for creating a git repository and initializing an renv environment for the project. Visual Editor RStudio IDE includes a visual editor for Quarto markdown, including support for tables, citations, cross-references, footnotes, divs/spans, definition lists, attributes, raw HTML/TeX, and more: To learn more, see the documentation on Using the Visual Editor with RStudio. Knitr Engine Quarto is designed to be highly compatible with existing R Markdown documents. You should generally be able to use Quarto to render any existing Rmd document without changes. One important difference between R Markdown documents and Quarto documents is that in Quarto chunk options are typically included in special comments at the top of code chunks rather than within the line that begins the chunk. For example: ```{r} #| echo: false #| fig-cap: "Air Quality" library(ggplot2) ggplot(airquality, aes(Temp, Ozone)) + geom_point() + geom_smooth(method = "loess", se = FALSE) ``` Quarto uses this approach to both better accommodate longer options like fig-cap, fig-subcap, and fig-alt as well as to make it straightforward to edit chunk options within more structured editors that don’t have an easy way to edit chunk metadata (e.g. most traditional notebook UIs). Note Note that if you prefer it is still possible to include chunk options on the first line (e.g. ```{r, echo = FALSE}). That said, we recommend using the comment-based syntax to make documents more portable and consistent across execution engines. Chunk options included this way use YAML syntax rather than R syntax for consistency with options provided in YAML front matter. You can still however use R code for option values by prefacing them with !expr. For example: #| fig-cap: !expr 'paste("Air", "Quality")' Caution the !expr syntax is an example of a YAML “tag” literal, and it can be unintuitive. !expr needs to be followed by a single YAML “flow scalar”: see the YAML spec for details on how double-quoted, single-quoted, and unquoted strings work. Jupyter Engine You can also work with Quarto markdown documents that target the Jupyter engine within RStudio. These files will typically include a jupyter option in the YAML front matter indicating which kernel to use. For example: --- title: "Matplotlib Demo" author: "Norah Smith" jupyter: python3 --- If you want to work within a virtual environment (venv), use the File : New Project… command, specify the Jupyter engine with a venv, and specify which packages you’d like to seed the venv with: RStudio will automatically activate this virtual environment whenever you open the project. You can install additional Python packages into the environment using the RStudio Terminal tab. For example: YAML Intelligence YAML code completion is available for project files, YAML front matter, and executable cell options: If you have incorrect YAML it will also be highlighted when documents are saved: R Package If you are not using RStudio and/or you prefer to render from the R console, you can do so using the quarto R package. To install the R package: install.packages("quarto") Then, to render a document: library(quarto) quarto_render("document.qmd") To render a website (ie; all qmd in a directory organized as a website): library(quarto) quarto_render() To live preview (automatically render & refresh the browser on save) for a document you are working on, use the quarto_preview() function: library(quarto) quarto_preview("document.qmd") If you are working on a website or book project, you can also use quarto_preview() on a project directory: library(quarto) quarto_preview()
{ "lastmod": "2023-07-05T19:35:15.859Z", "loc": "https://quarto.org/docs/tools/rstudio.html", "source": "https://quarto.org/docs/tools/rstudio.html" }
Overview The Quarto JuptyerLab extension enables JupyterLab Notebooks which use Quarto markdown to properly display the contents of the markdown cells. For example, when the Quarto JupyterLab extension is installed, your Notebook will show rendered previews of elements like Callouts, Divs, Mermaid charts, as well as other Quarto elements (including the document front matter as a title block). Installing the Extension You can install the Quarto JupyterLab extension one of two ways: Using pip, you can install the jupyterlab-quarto by executing: Platform Commands Mac/Linux Terminal python3 -m pip install jupyterlab-quarto Windows Terminal py -m pip install jupyterlab-quarto This is the preferred way to install the JupyterLab Quarto extension as this takes advantage of traditional python packaging and doesn’t require a rebuild of JupyterLab to complete the installation. In the JupyterLab UI, you can install the Quarto extension directly using the Extension Manager by searching for ‘Quarto’ and installing the @quarto/jupyterlab-quarto extension. To complete the installation you need to rebuild JupyterLab (you should see a prompt to complete this once you’ve installed the Quarto extension). Using the Extension The Quarto extension, once installed, will automatically render the contents of markdown cells within your notebook. Cells without Quarto specific markdown will render normally, while cells containing Quarto specific markdown will show a preview of the content in a more usable form. Note The Quarto contents shown in your Notebooks will not match the rendered output precisely. For example, callouts shown in the Notebook don’t change their display based upon callout options you specify in your markdown. Disabling the Extension If you installed the Quarto JupyterLab extension using pip, you can use the following commands to disable and enable the extension. To disable extension, use the following command: Platform Commands Mac/Linux Terminal python3 -m jupyter labextension disable jupyterlab-quarto Windows Terminal py -m jupyter labextension disable jupyterlab-quarto To enable the extension, use the following command: Platform Commands Mac/Linux Terminal python3 -m jupyter labextension enable jupyterlab-quarto Windows Terminal py -m jupyter labextension enable jupyterlab-quarto If you installed the Quarto JupyterLab extension using the JupyterLab Notebook Extension Manager, you can use the UI directly to disable and enable the extension. Uninstalling the Extension If you installed the extension using pip, you can uninstall the Quarto extension using pip, like so: Platform Commands Mac/Linux Terminal python3 -m pip uninstall jupyterlab-quarto Windows Terminal py -m pip uninstall jupyterlab-quarto If you installed the extension using the JupyterLab Notebook Extension Manager, use the Extension Manager to uninstall the extension. To complete the uninstallation you need to rebuild JupyterLab (you should see a prompt to complete this once you’ve uninstalled the Quarto extension). Reporting Issues Please report issues with the Quarto JuptyerLab extension here.
{ "lastmod": "2023-07-05T19:35:15.859Z", "loc": "https://quarto.org/docs/tools/jupyter-lab-extension.html", "source": "https://quarto.org/docs/tools/jupyter-lab-extension.html" }
Shortcuts Visual mode supports both traditional keyboard shortcuts (e.g. ⌘ B for bold) as well as markdown shortcuts (using markdown syntax directly). For example, enclose **bold** text in asterisks or type ## and press space to create a second level heading. Here are the available keyboard and markdown shortcuts: Command Keyboard Shortcut Markdown Shortcut Bold ⌘ B **bold** Italic ⌘ I *italic* Code ⌘ D `code` Strikeout ~~strike~~ Subscript ~sub~ Superscript ^super^ Heading 1 ⌥⌘ 1 # Heading 2 ⌥⌘ 2 ## Heading 3 ⌥⌘ 3 ### Heading Attributes {#id .class} Link ⌘ K <href> Blockquote > Code Block ⇧⌘ \ ``` R Code Chunk ⌥⌘ I ```{r} Raw Block ```{=html} Div ::: Bullet List - Ordered List 1. Tight List ⌥⌘ 9 List Check [x] Emoji :smile: Definition : Non-Breaking Space ⌃ Space Hard Line Break ⇧ Enter Paragraph ⌥⌘ 0 Image ⇧⌘ I Footnote ⇧⌘ F7 Citation ⇧⌘ F8 [@ Table ⌥⌘ T Editing Comment ⇧⌘ C Select All ⌘ A Clear Formatting ⌘ \ Edit Attributes F4 Run Code Chunk ⇧⌘ Enter Run Previous Chunks ⇧⌥⌘ P For markdown shortcuts, if you didn’t intend to use a shortcut and want to reverse its effect, just press the backspace key. Insert Anything You can also use the catch-all ⌘ / shortcut to insert just about anything. Just execute the shortcut then type what you want to insert. For example: If you are at the beginning of a line (as displayed above) you can also enter plain / to invoke the shortcut. Global Options You can customize visual editing options within R Markdown -> Visual (note that the visual editor was originally created for use with R Markdown so its options are located there — these options are also applicable to usage with Quarto): Option Description Use visual editing by default Switch to visual mode immediately when creating new documents. Show document outline by default Show the navigational outline when opening documents in visual mode. Editor content width Maximum width for editing content. This is intended to keep editing similar to the width that users will see. Editor font size Base font size for editor content (default: inherit from IDE settings). Show margin column indicator in code blocks Show vertical line that indicates location of editing margin column (e.g. 80). Default spacing between list items Whether to use tight or normal spacing between list items by default. See Tight Lists for details. Automatic text wrapping (line breaks) When writing markdown, automatically insert line breaks after sentences or at a specified column (default: flow text; no auto-wrapping). See Line Wrapping for details. Write references at end of current Write references (footnotes) at the end of the block or section where they appear, or at the end of the document. See References for details. Write canonical visual mode markdown in source mode Use the visual mode markdown writer when saving markdown from source mode (ensure consistency between documents saved from either mode). Citation Options You can customize visual editor citation options within R Markdown -> Citations: Option Description Zotero Library Location of Zotero citation library (Local or Web). Zotero Data Directory Location of Zotero local data directory. Use libraries Zotero libraries to use as reference sources. Use Better BibTeX for citation keys and BibTeX export. Optionally use Better BibTeX to generate citation keys and export BibTeX from Zotero (this option appears only if Better BibTeX is installed). Project Options Global options that affect the way markdown is written can also be customized on a per-project basis. You can do this using the R Markdown pane of the Project Options dialog: By default projects inherit the current global settings for markdown writing and Zotero libraries. File Options Global and project options that affect the way markdown is written can also be customized on a per-file basis . You can do this by including an editor: markdown key in the YAML front matter of your document. For example: --- title: "My Document" author: "Jane Doe" editor: markdown: wrap: 72 --- You might want to do this to ensure that multiple authors on different workstations use the same markdown writing options. You can also instruct RStudio to use these same options when saving files from source mode. To do this add the canonical option. For example: --- editor: markdown: wrap: 72 canonical: true --- With canonical: true, edits in visual mode and source mode will result in identical markdown output. This is especially useful if you have multiple authors collaborating using version control, with a mixture of source and visual mode editing among the authors. See the documentation on Writer Options for additional details on markdown writing options.
{ "lastmod": "2023-07-05T19:35:15.975Z", "loc": "https://quarto.org/docs/visual-editor/options.html", "source": "https://quarto.org/docs/visual-editor/options.html" }
Overview The Quarto visual editor generates markdown using Pandoc. This means that in some cases your markdown will be rewritten to conform to standard Pandoc idioms. For example, Pandoc inserts 3 spaces after list bullets and automatically escapes characters that might be used for markdown syntax. Here is a list of conventions for Pandoc generated markdown that might differ from your own markdown writing style: *text* is used in preference to _text_ Backtick code blocks are written as ``` {.md} rather than ```md Backtick code blocks with no attributes are rendered as 4-space indented code blocks Horizontal rules are written as dashes spanning the full width of the document Plain links are written as <https://yihui.org> rather than https://yihui.org Bullet and numbered lists use additional leading spaces before list item content The blockquote character (>) is included on each new line of a blockquote Table captions are written below rather than above tables Multiline HTML and TeX blocks use the explicit raw attribute (e.g. ```{=tex}) Inline footnotes are replaced with footnotes immediately below the paragraph Nested divs use ::: at all levels so long as their attributes are distinct Unnumbered sections are designated with {.unnumbered} rather than {-} Characters used for markdown syntax (e.g. *, _, or #) are always escaped While some of this behavior might be bothersome at first, if you decide that visual editing mode is useful for your workflow it’s probably best to just adapt to writing your own markdown the same way that Pandoc does. Note that you can also configure source mode to write markdown using these conventions, ensuring that the same markdown is written no matter which mode edits originate from. Writer Options Some aspects of markdown output can be customized via global, project, or file-level options, including: How to wrap / break lines (fixed column, sentence-per-line, etc.). Where to write footnotes (below the current paragraph or section, or at the end of the document). Whether to use the visual mode markdown writer when saving markdown from source mode (to ensure consistency between documents saved from either mode). You can set these options within the R Markdown Global Options or Project Options, or can alternatively set them on a per-file basis using YAML (as described below). Line Wrapping By default, the visual editor writes Markdown with no line wrapping (paragraphs all occupy a single line). This matches the behavior of markdown source editing mode within RStudio. However, if you prefer to insert line breaks at a particular column (e.g. 72 or 80), or to insert a line break after each sentence, you can set a global or per-project editor option to this effect. You can also set this behavior on a per-document basis via the wrap option. For example, to wrap lines after 72 characters you would use this: --- editor: markdown: wrap: 72 --- To insert a line break after each sentence, use wrap: sentence. For example: --- editor: markdown: wrap: sentence --- The algorithm used for sentence wrapping will handle English and Japanese text well, but may not detect the end of sentences accurately for other languages. If you have enabled a global line wrapping option and want to turn off wrapping for a given document, use wrap: none. References By default, references are written at the end of the block where their corresponding footnote appears. You can override this behavior using the references option. For example, to write references at the end of sections rather than blocks you would use: --- title: "My Document" editor: markdown: references: location: block --- Valid values for the references option are block, section, and document. Note that you can also set a global or per-project editor option to control reference writing behavior. If you are aggregating a set of markdown documents into a larger work, you may want to make sure that reference identifiers are unique across all of your documents (e.g. you don’t want to have [^1] appear multiple times). You can ensure uniqueness via the prefix option. For example: --- title: "My Document" editor: markdown: references: location: block prefix: "mydoc" --- This will result in footnotes in this document using the specified prefix (e.g. [^mydoc-1]), ensuring they are globally unique across the manuscript. Note that if you are within a Quarto book project then a references prefix is applied automatically so no changes to editor: markdown are required. Canonical Mode If you have a workflow that involves editing in both visual and source mode, you may want to ensure that the same markdown is written no matter which mode edits originate from. You can accomplish this using the canonical option. For example: --- title: "My Document" editor: markdown: wrap: 72 references: location: block canonical: true --- With canonical: true, edits in visual mode and source mode will result in identical markdown output. This is especially useful if you have multiple authors collaborating using version control, with a mixture of source and visual mode editing among the authors. Known Limitations There are a handful of Pandoc markdown extensions not currently supported by visual editing. These are infrequently used extensions, so in all likelihood they won’t affect documents you edit, but are still worth noting. Extension(s) Example Behavior Inline footnotes ^[inline] Converted to numeric footnote. Footnote identifiers [^longnote] Converted to numeric footnote. Example lists (@) First example Read/written as ordinary numbered lists. Auto-list numbers #. First item Read/written as ordinary numbered lists. Reference links This is a [link] Converted to ordinary links. MultiMarkdown attributes # Heading [id] Converted to Pandoc attributes. The visual editor is unable to parse non-YAML title blocks (e.g. old-style % titles or MultiMarkdown titles) and also unable to parse non top-level YAML metadata blocks. If these forms of metadata are encountered, visual mode will fail to load with a warning.
{ "lastmod": "2023-07-05T19:35:15.975Z", "loc": "https://quarto.org/docs/visual-editor/markdown.html", "source": "https://quarto.org/docs/visual-editor/markdown.html" }
Overview The Quarto VS Code Extension includes a visual markdown editor that supports all of Quarto’s markdown syntax including tables, citations, cross-references, footnotes, divs/spans, definition lists, attributes, raw HTML/TeX, and more: You can switch between visual and source mode at any time and can even edit documents concurrently in both modes. To switch between visual and source mode: Use the ⇧⌘ F4 keyboard shortcut. Use the context menu from anywhere in a document: Use the Edit in Visual Mode and Edit in Source Mode commands: Use the editor menu: You can also right click a .qmd document in the file explorer and select the Open With… command, which will prompt you for the editor to open the file with: Note that this menu also provides an option to configure the default editor for .qmd files: use this if you want to primarily edit in visual mode and occasionally switch to source mode. Keyboard Shortcuts Visual mode supports both traditional keyboard shortcuts (e.g. ⌘ B for bold) as well as markdown shortcuts (using markdown syntax directly). For example, enclose **bold** text in asterisks or type ## and press space to create a second level heading. Here are the available keyboard and markdown shortcuts: Command Keyboard Shortcut Markdown Shortcut Bold ⌘ B **bold** Italic ⌘ I *italic* Code ⌘ D `code` Strikeout ~~strike~~ Subscript ~sub~ Superscript ^super^ Heading 1 ⌥⌘ 1 # Heading 2 ⌥⌘ 2 ## Heading 3 ⌥⌘ 3 ### Heading Attributes {#id .class} Link ⌘ K <href> Blockquote > Code Block ⇧⌘ \ ``` Code Cell ⌥⌘ I ```{python} Raw Block ```{=html} Div ::: Bullet List - Ordered List 1. Tight List ⌥⌘ 9 List Check [x] Emoji :smile: Definition : Non-Breaking Space ⌃ Space Hard Line Break ⇧ Enter Paragraph ⌥⌘ 0 Image ⇧⌘ I Footnote ⇧⌘ F7 Citation ⇧⌘ F8 [@ Table ⌥⌘ T Editing Comment ⇧⌘ C Select All ⌘ A Clear Formatting ⌘ \ Edit Attributes F4 For markdown shortcuts, if you didn’t intend to use a shortcut and want to reverse its effect, just press the backspace key. Insert Anything You can also use the catch-all ⌘ / shortcut to insert just about anything. Just execute the shortcut then type what you want to insert. For example: If you are at the beginning of a line (as displayed above), you can also enter plain / to invoke the shortcut. Editor Toolbar The editor toolbar includes buttons for the most commonly used formatting commands: Additional commands are available on the Format, Insert, and Table menus: Format Insert Table Editor Options There are a variety of VS Code options available to configure the behavior of the visual editor. You can location these options by filtering on quarto.visualEditor in the settings pane: Options enable configuration of appearance (font size, content width, etc.), markdown output (e.g. column wrapping), spell checking, and default spacing for lists. Zotero Citations Zotero is a popular free and open source reference manager. The Quarto visual editor integrates directly with Zotero, enabling you to use the Insert Citation command to use references from your Zotero libraries: Zotero references will also show up automatically in visual editor completions: Items from Zotero will appear alongside items from your bibliography with a small “Z” logo juxtaposed over them. If you insert a citation from Zotero that isn’t already in your bibliography then it will be automatically added to the bibliography. If you are running both VS Code and Zotero on your desktop, then no additional configuration is required for connecting to your Zotero library. If however you using VS Code in a web browser and/or want to access your Zotero library over the web, then a few more steps are required (see the Zotero Web API section for details). Group Libraries Zotero Groups provide a powerful way to share collections with a class or work closely with colleagues on a project. By default, Zotero Group Libraries are not included in the Insert Citation dialog or citation completions. However, you can use the Quarto > Zotero: Group Libraries option to activate one or more group libraries (either globally, or per-workspace): After you’ve added a group library to the list, a sync will be performed and you should see the library in the Insert Citation dialog. If you don’t, double check the exact spelling of the group library name you are configuring (you may even want to copy and paste it from Zotero so you are certain to get it right). Zotero Web API If you are using VS Code in a web browser and/or don’t have Zotero installed locally, you can still access your Zotero library using the Zotero Web API (assuming you have a Zotero web account and have synced your libraries to your account). If you are running VS Code on your desktop it’s generally easier to also run Zotero on your desktop and access your library locally. That said, it is possible to access Zotero web libraries from VS Code on the desktop if you prefer that configuration. API Access Key Zotero integration uses the Zotero Web API, so the first step is to create a Zotero account and then configure Zotero to sync its data to your account. You can do this using the Sync tab of the Zotero preferences: Once you’ve configured your library to sync, you need to create a Zotero API Key: Follow the instructions to create a new access key. Note that if you want to use Group Libraries, you should change the default to provide read-only access to groups (as illustrated above). Be sure to record your key after generating it (i.e. copy it to the clipboard and/or save it somewhere more permanent) as you won’t be able to view it again after you navigate away. Library Configuration Finally, go to Zotero settings and specify that you’d like to use your web Zotero library rather than a local one: You’ll then be promoted to enter your Zotero Web API Key: After you provide your API key and it is validated, an initial sync of your Zotero libraries is performed. After this, you are ready to start inserting citations from Zotero. Note If you need to change your Zotero API key, you can always execute the Quarto: Zotero - Connect Web Library command. To force a sync of your web library, execute the Quarto: Zotero - Sync Web Library command (note that your web library is synced automatically so it is unlikely you’ll need to use this command explicitly). Markdown Output The Quarto visual editor generates markdown using Pandoc. This means that in some cases your markdown will be rewritten to conform to standard Pandoc idioms. For example, Pandoc inserts 3 spaces after list bullets and automatically escapes characters that might be used for markdown syntax. Here is a list of conventions for Pandoc generated markdown that might differ from your own markdown writing style: *text* is used in preference to _text_ Backtick code blocks are written as ``` {.md} rather than ```md Backtick code blocks with no attributes are rendered as 4-space indented code blocks Horizontal rules are written as dashes spanning the full width of the document Plain links are written as <https://yihui.org> rather than https://yihui.org Bullet and numbered lists use additional leading spaces before list item content The blockquote character (>) is included on each new line of a blockquote Table captions are written below rather than above tables Multiline HTML and TeX blocks use the explicit raw attribute (e.g. ```{=tex}) Inline footnotes are replaced with footnotes immediately below the paragraph Nested divs use ::: at all levels so long as their attributes are distinct Unnumbered sections are designated with {.unnumbered} rather than {-} Characters used for markdown syntax (e.g. *, _, or #) are always escaped While some of this behavior might be bothersome at first, if you decide that visual editing mode is useful for your workflow it’s probably best to just adapt to writing your own markdown the same way that Pandoc does. Writer Options Some aspects of markdown output can be customized via global, project, or file-level options, including: How to wrap / break lines (fixed column, sentence-per-line, etc.). Where to write footnotes (below the current paragraph or section, or at the end of the document). Wheter to write inline or reference style links. You can specify these options in one of two ways: As a global or per-workspace VS Code option (you can find the options that affect markdown output by filtering on quarto.visualEditor.markdown). Specifying them within document or project level YAML (described below). Line Wrapping By default, the visual editor writes Markdown with no line wrapping (paragraphs all occupy a single line). However, if you prefer to insert line breaks at a particular column (e.g. 72 or 80), or to insert a line break after each sentence, you can use the quarto.visualEditor.markdownWrap and quarto.visualEditor.markdownWrapColumn options accessible from the settings editor in VS Code. You can also set this behavior on a per-document or per-project basis via the wrap option. For example, to wrap lines after 72 characters you would use this: --- editor: markdown: wrap: 72 --- To insert a line break after each sentence, use wrap: sentence. For example: --- editor: markdown: wrap: sentence --- The algorithm used for sentence wrapping will handle English and Japanese text well, but may not detect the end of sentences accurately for other languages. If you have enabled a global line wrapping option and want to turn off wrapping for a given document, use wrap: none. References By default, references (footnotes and reference links) are written at the end of the block where their corresponding footnote appears. You can override this behavior using the quarto.visualEditor.markdownReferences VS Code setting or by using the references option within document or project YAML. For example, to write references at the end of sections rather than blocks you would use: --- title: "My Document" editor: markdown: references: location: block --- Valid values for the references option are block, section, and document. If you are aggregating a set of markdown documents into a larger work, you may want to make sure that reference identifiers are unique across all of your documents (e.g. you don’t want to have [^1] appear multiple times). You can ensure uniqueness via the prefix option. For example: --- title: "My Document" editor: markdown: references: location: block prefix: "mydoc" --- This will result in footnotes in this document using the specified prefix (e.g. [^mydoc-1]), ensuring they are globally unique across the manuscript. Note that if you are within a Quarto book project then a references prefix is applied automatically so no changes to editor options are required. Links Links are written inline by default, however they can be written as reference links (below content as with footnotes) by adding the links: true option to the references section of document or project YAML. For example: --- title: "My Document" editor: markdown: references: location: block links: true --- You can alternatively enable reference links using the VS Code quarto.visualEditor.markdownReferenceLinks option. Known Limitations There are a handful of Pandoc markdown extensions not currently supported by visual editing. These are infrequently used extensions, so in all likelihood they won’t affect documents you edit, but are still worth noting. Extension(s) Example Behavior Inline footnotes ^[inline] Converted to numeric footnote. Footnote identifiers [^longnote] Converted to numeric footnote. Example lists (@) First example Read/written as ordinary numbered lists. Auto-list numbers #. First item Read/written as ordinary numbered lists. Reference links This is a [link] Converted to ordinary links. MultiMarkdown attributes # Heading [id] Converted to Pandoc attributes. The visual editor is unable to parse non-YAML title blocks (e.g. old-style % titles or MultiMarkdown titles) and also unable to parse non top-level YAML metadata blocks. If these forms of metadata are encountered, visual mode will fail to load with a warning. Note that support for reference links can be enabled via the editor: markdown: references: links option in document or project YAML, or the VS Code quarto.visualEditor.markdownReferenceLinks option. Reference links will be written according the reference location option (either the block or section in which they appear, or alternatively at the end of the document).
{ "lastmod": "2023-07-05T19:35:15.975Z", "loc": "https://quarto.org/docs/visual-editor/vscode/index.html", "source": "https://quarto.org/docs/visual-editor/vscode/index.html" }
Overview Quarto Websites are a convenient way to publish groups of documents. Documents published as part of a website share navigational elements, rendering options, and visual style. Website navigation can be provided through a global navbar, a sidebar with links, or a combination of both for sites that have multiple levels of content. You can also enable full text search for websites. Quarto websites can be published to a wide variety of destinations including GitHub Pages, Netlify, Posit Connect, or any other static hosting service or intranet web server. See the documentation on Publishing Websites for additional details. Quick Start Follow the Quick Start for your tool of choice to get a simple website up and running. After covering the basics, read on to learn about website navigation and other more advanced website features. VS CodeRStudioTerminal To create a new website project within VS Code, execute the Quarto: Create Project command from the command-palette: Then, select Website Project: You’ll be prompted to select a parent directory to create the project within. Then, you’ll be asked to name the directory for your website project: The new website project will be created and opened within VS Code. Click the Render button to preview the website: The preview will show to the right of the source file. As you re-render index.qmd or render other files like about.qmd, the preview is automatically updated. To create a new website project within RStudio, use the New Project command and select Quarto Website: Then, provide a directory name and other relevant options for the website: Click the Render button to preview the website: The preview will show to the right of the source file. As you re-render index.qmd or render other files like about.qmd, the preview is automatically updated. To create a new website project from the Terminal, use the quarto create-project command, specifying the directory that will hold the new project as first argument: Terminal quarto create-project mysite --type website This will create the scaffolding for a simple website in the mysite sub-directory. Use the quarto preview command to render and preview the website: Terminal quarto preview mysite The website preview will open in a new web browser. As you edit and save index.qmd (or other files like about.qmd) the preview is automatically updated. Workflow Above we demonstrated how to create and edit a simple website. In this section we go into more depth on website workflow. Config File Every website has a _quarto.yml config file that provides website options as well as defaults for HTML documents created within the site. For example, here is the default config file for the simple site created above: _quarto.yml project: type: website website: title: "today" navbar: left: - href: index.qmd text: Home - about.qmd format: html: theme: cosmo css: styles.css toc: true See the documentation on Website Navigation and Website Tools for additional details on website configuration. See HTML Documents for details on customizing HTML format options. Website Preview If you are using VS Code or RStudio, the Render button automatically renders and runs quarto preview in an embedded window. You can also do the same thing from the Terminal if need be: Terminal # preview the website in the current directory quarto preview Note that when you preview a site (either using VS Code / RStudio integrated tools or from the terminal) changes to configuration files (e.g. _quarto.yml) as well as site resources (e.g. theme or CSS files) will cause an automatic refresh of the preview. You can customize the behavior of the preview server (port, whether it opens a browser, etc.) using command line options or the _quarto.yml config file. See quarto preview help or the project file reference for additional details. Important As you preview your site, pages will be rendered and updated. However, if you make changes to global options (e.g. _quarto.yml or included files) you need to fully re-render your site to have all of the changes reflected. Consequently, you should always fully quarto render your site before deploying it, even if you have already previewed changes to some pages with the preview server. Website Render To render (but not preview) a website, use the quarto render command, which will render the website into the _site directory by default: Terminal # render the website in the current directory quarto render See the Project Basics article to learn more about working with projects, including specifying an explicit list of files to render, as well as adding custom pre and post render scripts to your project. Render Targets By default, all valid Quarto input files (.qmd, .ipynb, .md, .Rmd) in the project directory will be rendered, save for ones with: A file or directory prefix of . (hidden files) A file or directory prefix of _ (typically used for non top-level files, e.g. ones included in other files) Files named README.md or README.qmd (which are typically not actual render targets but rather informational content about the source code to be viewed in the version control web UI). If you don’t want to render all of the target documents in a project, or you wish to control the order of rendering more precisely, you can add a project: render: [files] entry to your project metadata. For example: project: render: - section1.qmd - section2.qmd Note that you can use wildcards when defining the render list. For example: project: render: - section*.qmd You can also use the prefix ! to ignore some paths in the render list. Note that in that case you need to start by specifying everything you do want to render. For example: project: render: - "*.qmd" - "!ignored.qmd" - "!ignored-dir/" Note If the name of your output file needs to start with . or _ (for instance _index.md for Hugo users), you must name the Quarto input file without the prefix (for instance index.qmd) and add an explicit output-file parameter in the YAML such as --- output-file: _index.md --- Linking When creating links between pages in your site, you can provide the source file as the link target (rather than the .html file). You can also add hash identifiers (#) to the source file if you want to link to a particular section in the document. For example: [about](about.qmd) [about](about.qmd#section) One benefit of using this style of link as opposed to targeting .html files directly is that if you at some point convert your site to a book the file-based links will automatically resolve to section links for formats that produce a single file (e.g. PDF or MS Word). Learning More Once you’ve got a basic website up and running check out these articles for various ways to enhance your site: Website Navigation describes various ways to add navigation to a website, including top-level navigation bars, sidebars, or hybrid designs that uses both. This article also covers adding full-text search as well as a site-wide footer. Website Tools covers adding social metadata (e.g. for Twitter Cards) and Google Analytics to your site, as well as enabling users to toggle between dark and light color schemes. Website Options provides a comprehensive reference to all of the available website options. Code Execution provides tips for optimizing the rendering of sites with large numbers of documents or expensive computations. Publishing Websites enumerates the various options for publishing websites including GitHub Pages, Netlify, and Posit Connect.
{ "lastmod": "2023-07-05T19:35:16.031Z", "loc": "https://quarto.org/docs/websites/index.html", "source": "https://quarto.org/docs/websites/index.html" }
Overview Quarto includes support for full text search of websites and books. By default, Quarto will automatically index the contents of your site and make it searchable using a locally built index. You can also configure Quarto search to use a hosted Algolia index. Search Appearance Search is enabled by default for websites and books. If the site has a navbar the search UI will appear on the navbar, otherwise it will appear on the sidebar. You can control the location of search with the following options: Option Description location navbar or sidebar (defaults to navbar if one is present on the page). type overlay or textbox (overlay provides a button that pops up a search UI, textbox does search inline) For example: website: search: location: navbar type: overlay Note that the above example reflects the default behavior so need not be explicitly specified. Note also that search is enabled by default for websites (you can disable it with search: false). The overlay option displays the search UI as follows: The textbox option displays search like this: Customizing Results You can use the following search options to customize how search results are displayed: Option Description limit The number of results to display in the search results. Defaults to 20. collapse-after The number of sections matching a document to show before hiding additional sections behind a ‘more matches’ link. Defaults to 2. copy-button If true, the search textbox will include a small icon that when clicked will copy a url to the search results to the clipboard (this is useful if users would like to share a particular search with results). Defaults to false. Using Algolia In addition to the built in search capability, Quarto websites can also be configured to use an external Algolia search index. When rendering a website, Quarto will produce a JSON file (search.json in the site output directory) which can be used to update an Algolia index. For more on creating indexes with Algolia, see Send and Update Your Data using Algolia. Basic Configuration In order for Quarto to connect to your Algolia index, you need to provide basic connection information in your Quarto project file. You can find this connection information for your Algolia index in the Dashboard in the API Keys section. The following basic connection information is required: Option Description index-name The name of the index to use when performing a search. application-id The unique ID used by Algolia to identify your application. search-only-api-key The Search-Only API key to use to connect to Algolia. Important Be sure to use the Search Only API key, which provides read only access to your index and is safe to include in project files. Never use your Admin API key in a Quarto document or project. show-logo Displays a ‘search by Algolia’ logo in the footer of search results. For example: website: search: algolia: index-name: <my-index-name> application-id: <my-application-id> search-only-api-key: <my-search-only-api-key> Custom Index Schema If you are simply using the search.json file generated by Quarto as your Algolia index, the above configuration information is all that is required to set up search using Algolia. However, if you are generating an index in some other fashion, you may need to provide additional information to specify which fields Quarto should use when searching. You do this by including an index-fields key under algolia which specifies the names of specific fields in your index. Option Description href The field to use to read the URL to this index entry. The user will be navigated to this URL when they select the matching search result. Note that Quarto groups results by URL (not including the anchor when grouping). This field is required (either as an existing field in your index or with a mapped field name). title The field to use to read the title of the index entry. This field is required (either as an existing field in your index or with a mapped field name). text The field to use to read the text of the index entry. This field is required (either as an existing field in your index or with a mapped field name). section The field to use to read the section of the index entry. Quarto groups results by URL and uses the section information (if present) to show matching subsections of the same document. This field is optional. Any or all of the above may be specified in your Quarto project file. For example: website: search: algolia: index-name: <my-index-name> application-id: <my-application-id> search-only-api-key: <my-search-only-api-key> index-fields: href: url section: sec text: body Algolia Insights By default, Algolia provides a number of insights based upon the performance of your Algolia search. In addition, it may be helpful to understand more detailed tracking of the results that are viewed and clicked. You can enable click and conversion tracking using Algolia by setting the analytics-events to true: website: search: algolia: index-name: <my-index-name> application-id: <my-application-id> search-only-api-key: <my-search-only-api-key> analytics-events: true You can confirm that events are being properly sent to Algolia using the Event Debugger. Note that the click and conversion events use cookies to maintain an anonymous user identifier—if cookie consent is enabled, search events will only be enabled if cookie consent has been granted. Advanced Configuration In addition to the above configuration, you may also pass Algolia specific parameters when executing a search. For example, you may want to limit results to a particular facet or set of tags. To specify parameters, add the params key to your algolia yaml and provide params. For information about about available parameters, see Algolia’s Search API Parameters. For example: website: search: algolia: index-name: <my-index-name> application-id: <my-application-id> search-only-api-key: <my-search-only-api-key> index-fields: href: url section: sec text: body params: tagFilters: ['tag1','tag2'] Disabling Search You can disable search for an individual document by adding search: false to the document metadata. For example: --- title: "My Document" search: false --- If you’d like to disable search support for an entire website, you can do so by including the following in your _quarto.yml file: website: search: false
{ "lastmod": "2023-07-05T19:35:16.031Z", "loc": "https://quarto.org/docs/websites/website-search.html", "source": "https://quarto.org/docs/websites/website-search.html" }
Overview There are a variety of options available for providing website navigation, including: Using top navigation (a navbar) with optional sub-menus. Using side navigation with a hierarchy of pages. Combining top and side navigation (where top navigation links to different sections of the site each with their own side navigation). In addition, you can add full text search to either the top or side navigation interface. Top Navigation To add top-navigation to a website, add a navbar entry to the website config in _quarto.yml. For example, the following YAML: website: navbar: background: primary search: true left: - text: "Home" file: index.qmd - talks.qmd - about.qmd Results in a navigation bar that looks something like this: Above we use the left option to specify items for the left side of the navigation bar. You can also use the right option to specify items for the right side. The text for navigation bar items will be taken from the underlying target document’s title. Note that in the above example we provide a custom text: "Home" value for index.qmd. You can also create a navigation bar menu by including a menu (which is a list of items much like left and right). For example: left: - text: "More" menu: - talks.qmd - about.qmd Here are all of the options available for top navigation: Option Description title Navbar title (uses the site: title if none is specified). Use title: false to suppress the display of the title on the navbar. logo Logo image to be displayed left of the title. logo-alt Alternate text for the logo image. logo-href Target href from navbar logo / title. By default, the logo and title link to the root page of the site (/index.html). background Background color (“primary”, “secondary”, “success”, “danger”, “warning”, “info”, “light”, “dark”, or hex color) foreground Foreground color (“primary”, “secondary”, “success”, “danger”, “warning”, “info”, “light”, “dark”, or hex color). The foreground color will be used to color navigation elements, text and links that appear in the navbar. search Include a search box (true or false) tools List of navbar tools (e.g. link to github or twitter, etc.). See Navbar Tools for details. left / right Lists of navigation items for left and right side of navbar pinned Always show the navbar (true or false). Defaults to false, and uses headroom.js to automatically show the navbar when the user scrolls up on the page. collapse Collapse the navbar items into a hamburger menu when the display gets narrow (defaults to true) collapse-below Responsive breakpoint at which to collapse navbar items to a hamburger menu (“sm”, “md”, “lg”, “xl”, or “xxl”, defaults to “lg”) Here are the options available for individual navigation items: Option Description href Link to file contained with the project or external URL. text Text to display for navigation item (defaults to the document title if not provided). icon Name of one of the standard Bootstrap 5 icons (e.g. “github”, “twitter”, “share”, etc.). aria-label Accessible label for the navigation item. rel Value for rel attribute. Multiple space-separated values are permitted. menu List of navigation items to populate a drop-down menu. For more information on controlling the appearance of the navigation bar using HTML themes, see HTML Themes - Navigation. Navbar Tools Quarto 1.3 Feature This feature is new in Quarto 1.3, which you can download at https://quarto.org/docs/download/ In addition to traditional navigation, the navbar can also display a set of tools (e.g. social actions, GitHub view or edit actions, etc.) A tool definition consists of an icon name and an href to follow when clicked. For icon, use the icon name of any of the 1,300+ Bootstrap Icons. For example: website: navbar: tools: - icon: twitter href: https://twitter.com - icon: github menu: - text: Source Code url: https://code.com - text: Report a Bug url: https://bugs.com Tools specified for a navigation bar will appear on the right side of the Navbar. If you specify a dark theme or reader mode for your website, the controls for those options will appear with any specified tools. When the navbar is collapsed into a menu on smaller screens, the tools will be placed at the bottom of the menu. Side Navigation If your site consists of more than a handful of documents, you might prefer to use side navigation, which enables you to display an arbitrarily deep hierarchy of articles. If you are reading this page on a desktop device then you will see the default side navigation display on the left (otherwise you’ll see a title bar at the top which you can click or touch to reveal the navigation). To add side navigation to a website, add a sidebar entry to the website section of _quarto.yml. For example: website: sidebar: style: "docked" search: true contents: - section: "Basics" contents: - index.qmd - basics-knitr.qmd - basics-jupyter.qmd - section: "Layout" contents: - layout.qmd - layout-knitr.qmd - layout-jupyter.qmd There are two styles of side navigation available: “docked” which shows the navigation in a sidebar with a distinct background color, and “floating” which places it closer to the main body text. Here’s what the “docked” and “floating” styles look like (respectively): Here are all of the options available for side navigation: Option Description id Optional identifier (used only for hybrid navigation, described below). title Sidebar title (uses the project title if none is specified). subtitle Optional subtitle logo Optional logo image search Include a search box (true or false). Note that if there is already a search box on the top navigation bar it won’t be displayed on the sidebar. tools List of sidebar tools (e.g. link to github or twitter, etc.). See the next section for details. items List of navigation items to display (typically top level items will in turn have a list of sub-items). style “docked” or “floating” type “dark” or “light” (hint to make sure the text color is the inverse of the background) background Background color (“none”, “primary”, “secondary”, “success”, “danger”, “warning”, “info”, “light”, “dark”, or “white”). Defaults to “light”. foreground Foreground color (“primary”, “secondary”, “success”, “danger”, “warning”, “info”, “light”, “dark”, or hex color). The foreground color will be used to color navigation elements, text and links that appear in the sidebar. border Whether to show a border on the sidebar. “true” or “false” alignment Alignment (“left”, “right”, or “center”). collapse-level Whether to show sidebar navigation collapsed by default. The default is 2, which shows the top and next level fully expanded (but leaves the 3rd and subsequent levels collapsed). pinned Always show a title bar that expands to show the sidebar at narrower screen widths (true or false). Defaults to false, and uses headroom.js to automatically show the navigation bar when the user scrolls up on the page. For more information on controlling the appearance of the side navigation using HTML themes, see HTML Themes - Navigation. If you need to control the width of the sidebar, see Page Layout - Grid Customization. Auto Generation Above we describe how to explicitly populate the contents of your sidebar with navigation items. You can also automatically generate sidebar navigation from the filesystem. The most straightforward way to do this is to specify the auto: true option as follows: sidebar: contents: auto Using contents: auto at the root level will result in all documents in your website being included within the navigation (save for the home page which can be navigated to via the title link). Navigation is constructed using the following rules: Navigation item titles will be read from the title field of documents. Sub-directories will create sections and will be automatically titled based on the directory name (including adding capitalization and substituting spaces for dashes and underscores). Use an index.qmd in the directory to provide an explicit title if you don’t like the automatic one. Order is alphabetical (by filename) unless a numeric order field is provided in document metadata. Automatic navigation automatically includes items in sub-directories. If you prefer not to do this, use an explicit /* to indicate only the documents in the root directory: sidebar: contents: /* Rather than specifying that all documents should be included, you can also specify a directory name or a glob pattern. For example, the following values for auto are all valid (note that the second form for reports is non-recursive): sidebar: contents: reports sidebar: contents: reports/* sidebar: contents: "*.ipynb" Note that in YAML we need to quote any strings that begin with * (as we do above for *.ipynb). You can automatically build sidebar contents anywhere within a sidebar hierarchy. For example, here we add a section that is automatically generated from a directory: sidebar: contents: - about.qmd - contributing.qmd - section: Reports contents: reports You can also include automatically generated items in the middle of a list of normal items by including an item with an auto property. Here we add an auto entry in the middle of a list of items: sidebar: contents: - about.qmd - contributing.qmd - auto: "*-report.qmd" Note again that we quote the auto entry with a * in it so that it is correctly parsed. Sidebar Tools In addition to traditional navigation, the sidebar can also display a set of tools (e.g. social actions, GitHub view or edit actions, etc.) A tool definition consists of an icon name and an href to follow when clicked. For icon, use the icon name of any of the 1,300+ Bootstrap Icons. For example: website: sidebar: tools: - icon: twitter href: https://twitter.com - icon: github menu: - text: Source Code url: https://code.com - text: Report a Bug url: https://bugs.com Hybrid Navigation If you have a website with dozens or even hundreds of pages, you will likely want to use top and side navigation together, where the top navigation links to various sections, each with their own side navigation. To do this, provide a group of sidebar entries and link each group of sidebar entries with a navbar entry by matching their titles and listing the page linked from the navbar as the first content in the sidebar group. For example, if you are using the Diátaxis Framework for documentation, you might have separate sections for tutorials, how-to guides, explanations, and reference documents, your page might look like the following. With hybrid navigation, if then you click on, say, Tutorials, you might land in a page like the following. To achieve this layout, your site configuration needs to look something like this: website: title: ProjectX navbar: background: primary search: true left: - text: "Home" file: index.qmd - text: "Tutorials" file: tutorials.qmd - text: "How-To" file: howto.qmd - text: "Fundamentals" file: fundamentals.qmd - text: "Reference" file: reference.qmd sidebar: - title: "Tutorials" style: "docked" background: light contents: - tutorials.qmd - tutorial-1.qmd - tutorial-2.qmd - title: "How-To" contents: - howto.qmd # navigation items - title: "Fundamentals" contents: - fundamentals.qmd # navigation items - title: "Reference" contents: - reference.qmd # navigation items Note that the first sidebar definition contains a few options (e.g. style and background). These options are automatically inherited by the other sidebars. An alternative approach is to make the sidebar entries available from a drop down menu from the navbar items they’re grouped with. To do this, provide a list of sidebar entries and give them each an id, which you then use to reference them from the navbar. Note A page that doesn’t appear in any sidebar will inherit and display the first sidebar- you can prevent the sidebar from showing on a page by setting sidebar: false in it’s front matter. To achieve this, your site configuration needs to look something like this: website: title: ProjectX navbar: background: primary search: true left: - text: "Home" file: index.qmd - sidebar:tutorials - sidebar:howto - sidebar:fundamentals - sidebar:reference sidebar: - id: tutorials title: "Tutorials" style: "docked" background: light collapse-level: 2 contents: # navigation items - id: howto title: "How-To" contents: # navigation items - id: fundamentals title: "Fundamentals" contents: : # navigation items - id: reference title: "Reference" contents: # navigation items Page Navigation If you have a website with several pages in a section or subsection, it is often convenient to offer the user the ability to navigate to the next page (or previous page) at the bottom of the page that they’ve just finished reading. You can enable this using: website: page-navigation: true When enabled, page navigation will be displayed at the bottom of the page whenever there is a next or previous page (including in the next or previous section). This option is enabled by default for books but not for websites. Separators If you include a page separator in the sidebar (either between sections or items), page navigation controls will not appear to continue pagination across the separator. For example, in the following sidebar: website: sidebar: contents: - section: "First Section" contents: - href: document1.qmd - href: document2.qmd - href: document3.qmd - text: "---" - section: "Second Section" contents: - href: document4.qmd - href: document5.qmd - href: document6.qmd When the user reaches the bottom of document3.qmd, they will see previous navigation to go back to document2.qmd, but they will not see next navigation to continue onto document 4. This behavior is useful when you have sections of contents that don’t naturally flow together in sequential order. Use the separator to denote this in the sidebar with a horizontal line and to break up pagination. Back to Top You can include a “Back to top” link at the bottom of documents in a website using the back-to-top-navigation option. For example: website: back-to-top-navigation: true Note that you can disable back to top navigation on a page by page basis by specifying back-to-top-navigation: false. Page Footer Use the page-footer option to provide a common footer for all of the pages in a website. The simplest footer just provides text that will be centered and displayed in a lighter typeface: website: page-footer: "Copyright 2021, Norah Jones" You can alternatively target the left, right, and center regions of the footer individually: website: page-footer: left: "Copyright 2021, Norah Jones" right: - icon: github href: https://github.com/ - icon: twitter href: https://twitter.com/ Note for the right region of the footer we included navigational items for GitHub and Twitter rather than text. You can include navigational items in any region of the footer. You can use the background, foreground, and border options to further control the appearance of the footer. By default, the footer has no background color and a top border. To eliminate the border you would do this: website: page-footer: border: false To use a light background (e.g. to match a navigation bar) you would do this: website: page-footer: background: light Unless specified, the color (foreground) used for elements that appear in the footer will be automatically determined by using a color that contrasts with the footer background. Hiding Navigation For some pages (especially those with a completely custom layout) you can hide navigation altogether (navbar, sidebar, or both). In these case, add the following to the page front matter: # Hides the sidebar on this page sidebar: false # Hides the navbar on this page navbar: false Reader Mode If you’d like users to be able to hide the side navigation and table of contents and have a more focused reading experience, you can enabled reader-mode. When enabled, a reader-mode toggle will appear on the navbar, if present, or on the sidebar. When pressed, the toggle will ‘roll up’ the sidebar and table of contents. To enable reader-mode, use the following in your project: website: reader-mode: true Site Search You can add site search by including search: true in either your site-navbar or site-sidebar configuration. For example: website: sidebar: style: "docked" search: true items: - text: "Basics" contents: - index.qmd - basics-jupyter.md # etc GitHub Links You can add various links (e.g. to edit pages, report issues, etc.) to the GitHub repository where your site source code is hosted. To do this, add a repo-url along with one or more actions in repo-actions. For example: website: repo-url: https://github.com/quarto-dev/quarto-demo repo-actions: [edit, issue] The links will be displayed immediately below the page table of contents: There are a couple of additional options that enable you to customize the behavior of repository links: Option Description repo-subdir Subdirectory of repository containing source files (defaults to root directory). repo-branch Repository branch containing the source files (defaults to main) issue-url Provide an explicit URL for the ‘Report an Issue’ action. Redirects If you rename or move a page on your site, you may want to create redirects from the old URLs so that existing links don’t break. You can do this by adding aliases from old pages to renamed pages. For example, let’s say you renamed page.qmd to renamed-page.qmd. You would add the following aliases entry to renamed-page.qmd to create the redirect: --- title: "Renamed Page" aliases: - page.html --- This can also be useful for situations where you re-organize content on your site into a different directory hierarchy or break one large article into smaller ones. For this case, you may want to add the URL hash of the section that you have broken into a new page. For example: --- title: "Learning More" aliases: - overview.html#learning-more --- Tip Depending on where you are deploying your site there may be more powerful tools available for defining redirects based on patterns. For example, Netlify _redirects files or .htaccess files. Search your web host’s documentation for “redirects” to see if any of these tools are available. 404 Pages When a browser can’t find a requested web page, it displays a 404 error indicating that the file can’t be found. Browser default 404 pages can be pretty stark, so you may want to create a custom page with a more friendly message and perhaps pointers on how users might find what they are looking for. Most web serving platforms (e.g. Netlify, GitHub Pages, etc.) will use a file named 404.html in the root of your website as a custom error page if you provide it. You can include a custom 404 page in a Quarto website by creating a markdown file named 404.qmd in the root of your project. For example: --- title: Page Not Found --- The page you requested cannot be found (perhaps it was moved or renamed). You may want to try searching to find the page's new location. Note that you can use HTML alongside markdown within your 404.qmd file in order to get exactly the appearance and layout you want. Your 404 page will appear within the chrome of your site (e.g. fonts, css, layout, navigation, etc.). This is so that users don’t feel that they’ve irrecoverably “left” your site when they get a 404 error. If you don’t want this behavior, then provide a 404.html rather than 404.qmd. Here are some examples of how various popular websites handle custom 404 pages: https://blog.fluidui.com/top-404-error-page-examples/. Non-Root Site Paths If your website is served from the root of a domain (e.g. https://example.com/) then simply providing a 404.qmd file as described above is all that’s required to create a custom 404 page. However, if your website is not served from the root of a domain then you need to provide one additional bit of configuration to make sure that resources (e.g. your site’s CSS) are resolved correctly within 404 pages. For example, if your site is served from https://example.com/mysite/ then you’d add the following to your project website configuration within _quarto.yml: website: title: "My Site" site-path: "/mysite/" Note that if you are already providing a site-url (which is required for generation of sitemaps and social metadata preview images) then it’s enough to simply include the path within the site-url: website: title: "My Site" site-url: "https://example.com/mysite/"
{ "lastmod": "2023-07-05T19:35:16.031Z", "loc": "https://quarto.org/docs/websites/website-navigation.html", "source": "https://quarto.org/docs/websites/website-navigation.html" }
Headers & Footers You can provide standard headers and footers for pages on your site. These can apply to the main document body or to the sidebar. Available options include: Value Description body-header Markdown to insert at the beginning of each page’s body (below the title and author block). body-footer Markdown to insert below each page’s body. margin-header Markdown to insert above right margin content (i.e. table of contents). margin-footer Markdown to insert below right margin content. For example (included in _quarto.yml) : body-header: | This page brought to you by <https://example.com> margin-header: | ![Logo image](/img/logo.png) Note that links to figures should start with a / to work on each level of the website. Social Metadata You can enhance your website and the content that you publish to it by including additional types of metadata, including: Favicon Twitter Cards Open Graph One important thing to note about using website tools is that while these tools are added to websites within the website key, in a book you should include the same options in the book key. For example, in a website you would include a favicon and twitter card as follows: website: favicon: logo.png twitter-card: true site-url: https://example.com In a book you’d use the book key instead: book: favicon: logo.png twitter-card: true site-url: https://example.com As you read the documentation below, keep in mind to substitute book for website if you are authoring a book. Favicon The favicon for your site provides an icon for browser tabs and other sites that link to yours. Use the favicon option to provide the path to a favicon image. For example: website: favicon: logo.png Twitter Cards Twitter Cards provide an enhanced appearance when someone links to your site on Twitter. When a link to your site is included in a Tweet, Twitter automatically crawls your site and fetches any Twitter Card metadata. To enable the automatic generation of Twitter Card metadata for your site, you can add the following to your _quarto.yml configuration file: website: twitter-card: true In this case, Quarto will automatically generate a title, description, and preview image for the content. For more information about how Quarto finds preview images, see Preview Images. You may also provide additional metadata to be used when generating the Twitter Card, including: Key Description title The title of the page. Quarto will automatically use the title metadata from the page metadata. If you’d like you can override this just for the Twitter Card by including a title in the twitter-card metadata. description A short description of the content. Quarto will automatically use the description metadata from the page metadata. If you’d like you can override this just for the Twitter Card by including a description in the twitter-card metadata. image The path to a preview image for this content. By default, Quarto will use the image value from the document metadata. If you provide an image, you may also optionally provide an image-width and image-height to improve the appearance of your Twitter Card. If image is not provided, Quarto will automatically attempt to locate a preview image. For more information, see Preview Images. card-style Either summary or summary_large_image. If this is not provided, the best style will automatically selected based upon other metadata. You can learn more about Twitter Card styles here. creator @username of the content creator. Note that strings with special characters such as @ must be quoted in yaml. site @username of website. Note that strings with special characters such as @ must be quoted in yaml. Here is a more comprehensive example of specifying Twitter Card metadata in a quarto.yml file: website: twitter-card: creator: "@dragonstyle" site: "@rstudio" Quarto will automatically merge global metadata found in the website: twitter-card key with any metadata provided in the document itself in the twitter-card key. This is useful when you need to specify a mix of global options (for example, site) with per document options such as title or image. Open Graph The Open Graph protocol is a specification that enables richer sharing of links to articles on the web. It will improve the previews of your content when a link to it is pasted into applications like Slack, Discord, Facebook, Linkedin, and more. To enable the automatic generation of Open Graph metadata for your content, include the following in your _quarto.yml configuration file: website: open-graph: true In this case, Quarto will automatically generate a title, description, and preview image for the content. For more information about how Quarto finds preview images, see Preview Images. You may also provide additional metadata to be used when generating the Open Graph metadata, including: Key Description title The title of the page. Quarto will automatically use the title metadata from the page metadata. If you’d like you can override this just for the Open Graph metadata by including a title in the open-graph metadata. description A short description of the content. Quarto will automatically use the description metadata from the page metadata. If you’d like you can override this just for the Open Graph metadata by including a description in the open-graph metadata. image The path to a preview image for this content. By default, Quarto will use the image value from the site: metadata. If you provide an image, you may also optionally provide an image-width and image-height. If image is not provided, Quarto will automatically attempt to locate a preview image. For more information, see Preview Images. locale The locale that the Open Graph metadata is marked up in. site-name The name which should be displayed for the overall site. If not explicitly provided in the open-graph metadata, Quarto will use the site:title value. Here is a more comprehensive example of specifying Open Graph metadata in a quarto.yml file: website: open-graph: locale: es_ES site-name: Quarto Quarto will automatically merge global metadata found in the website: open-graph key with any metadata provided in the document itself in the open-graph key. This is useful when you need to specify a mix of global options (for example, site) with per document options such as title or image. Preview Images You can specify a preview image for your article in several different ways: You can explicitly provide a full url to the preview image using the image field in the appropriate metadata. For example: title: "My Document" twitter-card: image: "https://quarto.org/docs/websites/images/tools.png" You may provide a document relative path to an image (such as images/preview-code.png) or a project relative path to an image (such as /images/preview-code.png). If you provide a relative path such as this, you must also provide a site-url in your site’s metadata. For example in your _quarto.yml configuration file: website: site-url: "https://www.quarto.org" and in your document front matter: title: "My Document" twitter-card: image: "/docs/websites/images/tools.png" Any image that is being rendered in the page may also be used as a preview image by giving it the class name preview-image. Quarto will select the first image it finds with this class. For example, the following image will be used as the preview image when included on a page: ![](images/tools.png){.preview-image} If you label an image with this class, you must also provide a site-url in your site’s metadata. If none of the above ways of specifying a preview image have been used, Quarto will attempt to find a preview image by looking for an image included in the rendered document with one of the following names: preview.png, feature.png, cover.png, or thumbnail.png. Google Analytics You can add Google Analytics to your website by adding adding a google-analytics key to your _quarto.yml file. In its simplest form, you can just pass your Google Analytics tracking Id (e.g. UA-xxxxxxx) or Google Tag measurement Id (e.g. G-xxxxxxx) like: website: google-analytics: "UA-XXXXXXXX" Quarto will use the key itself to determine whether to embed Google Analytics (analytics.js) or Google Tags (gtag) as appropriate. In addition to this basic configuration, you can exercise more fine grained control of your site analytics using the following keys. Key Description tracking-id The Google tracking Id or measurement Id of this website. storage cookies - Use cookies to store unique user and session identification (default). none - Do not use cookies to store unique user and session identification. For more about choosing storage options see Storage. anonymize-ip Anonymize the user ip address. For more about this feature, see IP Anonymization (or IP masking) in Google Analytics. version The version number of Google Analytics to use. Currently supports either 3 (for analytics.js) or 4 (for gtag). This is automatically detected based upon the tracking-id, but you may specify it. Storage Google Analytics uses cookies to distinguish unique users and sessions. If you choose to use cookies to store this user data, you should consider whether you need to enable Cookie Consent in order to permit the viewer to control any tracking that you enable. If you choose none for storage, this will have the following effects: For Google Analytics v3 (analytics.js) No tracking cookies will be used. Individual page hits will be properly tracked, enabling you to see which pages are viewed and how often they are viewed. Unique user and session tracking will not report data correctly since the tracking cookies they rely upon are not set. For Google Tags (gtag) User consent for ad and analytics tracking cookies will be withheld. In this mode, Google Analytics will still collect user data without the user identification, but that data is currently not displayed in the Google Analytics reports. Cookie Consent Quarto includes the ability to request cookie consent before enabling scripts that set cookies, using Cookie Consent. The user’s cookie preferences will automatically control Google Analytics (if enabled) and can be used to control custom scripts you add as well (see Custom Scripts and Cookie Consent. You can enable the default request for cookie consent using the following: website: cookie-consent: true You can further customize the appearance and behavior of the consent using the following: Key Description type The type of consent that should be requested, using one of these two values: implied - (default) This will notify the user that the site uses cookies and permit them to change preferences, but not block cookies unless the user changes their preferences. express - This will block cookies until the user expressly agrees to allow them (or continue blocking them if the user doesn’t agree). style The style of the consent banner that is displayed: simple - (default) A simple dialog in the lower right corner of the website. headline - A full width banner across the top of the website. interstitial - An semi-transparent overlay of the entire website. standalone - An opaque overlay of the entire website. palette Whether to use a dark or light appearance for the consent banner: light - A light colored banner. dark - A dark colored banner. policy-url The url to the website’s cookie or privacy policy. prefs-text The text to display for the cookie preferences link in the website footer. A custom example might look more like: website: cookie-consent: type: express style: headline palette: dark google-analytics: tracking-id: "G-XXXXXXX" anonymize-ip: true Cookie Preferences In addition to requesting consent when a new user visits your website, Cookie Consent will also add a cookie preferences link to the footer of the website. You can control the text of this link using prefs-text. If you would rather position this link yourself, just add a link with the id #open_preferences_center to the website and Cookie Consent will not add the preferences link to the footer. For example: Change [cookie preferences]{#open_preferences_center} Custom Scripts and Cookie Consent Cookie Consent works by preventing the execution of scripts unless the user has expressed their consent. To control your custom scripts using Cookie Consent: Insert script tags as type='text/plain' (when the user consents, the type will be switched to text/javascript and the script will be executed). Add a cookie-consent attribute to your script tag, setting it one of the following 4 levels: Level Description strictly-necessary Strictly scripts are loaded automatically and cannot be disabled by the user. functionality Scripts that are required for basic functionality of the website, for example, remembering a user language preference. tracking Scripts that are used to track users, for example Google Analytics. targeting Scripts that are used for the purposed of advertising to ad targeting, for example Google AdSense remarketing. An example script that is used for user tracking would look like: <script type="text/plain" cookie-consent="tracking"> // My tracking JS code here </script> Site Resources Besides input and configuration files, your site likely also includes a variety of resources (e.g. images) that you will want to publish along with your site. Quarto will automatically detect any files that you reference within your site and copy them to the output directory (e.g. _site). If this auto-detection fails for any reason, or if you want to publish a file not explicitly linked to from within your site, you can add a resources entry to your configuration. For example, here we specify that we want to include all Excel spreadsheets within the project directory as part of the website: project: type: website resources: - "*.xlsx" Note that the *.xslx value is quoted: this is because YAML requires that strings that begin with non-alphanumeric characters be quoted. You can also add a resources metadata value to individual files. For example: title: "My Page" resources: - "sheet.xlsx" Images are the most commonly used type of resource file. If you have global images (e.g. a logo) that you want to reference from various pages within your site, you can use a site-absolute path to refer to the images, and it will be automatically converted to a relative path during publishing. For example: ![](/images/logo.png) Dark Mode Quarto websites can support both a light and dark mode. For example, you may use the flatly and darkly themes (which are designed to be used in tandem as dark and light appearances) as: theme: light: flatly dark: darkly For more about selecting the dark and light themes for your website, see Dark Mode. Light Dark When enabled, a toggle that allows your reader to control the appearance of the website will appear. The toggle will automatically be added to the website navigation as follows: If a navbar has been specified, the toggle will appear in the top right corner of the nav bar. If there is no navbar present, but a sidebar has been specified, the toggle will appear in the same location that the sidebar tools appears (adjacent to the title or logo in the sidebar). If there is no navbar or sidebar present, the toggle will appear in the top right corner of the page.
{ "lastmod": "2023-07-05T19:35:16.031Z", "loc": "https://quarto.org/docs/websites/website-tools.html", "source": "https://quarto.org/docs/websites/website-tools.html" }
This article covers customizing the output of book projects, including how to tailor the styles and appearance of books in each supported output format. Format Options If you want to specify rendering options (including format-specific options), you do it within the _quarto.yml project file rather than within the individual markdown documents. This is because when rendering a book all of the chapters are combined together into a single document (with a single set of format options). Here’s an example configuration: highlight-style: pygments format: html: theme: cosmo code-copy: true pdf: default bibliography: references.bib csl: citestyle.csl Note that in the above configuration the highlight-style option applies to all formats whereas the html options apply to only HTML output. The bibliography related options naturally also apply to all formats. Reader Tools Website Tools HTML books are at their core Quarto Websites with some special navigational behavior built in. This means that all of the features described for enhancing websites are also available for books, including: Navbars Social Metadata Full Text Search Google Analytics Headers and Footers Dark Mode One important thing to note about using website tools is that while these tools are added to websites within the website key, in a book you should include the same options in the book key. For example, in a website you would include a favicon and twitter card as follows: website: favicon: logo.png twitter-card: true site-url: https://example.com In a book you’d use the book key instead: book: favicon: logo.png twitter-card: true site-url: https://example.com Sidebar Tools Books automatically include a navigational sidebar that can optionally include tools for searching book contents, sharing links to the book, etc. Here is an example _quarto.yml file that enables these options: book: title: "Hands-On Programming with R" author: "Garrett Grolemund" search: true repo-url: https://github.com/jjallaire/hopr/ repo-actions: [edit] downloads: [pdf, epub] sharing: [twitter, facebook] comments: hypothesis: true Note the various tools that now appear: The search box enables full text search of the entire book The buttons immediately below the book title in the sidebar provide a link to the GitHub repo for the book, downloads for PDF and ePub versions of the book, and links for sharing the book on Twitter and Facebook. Immediately below the table of contents on the right there is an “Edit this page” link that takes the reader to the edit interface on GitHub for the current chapter. Note that in this example we specify repo-actions: [edit]. You can optionally also add issue and source actions (e.g. repo-actions: [edit, issue, source]). There are additional options available (repo-subdir and repo-branch) for customizing repository links. The Hypothesis commenting bar appears on the far right of the page. Note that commenting is a feature available for all Quarto HTML output so appears in its own YAML key. Sidebar Options Note that books utilize the standard sidebar component from Quarto Websites. This means that you can use any of the available sidebar options within your book configuration. For example, here we specify a docked sidebar with a light background: book: title: "Hands-On Programming with R" author: "Garrett Grolemund" sidebar: style: docked background: light Cover Images You can provide a cover image for EPUB and/or HTML formats using the cover-image option. For example: book: cover-image: cover.png You can also do this on a per-format basis (if for example you want to provide a higher resolution image for EPUB and a lower resolution image for HTML to reduce download time). For example: format: html: cover-image: cover.png epub: cover-image: cover-highres.png You can specify HTML alt-text for book cover images using the cover-image-alt option: book: cover-image: cover.png cover-image-alt: | Alternative text describing the book cover Output Path By default, book output is written to the _book directory of your project. You can change this via the output-dir project option. For example: project: type: book output-dir: docs Single file outputs like PDF, EPUB, etc. are also written to the output-dir. Their file name is derived from the book title. You can change this via the output-file option: book: title: "My Book" output-file: "my-book" Note that the output-file should not have a file extension (that will be provided automatically as appropriate for each format). LaTeX Output In some cases you’ll want to do customization of the LaTeX output before creating the final printed manuscript (e.g. to affect how text flows between pages or within and around figures). The best way to approach this is to develop your book all the way to completion, then render to the latex format Terminal quarto render --to latex The complete LaTeX source code of your book will be output into the _book/book-latex directory. At this point you should probably make a copy or git branch of the _book directory to perform your final LaTeX modifications within (since the modifications you make to LaTeX will not be preserved in your markdown source, and will therefore be overwritten the next time you render). HTML Styles HTML output can be customized either by adding (or enhancing) a custom theme, or by providing an ordinary CSS file. Use the theme option to specify a theme: format: html: theme: cosmo To further customize a theme add a custom theme file: format: html: theme: [cosmo, theme.scss] You can learn more about creating theme files in the documentation on HTML Themes. You can also just use plain CSS. For example: format: html: css: styles.css EPUB Styles You can also use CSS to customize EPUB output: format: epub: css: epub-styles.css epub-cover-image: epub-cover.png Note that we also specify a cover image. To learn more about other EPUB options, see the Pandoc documentation on EPUBs. PDF Styles You can include additional LaTeX directives in the preamble of your book using the include-in-header option. You can also add documentclass and other options (see the Pandoc documentation on LaTeX options for additional details). For example: format: pdf: documentclass: scrbook include-in-header: preamble.tex fontfamily: libertinus Quarto uses the KOMA Script scrreprt document class by default for PDF books. KOMA-Script classes are drop-in replacements for the standard classes with an emphasis on typography and versatility. You can switch to KOMA scrbook as demonstrated above, or to the standard LaTeX book and report classes. You can find a summary of the differences between book and report here: https://tex.stackexchange.com/questions/36988 MS Word Styles You can customize MS Word output by creating a new reference doc, and then applying it to your book as follows: format: docx: reference-doc: custom-reference.docx To create a new reference doc based on the Pandoc default, execute the following command: Terminal quarto pandoc -o custom-reference.docx --print-default-data-file reference.docx Then, open custom-reference.docx in MS Word and modify styles as you wish: You can open the Styles pane from the HOME tab in the MS Word toolbar. When you move the cursor to a specific element in the document, an item in the styles list will be highlighted. If you want to modify the style of any type of element, you can click the drop-down menu on the highlighted item, and you will see a dialog box like this: After you finish modifying the styles, you can save the document and use it as the template for future Word documents.
{ "lastmod": "2023-07-05T19:35:15.255Z", "loc": "https://quarto.org/docs/books/book-output.html", "source": "https://quarto.org/docs/books/book-output.html" }
Overview Quarto Books are combinations of multiple documents (chapters) into a single manuscript. Books can be created in a variety of formats: HTML PDF MS Word EPUB AsciiDoc HTML books are actually just a special type of Quarto Website and consequently support all of the same features as websites including full-text search. The most important difference is that HTML books use chapter numbers and therefore support Cross References between different chapters. Here are some examples of books created with Quarto: Book Source R for Data Science Code Python for Data Analysis Code Visualization Curriculum Code Quarto books can be published to a wide variety of destinations including GitHub Pages, Netlify, RStudio Connect, or any other static hosting service or intranet web server. See the documentation on Publishing Websites for additional details. Quick Start Follow the Quick Start for your tool of choice to get a simple book up and running. After covering the basics, read on to learn about more advanced book features. VS CodeRStudioTerminal To create a new book project within VS Code, execute the Quarto: Create Project command from the command-palette: Then, select Book Project: You’ll be prompted to select a parent directory to create the project within. Then, you’ll be asked to name the directory for your book project: The new book project will be created and opened within VS Code. Click the Render button to preview the book: The preview will show to the right of the source file. As you re-render index.qmd or render other files like intro.qmd, the preview is automatically updated. To create a new book project within RStudio, use the New Project command and select Quarto Book: Then, provide a directory name and other relevant options for the book: Click the Render button to preview the book: The preview will show to the right of the source file. As you re-render index.qmd or render other files like intro.qmd, the preview is automatically updated. To create a new book project from the Terminal, use the quarto create-project command, specifying the directory that will hold the new project as first argument: Terminal quarto create-project mybook --type book This will create the scaffolding for a simple book in the mybook sub-directory. Use the quarto preview command to render and preview the book: Terminal quarto preview mybook The book preview will open in a new web browser. As you edit and save index.qmd (or other files like intro.qmd) the preview is automatically updated. Workflow Above we demonstrated how to create and edit a simple book with chapters contained in the files index.qmd, intro.qmd, summary.qmd. Here we’ll cover additional aspects of book workflow in more depth. Config File A Quarto project file (_quarto.yml) is contained within the book project directory. This file contains the initial configuration for your book. For example: project: type: book book: title: "mybook" author: "Jane Doe" date: "8/18/2021" chapters: - index.qmd - intro.qmd - summary.qmd - references.qmd bibliography: references.bib format: html: theme: cosmo pdf: documentclass: scrreport epub: cover-image: cover.png See the Project Basics article to learn more about working with projects, including how to add custom pre and post render scripts to your book. Book Preview If you are using VS Code or RStudio, the Render button automatically renders and runs quarto preview in an embedded window. You can also do the same thing from the Terminal if need be: Terminal # preview the book in the current directory quarto preview Note that when you preview a book (either using VS Code / RStudio integrated tools or from the terminal) changes to configuration files (e.g. _quarto.yml) as well as book resources (e.g. theme or CSS files) will cause an automatic refresh of the preview. You can customize the behavior of the preview server (port, whether it opens a browser, etc.) using command line options or the _quarto.yml config file. See quarto preview help or the project file reference for additional details. Important As you preview your book, chapters will be rendered and updated. However, if you make changes to global options (e.g. _quarto.yml or included files) you need to fully re-render your book to have all of the changes reflected. Consequently, you should always fully quarto render your site before deploying it, even if you have already previewed changes to some pages with the preview server. For AsciiDoc Books we recommend using the HTML format to preview your book, read more in AsciiDoc Books. Publishing When you are ready to publish the book, use the render command to render all output formats: Terminal quarto render If you pass no arguments to quarto render, all formats will be rendered. You can also render individual formats via the --to argument: Terminal quarto render # render all formats quarto render --to pdf # render PDF format only The output of your book will be written to the _book sub-directory of your book project: Terminal mybook/ _book/ index.html # and other book files mybook.pdf mybook.epub See the documentation on Publishing Websites for details on how to publish books to GitHub Pages, Netlify, and other services. Note that in that documentation the output-dir may be referred to as _site: for publishing books you should use _book rather than _site. AsciiDoc Books For AsciiDoc books, we recommend that while you are working on your book, you preview your content using Quarto’s built in HTML format, which allows a iterative workflow using the preview capabilities of Quarto. Once you’re ready to produce AsciiDoc, you can use the AsciiDoctor tools to compile your book to PDF or HTML output to preview the content in its final rendered form. Previewing PDF with Asciidoctor-pdf Creating a PDF preview with the AsciiDoc toolchain is a useful way to verify that the AsciiDoc output of your book can be rendered properly. To do this, follow these instructions: First, install Asciidoctor PDF by following the instructions here: https://docs.asciidoctor.org/pdf-converter/latest/install/ From the terminal in the root of your project, use the following command to compile your AsciiDoc book to a PDF: $ asciidoctor-pdf _book/book-asciidoc/<title>.adoc The PDF will be placed at _book/book-asciidoc/<title>.pdf. Previewing HTML with Asciidoctor Creating an HTML preview the AsciiDoc toolchain is a useful way to verify that the AsciiDoc output of your book can be rendered properly. To do this, follow these instructions: First, install Asciidoctor by following the instructions here: https://docs.asciidoctor.org/asciidoctor/latest/install/ From the terminal in the root of your project, use the following command to compile your AsciiDoc book to a PDF: $ asciidoctor _book/book-asciidoc/<title>.adoc A single HTML file (with the entire contents of the book) will be placed at _book/book-asciidoc/<title>.html. The HTML file will contain references to files and images in the _book/book-asciidoc/ folder, so the HTML will not display these properly if it is moved without also moving those folders. Learning More Once you’ve got the basic book template up and running check out these articles for various ways to enhance your book: Book Structure delves into different ways to structure a book (numbered and unnumbered chapters/sections, creating multiple parts, adding appendices, etc.) Book Crossrefs explains how to create cross references to sections, figures, tables, equations and more within books. Book Output covers customizing the style and appearance of your book in the various output format as well as how to provide navigation and other tools for readers. Book Options provides a comprehensive reference to all of the available book options. Code Execution provides tips for optimizing the rendering of books with large numbers of documents or expensive computations. Publishing Websites enumerates the various options for publishing your book as a website including GitHub Pages, Netlify, and RStudio Connect.
{ "lastmod": "2023-07-05T19:35:15.255Z", "loc": "https://quarto.org/docs/books/index.html", "source": "https://quarto.org/docs/books/index.html" }
Quarto is open source software licensed under the GNU GPL v2. We believe that it’s better for everyone if the tools used for research and science are free and open. Reproducibility, widespread sharing of knowledge and techniques, and the leveling of the playing field by eliminating cost barriers are but a few of the shared benefits of free software in science. The Quarto source code is available at https://github.com/quarto-dev/ Quarto is a registered trademark of Posit. Please see our trademark policy for guidelines on usage of the Quarto trademark. Quarto also makes use of several other open-source projects, the distribution of which is subject to their respective licenses. Major components and their licenses include: Project License Pandoc GNU GPL v2 Bootstrap 5.1 MIT Bootswatch 5.1 MIT Deno MIT esbuild MIT Dart Sass MIT Observable Runtime ISC
{ "lastmod": "2023-07-05T19:35:16.055Z", "loc": "https://quarto.org/license.html", "source": "https://quarto.org/license.html" }
We want to hear about Quarto bugs and, we want to fix those bugs! The following guidance will help us be as efficient as we can. Rule 0: Please submit your bug report anyway! We have a better chance to fix your code quickly if you follow the instructions below. Still, we know that this takes work and isn’t always possible. We would rather have a record of the problem than not know about it. We appreciate bug reports even if you are unable to take any or all of the following steps: Small is beautiful: Aim for a single document with ~10 lines The most helpful thing you can do to help us is to provide a minimal, self-contained, and reproducible example. minimal: This will often mean turning your large website project into a project with a single small document, and a single large .qmd file into a small (ideally, about 10-20 total lines of code) example. By doing this, you might also be able to learn more specifically what the problem is. self-contained: The more software dependencies we need to understand and install, the harder it is to track the bug down. As you reduce the code, remove as many dependencies as possible. reproducible: If we cannot run your example, we cannot track the bug down. Please make sure the file you submitted is enough to trigger the bug on its own. Formatting: Make GitHub’s markdown work for us The easiest way to include a .qmd file in a comment is to wrap it in a code block. To make sure that GitHub doesn’t format your own .qmd, start and end your block with more backticks than you use in your .qmd file. In order to show .qmd files with three backticks (the most common case), use four backticks in your GitHub Issue: ``` This is a code block ``` Sometimes you might need more backticks: ```` This is a four backticks block. ``` This is a code block ``` ```` Don’t hold back: Tell us anything you think might make a difference Although we want the .qmd file to be small, we still can use as much information from you as you’re willing to share. Tell us all!, including: The version of quarto you’re running The operating system you’re running The IDE you’re using, and its version If you are seeing an error from Quarto, you can also provide additional diagnostic information by defining the QUARTO_PRINT_STACK environment variable. For example on Unix: export QUARTO_PRINT_STACK=true quarto render document.qmd or on Windows in a Powershell Terminal $ENV:QUARTO_PRINT_STACK="true" quarto render document.qmd
{ "lastmod": "2023-07-05T19:35:15.135Z", "loc": "https://quarto.org/bug-reports.html", "source": "https://quarto.org/bug-reports.html" }