Notebook Filters

Overview

Whenever you use Jupyter for embedded computations a notebook (.ipynb) is part of the rendering pipeline. This is naturally the case for rendering .ipynb files directly, however it is also the case for .qmd files that have embedded Julia or Python cells (in which case a temporary .ipynb is constructed). This notebook is ultimately converted into markdown and then rendered by Pandoc to the specified output format(s).

You may wish to do some pre-processing on the notebook prior to its conversion to markdown. This can be accomplished by specifying one or or more ipynb-filters. These filters are passed the JSON representation of the notebook on stdin and should write a transformed JSON representation to stdout.

Example

For example, this notebook filter uses the nbformat package to read a notebook, prepend a comment to the source of each code cell, and then write it back to stdout:

import sys
import nbformat

# read notebook from stdin
nb = nbformat.reads(sys.stdin.read(), as_version = 4)

# prepend a comment to the source of each cell
for index, cell in enumerate(nb.cells):
  if cell.cell_type == 'code':
     cell.source = "# comment\n" + cell.source
  
# write notebook to stdout 
nbformat.write(nb, sys.stdout)

You can arrange for this filter to be run using the ipynb-filters option (specified at either the document or project level):

---
ipynb-filters:
  - filter.py
---

Note that the current working directory for the filter will be set to the location of the input notebook.