[go: up one dir, main page]

How to Use Prettier to Format Quarto Documents

Prettified plaintext properly prepares posh powerful publications

programming
quarto
tooling
tutorial
Author

Vincent “VM” Mercator

Published

April 11, 2024

Modified

July 28, 2024

A series of icons spelling the rebus 'Prettier plus Quarto equals relaxed'.

Prettier is a JavaScript program that makes my code, docs, and articles… well… prettier.

I like opinionated code formatters and style guides because they provide consistent standards for how to write code. Running version control on opinionatedly formatted files makes tracking changes easier, since there are fewer ways to arrange the same sequence of code symbols. For HTML, CSS, JavaScript, Markdown, & YAML files, Prettier is my go-to tool for the job. While its default behavior is incompatible with the Quarto Markdown files that contain my website’s technical articles, I’ve configured Prettier to play nicely with Quarto so that all my documents are consistently formatted regardless of their file type.

Tutorial Prerequisites

Prettier is a JavaScript library available in the NPM package repository, so you can either download it as part of your IDE or directly using the npm command-line tool.

If you use Git as your version control system like I do, you can use a third-party package like Pre-Commit to create a commit hook for Prettier.

Configuring Prettier’s Project-Level Behavior

Regardless of whether you use Prettier in VS Code or not, you can change its behavior when it’s run on a file inside a project folder with a .prettierrc configuration file written in JSON, YAML, or TOML.1 Specifying the project-level Prettier configuration ensures that it will adhere to the same style guide regardless of what computer it’s run on. For this example, let’s say that you have a project directory called my_project with two files: test.md and test2.qmd.

  📂 my_project
  ├ 📄 test.md
  └ 📄 test2.qmd

If you want to configure Prettier to format both Markdown and Quarto files for this project, then you can add a Prettier configuration file like one of the two below to override its default behavior for Quarto files.2 When run, Prettier will format both documents according to the settings laid out in the configuration file.

Warning

Using the prettier command with the --write option will format the files in-place, overwriting their contents. Make sure that you have a backup or use version control before doing any mass formatting.

my_project/.prettierrc.yml
# Some example settings
proseWrap: "always"
semi: true
singleQuote: false
tabWidth: 2
trailingComma: "es5"
# ...
overrides:
  # Format QMD files as MD files
  - files: "**.qmd"
    options:
      parser: "markdown"
BASH Terminal
[me@pc my_project]$ ls -a
.  ..  .prettierrc.yml  test.md  test.qmd
[me@pc my_project]$ npx prettier . --write
.prettierrc.yml 67ms (unchanged)
test.md 54ms
test2.qmd 9ms
my_project/.prettierrc.json
{
  "proseWrap": "always",
  "semi": true,
  "singleQuote": false,
  "tabWidth": 2,
  "trailingComma": "es5",
  "overrides": [
    {
      "files": "**.qmd",
      "options": {
        "parser": "markdown"
      }
    }
  ]
}
BASH Terminal
[me@pc my_project]$ ls -a
.  ..  .prettierrc.json  test.md  test.qmd
[me@pc my_project]$ npx prettier . --write
.prettierrc.json 67ms (unchanged)
test.md 54ms
test2.qmd 9ms

Configuring Prettier for Quarto in VS Code

Before registering Prettier as a formatter for Quarto files in VS Code, you must first add the Prettier configuration file to your project’s directory as shown in the previous section. Then, you can configure VS Code to recognize Prettier as a formatter for Quarto files by using adding the following snippet to your VS Code settings.json configuration file.

settings.json
{
  "prettier.documentSelectors": ["**/*.qmd"]
}

Now, you can select formatting with either Quarto’s built-in VS Code formatter or Prettier.

Configuring Prettier for Quarto in Neovim

Vanilla Neovim can’t automatically format documents, but the conform.nvim extension by Steven Arcangeli can.

The official quarto-nvim plugin for VS Code creates the “quarto” file type for Neovim, which you can use for filetype-specific plugin configurations. If you either use LazyVim or the Lazy plugin manager, you can slot this code snippet into your Neovim configuration so that conform recognizes Prettier as Quarto’s formatter. That way, Quarto documents will get formatted like Markdown documents.

~/.config/nvim/lua/plugins/conform-nvim.lua
return {
    "stevearc/conform.nvim",
    ---@class ConformOpts
    opts = {
        formatters = {
            -- Prettier configuration in conform.nvim
            prettier = {
                options = {
                    ext_parsers = {
                        qmd = "markdown",
                    },
                },
            },
        },
        formatters_by_ft = {
            -- ...
            quarto = { "prettierd", "prettier" },
            -- ...
        },
    },
}

Prettier as a Commit Hook

In a Git project’s .git folder, the hooks folder contains example scripts that can be configured to trigger whenever important actions like committing code. The Pre-Commit Python package provides an easy way to manage these hooks across different contributors to the same project. We can use Pre-Commit to configure Git to automatically format new or modified documents with Prettier.

Here’s an excerpt of a pre-commit-config.yml configuration file that will run Prettier on the project. It goes in the project’s directory.

Note

As of 2024-04-11, the Official Pre-Commit plugin for Prettier is now deprecated. This Pre-Commit hook instead runs Prettier locally on the host machine with the same settings as the original plugin.

my_project/pre-commit-config.yml
repos:
  # ...
  - repo: local
    hooks:
      - id: prettier
        name: prettier
        description: Prettier is an opinionated code formatter.
        language: system
        entry: prettier --write --ignore-unknown
        types: [text]
  # ...

Now, whenever you commit code to your Git repository, Pre-Commit will automatically run Prettier to ensure that the code is properly formatted.

BASH Terminal
[me@pc my_project]$ pre-commit install
pre-commit installed at .git/hooks/pre-commit
[me@pc my_project]$ pre-commit
...
prettier.................................................................Passed
...

Quarto Markdown Compatibility Issues

There are lots of variants of the original Markdown syntax, each with different sets of features. While Prettier is designed for the GitHub-flavored Markdown and MDX specifications, Quarto Markdown documents use Pandoc Markdown.

For example, Prettier’s automatic formatting might break fenced divs in Pandoc Markdown, since that syntax doesn’t exist in the Markdown flavors it’s built for. To get around this issue, you can use double-space line breaks or empty lines to separate the triple-colon div fences.

Example text.

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

Example text.

Example text.

Note

This is a note.

Example text.

Example text.

:::{.callout-note}

This is a note.

:::

Example text.

Example text.

Note

This is a note.

Example text.

For more complicated Pandoc Markdown syntax like line blocks and grid tables, You can delineate sections that shouldn’t be formatted by Prettier using the <!-- prettier-ignore-start --> and <!-- prettier-ignore-end --> comments like in the example below.

<!-- prettier-ignore-start -->

+---------------------+----------+
| Property            | Earth    |
+=============+=======+==========+
|             | min   | -89.2 °C |
| Temperature +-------+----------+
| 1961-1990   | mean  | 14 °C    |
|             +-------+----------+
|             | max   | 56.7 °C  |
+-------------+-------+----------+

<!-- prettier-ignore-end -->
Property Earth
Temperature 1961-1990 min -89.2 °C
mean 14 °C
max 56.7 °C

With Prettier properly configured, all your Quarto documents will be consistently formatted.

Footnotes

  1. I recommend using the YAML configuration since Prettier can format that file type out-of-the-box.↩︎

  2. I’m not sure if it’s possible to set overrides for Prettier in a TOML configuration file, since there is no example in the documentation.↩︎

Reuse

CC BY SA 4.0 International License(View License)