---
title: Writing fastship plugins
description: How to customize fastship processors to do what you want
order: 9
---
<!-- WARNING: THIS FILE WAS AUTOGENERATED! DO NOT EDIT! -->

## Export processors

The [`Processor`](../api/process.md#processor) class shown later is for **doc processors** — they transform notebooks when building documentation with `ship-docs`.

First though we'll discuss the simpler kind of processor: **export processors** — they transform code cells when exporting to `.py` files with `ship-export`. These are just plain functions, not classes.

### Built-in export processor: [`scrub_magics`](../api/maker.md#scrub_magics)

fastship includes one export processor out of the box: [`scrub_magics`](../api/maker.md#scrub_magics). It removes Jupyter magic lines (like `%%time`, `%matplotlib inline`, `%%spark`) from your exported `.py` files.

To enable it, add to your `pyproject.toml`:

```toml
[tool.fastship]
export_procs = ["fastship.maker:scrub_magics"]
```

For example, a cell like this:

```python
%%time
#| export
def my_func(): return 42
```

Will export without the `%%time` line.

### Writing an export processor

An export processor is a function that receives a notebook cell and modifies it in place:

```python
def my_export_proc(cell):
    "Transform code cells during export"
    if cell.cell_type != 'code': return
    # Modify cell.source as needed
    cell.source = transform(cell.source)
```

For example, here's a formatter using `black`:

```python
# nbdev_black/__init__.py
def black_format(cell):
    "Format code cells with black"
    if cell.cell_type != 'code': return
    try:
        import black
        cell.source = black.format_str(cell.source, mode=black.Mode())
    except: pass  # Leave malformed code unchanged
```

### Enabling export processors

Add `export_procs` to your `pyproject.toml`:

```toml
[tool.fastship]
export_procs = ["nbdev_black:black_format"]
```

You can chain multiple processors — they run in order:

```toml
[tool.fastship]
export_procs = [
    "nbdev_black:black_format",
    "my_project.procs:my_custom_proc",
]
```

### Key differences from doc processors

|  | Doc processors | Export processors |
|--- |--- |--- |
| **Used by** | `ship-docs` | `ship-export` |
| **Interface** | [`Processor`](../api/process.md#processor) class with `cell()` method | Simple function |
| **Config key** | `doc_procs` | `export_procs` |
| **Purpose** | Transform notebooks for documentation | Transform code for `.py` files |

## Doc processors

### What will this cover?

With `fastship`, it's possible to customize and extend it further beyond the standard capabilities through a well thoughtout and scalable framework. Does your particular library or need require you to inject custom quarto additives in certain cells? What about if you want to do something more trivial such as finding shortcuts to replace complicated quarto directives more easily (such as replacing `::: {.column-margin}` with `#| margin`)?

Writing custom plugins with `fastship` is the easiest method to achieve this, and with this tutorial we will bring you up to speed on how you can use this to create your own plugins to expand and simplify your literate-programming experience with `fastship` and quarto.

Specifically, we will be building a *processor* (something that processes a notebook cell) that will let us quickly write out any quarto-specific headers (that `::: {.some_annotation}`) and replace it with a `div` shortcut. This is of course one example very specific to quarto that happens when building the documentation, but this technique can be used to have custom behaviors occur during library exportation as well.

> Note: We are using `div` here is it more closely resembles how each of the related Quarto directives do and behave as they act like `<div>`s in HTML code

This tutorial *won't* cover some of the basics when it comes to fastship, and instead comes with the understanding you know how to navigate fastship (such as what are [directives](https://ship.fast.ai/explanations/directives.html), [`export`](https://ship.fast.ai/explanations/directives.html#export-some.thing), etc).

### Getting started, how does `fastship` make this easy?

First let's visualize just what we're trying to achieve.

Instead of doing the following code which will add `"Some text"` to the sidebar (as shown off to the side currently):

Some text

```
::: {.column-margin}
Some text
:::
```

We will create a shorter way to write this out, making use of how fastship and quarto writes their *directives*

By the end of this tutorial we will create something that looks like the following:

```
#| div column-margin

Some text
```

And this will include cases where a `div` should be put across *multiple* cells as well, by specifying a `start` and an `end`.

> Note: Check out the [article layout](https://quarto.org/docs/authoring/article-layout.html) Quarto documentation to find the best examples of use cases for this custom directive, including the [`column-margin`](https://quarto.org/docs/authoring/article-layout.html#margin-content) just shown

This can be achieved in under 50 lines of code!

`fastship` let's us create what are called *processors* (this is how `#| export` will shove code into modules, for example). These processors are acted on each **cell** of a notebook and can modify its contents. These can then be wrapped into a module the same way that fastship will do `ship-export` or `ship-docs`. Thanks to the power of writing custom `fastship` extensions,  going deep into the inner-workings of the framework isn't required!

### Bringing in what we need

The actual imports we need to use from `fastship` is truly not that many! We just need one: the [`Processor`](../api/process.md#processor) class that will actually perform what we want on notebook cells. Reading `#|` directives needs no import at all, since every notebook cell carries them in its `directives` property.

The rest of the imports are there to make some of our lives easier as will be explained later

```python
from fastship.processors import Processor

from fastcore.basics import listify

from string import Template
```

Lastly for *testing* purposes we'll utilize `fastship`'s `mk_cell` function and the [`NBProcessor`](../api/process.md#nbprocessor) class, which will let us mock running our processor on a "real" notebook!

```python
from fastship.processors import mk_cell, NBProcessor
```

### Writing a converter

The first step is creating a quick and easy way to take the `fastship` directive we want to use (such as `#| div column-margin`) and convert it quickly into something quarto will then read (such as `::: {.column-margin}`).

We can create a string `Template` to perform this for us:

```python
_LAYOUT_STR = Template("::: {.$layout}\n${content}\n")
```

> [!TIP]
> This doesn't have to be a string template, I just found this the easiest to use!

```python
_LAYOUT_STR.substitute(
    layout="column-margin",
    content="Some text to go on the sidebar"
)
```

```output
'::: {.column-margin}\nSome text to go on the sidebar\n'
```

Next we need to write a simple converter that operates at the *cell* level:

```python
def convert_layout(
    cell:dict, # A single cell from a Jupyter Notebook
    is_multicell=False # Whether the div should be wrapped around multiple cells
):
    "Takes a code cell that contains `div` in the directives and modifies the contents to the proper Quarto format"
    div_ = cell.directives_["div"].split()
    # By the time procs run, the pipeline has stripped directive lines from the source
    if "end" in div_: cell.source = ":::"
    else:
        if "start" in div_: div_.remove("start")
        cell.source = _LAYOUT_STR.substitute(layout=" ".join(div_), content=cell.source)
        if not is_multicell: cell.source += ":::"
```

Let's go into detail on what's happening here.

```python
    content = cell.source
```

The source text of whatever exists in a notebook cell will live in `.source`.

```python
    code = cell.source.splitlines(True)
```

Then I want to extract the content of the cell and split them into multiple lines, seperated by newlines. This let's us check if a cell just contains `#| div end`, which means that the div that was started earlier should stop.

```python
    div_ = cell.directives_["div"]
```

Any directives (comments in any cell marked with ` #|  `) will exist in the `directives_` attribute as a dictionary. For our particular processor we only care about the `div` directive

```python
    if "end" in div_:
        # If it is, just fill the text with `:::` if no code exists there
        cell.source = ":::" if len(code) == 1 else f'{code.source}:::'
    else:
        # Actually modify the code
        cell.source = _LAYOUT_STR.substitute(layout=" ".join(div_), content=content)
        if not is_multicell: cell.source += ":::"
```

From there this last part checks whether to add the ending `:::` block to the cell or to use the `_LAYOUT_STR` and inject the boilerplate div CSS code in for Quarto.

Let's see it in action:

```python
cell = mk_cell(
    """#| div margin-column
Here is something for the sidebar!""",
    cell_type="markdown"
)
cell.directives_ = cell.directives  # NBProcessor sets this snapshot before procs run
```

Cells parse their own directives, available as a plain dict through the `directives` property:

```python
cell.directives
```

```output
{'div': 'margin-column'}
```

And now we can test out if our `convert_layout` function works!

```python
cell.remove_directives()  # the pipeline strips directives before procs run
convert_layout(cell)
print(cell.source)
```

```output
::: {.margin-column}
Here is something for the sidebar!
:::
```

> Note: I print the `cell.source` here so that it's text looks cleaner and what we would visually see in a `Markdown` cell

Looks exactly like we wanted earlier! Great!

How do we tell fastship to use this and create this [`Processor`](../api/process.md#processor) class mentioned earlier?

### Writing a [`Processor`](../api/process.md#processor)

The second-to-last step here is to create the custom [`Processor`](../api/process.md#processor) fastship utilizes to apply procs (things that modify the contents of cells). The basic understanding of these is simply that you should create a class, have it inherit [`Processor`](../api/process.md#processor), and any modifications that should be done must be defined in a `cell` function which takes in a `cell` and modifies it in-place.

Inside a processor, read directives from `cell.directives_` (with the underscore), not the `directives` property: the pipeline strips directives from cell sources before procs run, so the property would re-parse the stripped source and come up empty. `directives_` is the snapshot the pipeline took first.

```python
class LayoutProc(Processor):
    "A processor that will turn `div` based tags into proper quarto ones"
    has_multiple_cells = False
    def cell(self, cell):
        if cell.cell_type == "markdown" and "div" in cell.directives_:
            div_ = cell.directives_["div"].split()
            if self.has_multiple_cells and "end" in div_:
                convert_layout(cell)
            else:
                is_start = div_[-1] == "start"
                if is_start: self.has_multiple_cells = True
                convert_layout(cell, is_start)
```

How can we test if this will work or not?

A minimal Jupyter Notebook is just a dictionary where the cells are in a `cells` key and the cells themselves are a list of notebook cells following a special format. We've created one of these above. `fastship` has a `dict2nb` function which let's us convert this minimal idea of a Jupyter Notebook into the true thing quickly.

Afterwards, we can apply the processor to those cells though the [`NBProcessor`](../api/process.md#nbprocessor) class (what `fastship` uses to apply these)

```python
from fastship.process import NBProcessor, dict2nb
```

```python
nb = {
    "cells":[
    mk_cell("""#| div column-margin
A test""", "markdown"),
    mk_cell("""#| div column-margin start
A test""", "markdown"),
    mk_cell("""#| div end""", "markdown"),
]}
```

The `mk_cell` function will create a cell based on some `content` and a `cell type`. The particular extension we've built works off `Markdown` cells, so we set the type as `markdown`.

The [`NBProcessor`](../api/process.md#nbprocessor) takes in a list of procs (processors) that should be applied, and an opened Jupyter Notebook:

```python
processor = NBProcessor(procs=LayoutProc, nb=dict2nb(nb))
```

The act of applying these processors is done through calling the `.process():` function

```python
processor.process()
```

And now we can see that those code cells were changed:

```python
for i in range(3):
    print(f"Before:\n{nb['cells'][i].source}\n")
    print(f"After:\n{processor.nb.cells[i].source}\n")
```

```output
Before:
#| div column-margin
A test

After:
::: {.column-margin}
A test
:::

Before:
#| div column-margin start
A test

After:
::: {.column-margin}
A test


Before:
#| div end

After:
:::
```

Great! We've successfully created a plugin for fastship that will let us lazily write markdown quarto directives easily. How can we actually *use* this in our projects?

### How to enable the plugin on your project

This requires adding a `doc_procs` key to `[tool.fastship]` in your `pyproject.toml`.

For example, if this were code that lived in `fastship`, we can specify where the processor comes from:

```toml
[tool.fastship]
doc_procs = ["nbdev.extensions:LayoutProc"]
```

It follows the format of `library.module:ProcessorClass`

If this were being used from an external library (such as how this processor is based on the one that lives in [nbdev-extensions](https://muellerzr.github.io/nbdev-extensions)), you should add that to the dependencies of your project:

```toml
[project]
dependencies = ["nbdev-extensions"]
```

And you're done! Now when calling `ship-docs` or `ship-preview` the processor we just made will be *automatically* applied to your notebooks and perform this conversion!

### Conclusion

Basically if there's any part of a cell and how it should look either from exporting modules, building documentation, or creating your own special command to perform post-processing it can be done quickly and efficiently with this [`Processor`](../api/process.md#processor) class fastship provides!

Zachary Mueller has written a library dedicated to it called [nbdev-extensions](https://muellerzr.github.io/nbdev-extensions) where any ideas that may benefit how I approach fastship I then turn into an extension for the world to use.
