4. Output formats

When the source is parsed, and has been processed it is time to render the output. We will consider the following source snippet:

# # Rational numbers
#
# In julia rational numbers can be constructed with the `//` operator.
# Lets define two rational numbers, `x` and `y`:

x = 1//3
#-
y = 2//5

# When adding `x` and `y` together we obtain a new rational number:

z = x + y

and see how this is rendered in each of the output formats.

4.1. Markdown output

Markdown output is generated by Literate.markdown. There exist various "flavors" of markdown and Literate supports some different flavors, see Markdown flavors. The default flavor is Literate.DocumenterFlavor() and, as the name suggest, it generates markdown files meant to be used together with Documenter.jl. The output of the source snippet above is as follows:

```@meta
EditURL = "../outputformats.jl"
```

# Rational numbers

In julia rational numbers can be constructed with the `//` operator.
Lets define two rational numbers, `x` and `y`:

````@example name
x = 1//3
````

````@example name
y = 2//5
````

When adding `x` and `y` together we obtain a new rational number:

````@example name
z = x + y
````

We note that lines starting with # are printed as regular markdown, and the code lines have been wrapped in @example blocks. We also note that an @meta block have been added, that sets the EditURL variable. This is used by Documenter to redirect the "Edit on GitHub" link for the page, see Interaction with Documenter.

The @example blocks are wrapped in 4 consecutive backticks so as to allow for docstrings containing triple backticks, for example:

"""
This function perform the following calculation:
```math
    x_1 + x_2
```
"""
f(x) = x[1] + x[2]

If your Julia code itself contains 4 consecutive backticks, you can use the keyword argument codefence to setup 5 backticks for code blocks, see Configuration.

It possible to configure Literate.markdown to also evaluate code snippets, capture the result and include it in the output, by passing execute=true as a keyword argument. The result of the first code-block in the example above would then become

````julia
x = 1//3
````
````
1//3
````

In this example the output is just plain text. However, if the resulting value of the code block can be displayed as an image (image/png or image/jpeg), HTML (text/html) or markdown (text/markdown) Literate will include the richest representation of the output.

Note

Since Documenter executes and captures results of @example block it is not necessary to use execute=true for markdown output that is meant to be used as input to Documenter.

See the section about Configuration for more information about how to configure the behavior and resulting output of Literate.markdown.

Literate.markdownFunction
Literate.markdown(inputfile, outputdir=pwd(); config::AbstractDict=Dict(), kwargs...)

Generate a markdown file from inputfile and write the result to the directory outputdir.

See the manual section on Configuration for documentation of possible configuration with config and other keyword arguments.

source

Markdown flavors

Literate can output markdown in different flavors. The flavor is specified using the flavor keyword argument. The following flavors are currently supported:

  • flavor = Literate.DocumenterFlavor(): this is the default flavor and the output is meant to be used as input to Documenter.jl.
  • flavor = Literate.CommonMarkFlavor(): this outputs markdown that has the flavor of the CommonMark specification.
  • flavor = Literate.FranklinFlavor(): this outputs markdown meant to be used as input to Franklin.jl.
  • flavor = Literate.QuartoFlavor(): this outputs markdown file (with file extension .qmd) meant to be used with Quarto CLI.

Quarto flavor

Experimental feature

Quarto markdown output is marked as and experimental feature since it has not been widely tested. Quarto-specific syntax may change before Literate version 3 depending on what the community wants and/or needs. If you use this flavor non-interactively (such as automatically building documentation) it is recommended to pin Literate to a good known version.

Quarto is an open-source scientific and technical publishing system, which can extend the range of output formats from your Literate.jl-formatted scripts. Literate.jl will produce a .qmd file, which can be used as input to Quarto CLI to produce a variety of output formats, including HTML, PDF, Word and RevealJS slides.

Literate + Quarto syntax tips
  • #(hashtag followed by a space) at the beginning of a line will be stripped and anything that follows will rendered as a markdown, e.g., # # Header level 1 in your script will be rendered as # Header level 1 in your .qmd file (ie, it will show as a header). Use this for adding the YAML header at the top or any Markdown blocks in the Quarto guide.
  • ##|(two hashtags followed by a pipe) at the beginning of a line will strip the first hashtag and interpret the remainder of the line as part of the code block. This is useful to provide Quarto commands in computation blocks, e.g., ##! echo: false would be rendered as #| echo: false and would tell Quarto not to "echo" the outputs of the execution (see Guide: Executions options for more commands).
  • Make sure to always provide the YAML header and specify IJulia kernel when executing the file by Quarto, e.g.,
    # ---
    # title: "My Report"
    # jupyter: julia-1.9
    # ---
    Notice how all lines are escaped with a # so Literate.jl knows to strip the hashtags and render it as markdown (see Authoring Tutorial for more examples)
  • If any markdown components (e.g. headers) are not rendering correctly in your Quarto outputs, make sure they are surrounded by empty lines (e.g., add an empty line before and after the header) to help Quarto parse them correctly
Configuring Quarto for Julia code execution
  • Install Quarto CLI
  • Run quarto check to ensure all is installed correctly (you will need Python, Jupyter, and IJulia kernel, see Getting Started)
Steps to create reports
  • Make sure you have the right header specifying which IJulia kernel to use (e.g. jupyter: julia-1.9), otherwise Quarto will use the default Python kernel.
  • Convert your Literate.jl script to a .qmd file, e.g.
    Literate.markdown("my_script.jl", flavor = Literate.QuartoFlavor())
  • Run Quarto CLI to produce your desired output format, e.g.
    quarto render my_script.qmd --to html

4.2. Notebook output

Notebook output is generated by Literate.notebook. The (default) notebook output of the source snippet can be seen here: notebook.ipynb.

We note that lines starting with # are placed in markdown cells, and the code lines have been placed in code cells. By default the notebook is also executed and output cells populated. The current working directory is set to the specified output directory the notebook is executed.

See the section about Configuration for how to configure the behavior and resulting output of Literate.notebook.

Literate.notebookFunction
Literate.notebook(inputfile, outputdir=pwd(); config::AbstractDict=Dict(), kwargs...)

Generate a notebook from inputfile and write the result to outputdir.

See the manual section on Configuration for documentation of possible configuration with config and other keyword arguments.

source

Notebook metadata

Jupyter notebook cells (both code cells and markdown cells) can contain metadata. This is enabled in Literate by the %% token, similar to Jupytext. The format is as follows

%% optional ignored text [type] {optional metadata JSON}

Cell metadata can, for example, be used for nbgrader and the reveal.js notebook extension RISE.

The following would create a 3 slide deck with RISE:

#nb # %% A slide [markdown] {"slideshow": {"slide_type": "slide"}}
# # Some title
#
# We're using `#nb` so the metadata is only included in notebook output

#nb %% A slide [code] {"slideshow": {"slide_type": "fragment"}}
x = 1//3
y = 2//5

#nb # %% A slide [markdown] {"slideshow": {"slide_type": "subslide"}}
# For more information about RISE, see [the docs](https://rise.readthedocs.io/en/stable/usage.html)

4.3. Script output

Script output is generated by Literate.script. The (default) script output of the source snippet above is as follows:

x = 1//3

y = 2//5

z = x + y

We note that lines starting with # are removed and only the code lines have been kept.

See the section about Configuration for how to configure the behavior and resulting output of Literate.script.

Literate.scriptFunction
Literate.script(inputfile, outputdir=pwd(); config::AbstractDict=Dict(), kwargs...)

Generate a plain script file from inputfile and write the result to outputdir.

See the manual section on Configuration for documentation of possible configuration with config and other keyword arguments.

source

4.4. Configuration

The behavior of Literate.markdown, Literate.notebook and Literate.script can be configured by keyword arguments. There are two ways to do this; pass config::Dict as a keyword argument, or pass individual keyword arguments.

Configuration precedence

Individual keyword arguments take precedence over the config dictionary, so for e.g. Literate.markdown(...; config = Dict("name" => "hello"), name = "world") the resulting configuration for name will be "world". Both individual keyword arguments and the config dictionary take precedence over the default.

Available configurations with description and default values are given in the reference for Literate.DEFAULT_CONFIGURATION just below.

Literate.DEFAULT_CONFIGURATIONConstant
DEFAULT_CONFIGURATION

Default configuration for Literate.markdown, Literate.notebook and Literate.script which is used for everything not specified by the user. Configuration can be passed as individual keyword arguments or as a dictionary passed with the config keyword argument. See the manual section about Configuration for more information.

Available options:

  • name (default: filename(inputfile)): Name of the output file (excluding the file extension).
  • preprocess (default: identity): Custom preprocessing function mapping a String to a String. See Custom pre- and post-processing.
  • postprocess (default: identity): Custom preprocessing function mapping a String to a String. See Custom pre- and post-processing.
  • credit (default: true): Boolean for controlling the addition of This file was generated with Literate.jl ... to the bottom of the page. If you find Literate.jl useful then feel free to keep this.
  • keep_comments (default: false): When true, keeps markdown lines as comments in the output script. Only applicable for Literate.script.
  • execute (default: true for notebook, false for markdown): Whether to execute and capture the output. Only applicable for Literate.notebook and Literate.markdown.
  • continue_on_error (default: false): Whether to continue code execution of remaining blocks after encountering an error. By default execution errors are re-thrown. If continue_on_error = true the error will be used as the output of the block instead and execution will continue. This option is only applicable when execute = true.
  • codefence (default: "````@example $(name)" => "````" for DocumenterFlavor() and "````julia" => "````" otherwise): Pair containing opening and closing code fence for wrapping code blocks.
  • flavor (default: Literate.DocumenterFlavor()) Output flavor for markdown, see Markdown flavors. Only applicable for Literate.markdown.
  • devurl (default: "dev"): URL for "in-development" docs, see Documenter docs. Unused if repo_root_url/ nbviewer_root_url/binder_root_url are set.
  • softscope (default: true for Jupyter notebooks, false otherwise): enable/disable "soft" scoping rules when executing, see e.g. https://github.com/JuliaLang/SoftGlobalScope.jl.
  • repo_root_url: URL to the root of the repository. Determined automatically on Travis CI, GitHub Actions and GitLab CI. Used for @__REPO_ROOT_URL__.
  • nbviewer_root_url: URL to the root of the repository as seen on nbviewer. Determined automatically on Travis CI, GitHub Actions and GitLab CI. Used for @__NBVIEWER_ROOT_URL__.
  • binder_root_url: URL to the root of the repository as seen on mybinder. Determined automatically on Travis CI, GitHub Actions and GitLab CI. Used for @__BINDER_ROOT_URL__.
  • image_formats: A vector of (mime, ext) tuples, with the default Tuple{MIME, String}[(MIME type image/svg+xml, ".svg"), (MIME type image/png, ".png"), (MIME type image/jpeg, ".jpeg")]. Results which are showable with a MIME type are saved with the first match, with the corresponding extension.
source